@lunora/client 0.0.0 → 1.0.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE.md +105 -0
  2. package/README.md +113 -9
  3. package/__assets__/package-og.svg +14 -0
  4. package/dist/auth/index.d.mts +20 -0
  5. package/dist/auth/index.d.ts +20 -0
  6. package/dist/auth/index.mjs +60 -0
  7. package/dist/index.d.mts +385 -0
  8. package/dist/index.d.ts +385 -0
  9. package/dist/index.mjs +15 -0
  10. package/dist/packem_shared/CONFLICT_ERROR_CODE-aUdVbEDw.mjs +4 -0
  11. package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +107 -0
  12. package/dist/packem_shared/LunoraClient-CgZ6FhKP.mjs +2721 -0
  13. package/dist/packem_shared/OfflineQueue-BI0FNNvc.mjs +1 -0
  14. package/dist/packem_shared/SKIP-vItZChkw.mjs +50 -0
  15. package/dist/packem_shared/SubscriptionRegistry-Dn-7k7eo.mjs +1 -0
  16. package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +61 -0
  17. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +45 -0
  18. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +11 -0
  19. package/dist/packem_shared/createInMemoryPersistence-CW82inU5.mjs +105 -0
  20. package/dist/packem_shared/createInMemoryQueryCache-B1PQ9Twl.mjs +138 -0
  21. package/dist/packem_shared/createLocalStore-IOur0jHF.mjs +1 -0
  22. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +21 -0
  23. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +31 -0
  24. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +22 -0
  25. package/dist/packem_shared/createServerClient-BxkNcRlR.mjs +11 -0
  26. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +4 -0
  27. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +13 -0
  28. package/dist/packem_shared/local-store-BNgN3Dw3.mjs +111 -0
  29. package/dist/packem_shared/lunora-client.d-B5vWSgvD.d.mts +2196 -0
  30. package/dist/packem_shared/lunora-client.d-B5vWSgvD.d.ts +2196 -0
  31. package/dist/packem_shared/offline-queue-7Wc4onA0.mjs +164 -0
  32. package/dist/packem_shared/preload.d-3XJD-2hM.d.mts +20 -0
  33. package/dist/packem_shared/preload.d-CKZR675M.d.ts +20 -0
  34. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +13 -0
  35. package/dist/packem_shared/subscription-C1Jy7HiF.mjs +55 -0
  36. package/dist/pagination/index.d.mts +82 -0
  37. package/dist/pagination/index.d.ts +82 -0
  38. package/dist/pagination/index.mjs +61 -0
  39. package/dist/query/index.d.mts +62 -0
  40. package/dist/query/index.d.ts +62 -0
  41. package/dist/query/index.mjs +1 -0
  42. package/dist/ssr/index.d.mts +115 -0
  43. package/dist/ssr/index.d.ts +115 -0
  44. package/dist/ssr/index.mjs +4 -0
  45. package/package.json +53 -17
@@ -0,0 +1,2721 @@
1
+ import { S as SubscriptionRegistry, s as stableStringify } from './subscription-C1Jy7HiF.mjs';
2
+ import createInMemoryBookmarkStorage from './createInMemoryBookmarkStorage-BoN7a7TH.mjs';
3
+ import { isMutationDelta, applyDelta } from './applyDelta-4jFGTPA3.mjs';
4
+ import { a as applyOptimisticLayer, d as dropConfirmedLayers, n as notifySubscription, f as foldOptimistic, c as createLocalStore } from './local-store-BNgN3Dw3.mjs';
5
+ import { O as OfflineQueue, n as nextId, i as isStaleVersion, r as reportPersistenceError } from './offline-queue-7Wc4onA0.mjs';
6
+ import { queryCacheKey } from './createInMemoryQueryCache-B1PQ9Twl.mjs';
7
+ import { createReconnect } from './createReconnect-Di_-oHH7.mjs';
8
+ import { createStream } from './DEFAULT_MAX_BUFFER-BDkqO5PW.mjs';
9
+
10
+ class Listeners {
11
+ listeners = /* @__PURE__ */ new Set();
12
+ add(listener) {
13
+ this.listeners.add(listener);
14
+ return () => {
15
+ this.listeners.delete(listener);
16
+ };
17
+ }
18
+ // The conditional rest tuple makes `emit()` argument-free for a
19
+ // `Listeners<void>` and one-argument for every other payload.
20
+ // eslint-disable-next-line @typescript-eslint/no-invalid-void-type -- `[T] extends [void]` is the discriminant for the payload-free overload, not a value-position void
21
+ emit(...args) {
22
+ const [value] = args;
23
+ for (const listener of this.listeners) {
24
+ try {
25
+ listener(value);
26
+ } catch {
27
+ }
28
+ }
29
+ }
30
+ clear() {
31
+ this.listeners.clear();
32
+ }
33
+ }
34
+
35
+ const RPC_PATH = "/_lunora/rpc";
36
+ const WS_PATH = "/_lunora/ws";
37
+ const bucketQuery = (bucket) => bucket === void 0 || bucket === "" ? "" : `&bucket=${encodeURIComponent(bucket)}`;
38
+ const rollbackOptimistic = (optimisticRollbacks) => {
39
+ for (let index = optimisticRollbacks.length - 1; index >= 0; index -= 1) {
40
+ optimisticRollbacks[index]?.();
41
+ }
42
+ };
43
+ const applyRowOpsToView = (rows, ops) => {
44
+ for (const op of ops) {
45
+ if (op.op === "delete") {
46
+ rows.delete(op.key);
47
+ } else if (op.value !== void 0) {
48
+ rows.set(op.key, op.value);
49
+ }
50
+ }
51
+ };
52
+ const WS_KEEPALIVE_PING = "lunora-ping";
53
+ const DEFAULT_HEARTBEAT_INTERVAL_MS = 3e4;
54
+ const DEFAULT_CONNECT_TIMEOUT_MS = 1e4;
55
+ const QUERY_CACHE_DEBOUNCE_MS = 250;
56
+ const MAX_PENDING_STREAMS = 64;
57
+ const SHARD_TRAFFIC_PATH = "/_lunora/admin/shard-traffic";
58
+ const SCHEDULED_PATH = "/_lunora/admin/scheduled";
59
+ const SCHEDULED_STATUS_PATH = "/_lunora/admin/scheduled/status";
60
+ const SCHEDULED_WS_PATH = "/_lunora/admin/scheduled/ws";
61
+ const SCHEDULED_CANCEL_PATH = "/_lunora/admin/scheduled/cancel";
62
+ const SCHEDULED_DEAD_PATH = "/_lunora/admin/scheduled/dead";
63
+ const SCHEDULED_DEAD_RETRY_PATH = "/_lunora/admin/scheduled/dead/retry";
64
+ const SCHEDULED_DEAD_CANCEL_PATH = "/_lunora/admin/scheduled/dead/cancel";
65
+ const WORKFLOWS_INSTANCES_PATH = "/_lunora/admin/workflows/instances";
66
+ const WORKFLOWS_INSTANCE_PATH = "/_lunora/admin/workflows/instance";
67
+ const WORKFLOWS_STATUS_PATH = "/_lunora/admin/workflows/status";
68
+ const STORAGE_PATH = "/_lunora/admin/storage";
69
+ const STORAGE_URL_PATH = "/_lunora/admin/storage/url";
70
+ const STORAGE_BUCKETS_PATH = "/_lunora/admin/storage/buckets";
71
+ const FUNCTIONS_PATH = "/_lunora/admin/functions";
72
+ const CRON_JOBS_PATH = "/_lunora/admin/cron-jobs";
73
+ const CRON_JOBS_RUN_PATH = "/_lunora/admin/cron-jobs/run";
74
+ const OPENAPI_PATH = "/_lunora/admin/openapi";
75
+ const OPENRPC_PATH = "/_lunora/admin/openrpc";
76
+ const GLOBAL_TABLES_PATH = "/_lunora/admin/global/tables";
77
+ const GLOBAL_TABLE_PATH = "/_lunora/admin/global/table";
78
+ const GLOBAL_FACET_PATH = "/_lunora/admin/global/facet";
79
+ const VECTOR_INDEXES_PATH = "/_lunora/admin/vector/indexes";
80
+ const VECTOR_QUERY_PATH = "/_lunora/admin/vector/query";
81
+ const AUTH_USERS_PATH = "/_lunora/admin/auth/users";
82
+ const AUTH_SESSIONS_PATH = "/_lunora/admin/auth/sessions";
83
+ const AUTH_CREATE_USER_PATH = "/_lunora/admin/auth/users/create";
84
+ const AUTH_SET_ROLE_PATH = "/_lunora/admin/auth/users/role";
85
+ const AUTH_BAN_PATH = "/_lunora/admin/auth/users/ban";
86
+ const AUTH_UNBAN_PATH = "/_lunora/admin/auth/users/unban";
87
+ const AUTH_SET_PASSWORD_PATH = "/_lunora/admin/auth/users/password";
88
+ const AUTH_REMOVE_USER_PATH = "/_lunora/admin/auth/users/remove";
89
+ const AUTH_IMPERSONATE_PATH = "/_lunora/admin/auth/users/impersonate";
90
+ const AUTH_REVOKE_SESSION_PATH = "/_lunora/admin/auth/sessions/revoke";
91
+ const AUTH_REVOKE_SESSIONS_PATH = "/_lunora/admin/auth/sessions/revoke-all";
92
+ const AUTH_CAPABILITIES_PATH = "/_lunora/admin/auth/capabilities";
93
+ const AUTH_UPDATE_USER_PATH = "/_lunora/admin/auth/users/update";
94
+ const AUTH_ACCOUNTS_PATH = "/_lunora/admin/auth/accounts";
95
+ const AUTH_UNLINK_ACCOUNT_PATH = "/_lunora/admin/auth/accounts/unlink";
96
+ const AUTH_PASSKEYS_PATH = "/_lunora/admin/auth/passkeys";
97
+ const AUTH_DELETE_PASSKEY_PATH = "/_lunora/admin/auth/passkeys/delete";
98
+ const AUTH_DISABLE_2FA_PATH = "/_lunora/admin/auth/two-factor/disable";
99
+ const AUTH_ORGS_PATH = "/_lunora/admin/auth/organizations";
100
+ const AUTH_ORG_MEMBERS_PATH = "/_lunora/admin/auth/organizations/members";
101
+ const AUTH_ORG_INVITATIONS_PATH = "/_lunora/admin/auth/organizations/invitations";
102
+ const AUTH_REMOVE_MEMBER_PATH = "/_lunora/admin/auth/organizations/members/remove";
103
+ const AUTH_CANCEL_INVITATION_PATH = "/_lunora/admin/auth/organizations/invitations/cancel";
104
+ const DEFAULT_AUTH_BASE_PATH = "/api/auth";
105
+ const GET_SESSION_PATH = "/get-session";
106
+ const deriveWsUrl = (url) => {
107
+ if (url.startsWith("https://")) {
108
+ return `wss://${url.slice("https://".length)}`;
109
+ }
110
+ if (url.startsWith("http://")) {
111
+ return `ws://${url.slice("http://".length)}`;
112
+ }
113
+ return url;
114
+ };
115
+ const joinUrl = (base, path) => {
116
+ const trimmed = base.endsWith("/") ? base.slice(0, -1) : base;
117
+ return `${trimmed}${path}`;
118
+ };
119
+ const withQuery = (path, params) => {
120
+ const search = new URLSearchParams();
121
+ for (const [key, value] of Object.entries(params)) {
122
+ if (value !== void 0 && value !== "") {
123
+ search.set(key, String(value));
124
+ }
125
+ }
126
+ const query = search.toString();
127
+ return query === "" ? path : `${path}?${query}`;
128
+ };
129
+ const connectionKey = (shardKey) => shardKey ?? "";
130
+ const buildStreamError = (message) => {
131
+ const errorEnvelope = message.error;
132
+ const code = typeof errorEnvelope?.code === "string" ? errorEnvelope.code : void 0;
133
+ const nestedMessage = typeof errorEnvelope?.message === "string" ? errorEnvelope.message : void 0;
134
+ const messageText = (typeof message.message === "string" ? message.message : void 0) ?? nestedMessage ?? "stream error";
135
+ return Object.assign(new Error(messageText), code === void 0 ? void 0 : { code });
136
+ };
137
+ const buildSubscriptionError = (message) => {
138
+ const errorEnvelope = message.error;
139
+ const code = typeof errorEnvelope?.code === "string" ? errorEnvelope.code : void 0;
140
+ const nestedMessage = typeof errorEnvelope?.message === "string" ? errorEnvelope.message : void 0;
141
+ const messageText = (typeof message.message === "string" ? message.message : void 0) ?? nestedMessage ?? "subscription error";
142
+ return { message: messageText, ...code === void 0 ? {} : { code } };
143
+ };
144
+ const fanSubscriptionError = (callbacks, error) => {
145
+ for (const errorCallback of callbacks) {
146
+ try {
147
+ errorCallback(error);
148
+ } catch {
149
+ }
150
+ }
151
+ };
152
+ const sharedDecoder = new TextDecoder();
153
+ const decodeServerFrame = (raw) => {
154
+ if (typeof raw === "string") {
155
+ return raw;
156
+ }
157
+ if (raw instanceof ArrayBuffer) {
158
+ return sharedDecoder.decode(raw);
159
+ }
160
+ return void 0;
161
+ };
162
+ const sendOn = (conn, message) => {
163
+ if (!conn.socket || conn.wsState !== "open") {
164
+ return false;
165
+ }
166
+ try {
167
+ conn.socket.send(JSON.stringify(message));
168
+ return true;
169
+ } catch {
170
+ return false;
171
+ }
172
+ };
173
+ class LunoraClient {
174
+ /** 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. */
175
+ static MAX_POKE_BUFFERS = 256;
176
+ url;
177
+ wsUrl;
178
+ wsToken;
179
+ /** Better-auth base path (trailing slash stripped) for the `get-session` lookup. */
180
+ authBasePath;
181
+ fetchImpl;
182
+ WebSocketImpl;
183
+ bookmark;
184
+ reconnectOptions;
185
+ /** WS connect timeout (ms); `0` disables it. See {@link LunoraClientOptions.connectTimeoutMs}. */
186
+ connectTimeoutMs;
187
+ /** Keepalive cadence (ms); `0` disables the heartbeat. See {@link LunoraClientOptions.heartbeatIntervalMs}. */
188
+ heartbeatIntervalMs;
189
+ offlineQueue;
190
+ /**
191
+ * Durable outbox seam (the `@lunora/db` `createExecutorOutboxSink`). When
192
+ * set, offline writes are delegated here and the built-in {@link OfflineQueue}
193
+ * is bypassed, so a db app has exactly one durable write path.
194
+ */
195
+ outbox;
196
+ /** Stable per-client id stamped onto every `OutboxMutation` (custom-mutator watermark). */
197
+ clientId;
198
+ /**
199
+ * Highest custom-mutator watermark the server has echoed for this client,
200
+ * keyed by shard bucket (`shardKey ?? ""`) since the DO tracks one
201
+ * `__client_watermark` per shard. `callMutator` bumps it from every
202
+ * ack; the `@lunora/db` mutator runtime seeds its `clientSeq` generator from
203
+ * it so a reload (which resets the in-memory counter) never reissues a stale
204
+ * sequence the server would silently swallow as a replay.
205
+ */
206
+ clientWatermarks = /* @__PURE__ */ new Map();
207
+ /** Monotonic per-client mutation counter backing the server `__client_watermark`. */
208
+ outboxMutationCounter = 0;
209
+ onPersistenceError;
210
+ persistence;
211
+ /** App/schema version stamped on persisted writes + cached reads; mismatches are purged. */
212
+ persistenceVersion;
213
+ /** Releases the multi-tab outbox-leader Web Lock on close (see `hydrateAsOutboxLeader`). */
214
+ outboxLeaderRelease;
215
+ /** Durable read cache (Pillar 2); `undefined` when `queryCache` is omitted or `false`. */
216
+ queryCache;
217
+ /**
218
+ * Values restored from the `queryCache` at construction, keyed by the
219
+ * read-cache key, awaiting the `subscribe()` that will consume them. A
220
+ * key is consumed (deleted) the first time its subscription is created, so
221
+ * the cache only ever seeds the initial value — live frames take over after.
222
+ */
223
+ hydratedQueryCache = /* @__PURE__ */ new Map();
224
+ /**
225
+ * Coalesced read-cache writes: the latest value per key, flushed to
226
+ * the `queryCache` on a short debounce so a burst of deltas persists once.
227
+ */
228
+ pendingCacheWrites = /* @__PURE__ */ new Map();
229
+ cacheFlushTimer;
230
+ subscriptions = new SubscriptionRegistry();
231
+ /** One {@link ShardConnection} per shard key (keyed by `shardKey ?? ""`). */
232
+ connections = /* @__PURE__ */ new Map();
233
+ /** Default `connect`-envelope context applied to a shard with no explicit override. */
234
+ defaultConnectionContext;
235
+ /**
236
+ * Per-shard `connect`-envelope context registered via `setConnectionContext`
237
+ * (keyed by `shardKey ?? ""`), overriding `defaultConnectionContext`. Sent
238
+ * on every socket open so it replays across reconnects, and forwarded to the
239
+ * server's `onConnect`/`onDisconnect` lifecycle hooks. This holds only the
240
+ * imperative (last-writer-wins) override; refcounted holders registered via
241
+ * `acquireConnectionContext` live in `connectionContextHolders` and take
242
+ * precedence — see `effectiveConnectionContext`.
243
+ */
244
+ connectionContexts = /* @__PURE__ */ new Map();
245
+ /**
246
+ * Per-shard stack of refcounted connection-context holders (keyed by
247
+ * `shardKey ?? ""`), registered via `acquireConnectionContext`. Each holder
248
+ * is an opaque token carrying its `context`; the most-recently acquired
249
+ * holder wins (last-writer-wins among live holders), and the context is only
250
+ * cleared for a shard once its last holder releases — so two concurrently
251
+ * mounted presence hooks on the same shard can't stomp each other's context
252
+ * on cleanup. A holder is identified by reference identity so a release
253
+ * removes exactly the right one regardless of stack position.
254
+ */
255
+ connectionContextHolders = /* @__PURE__ */ new Map();
256
+ // `null` is the public sentinel for "signed out" across getAuthToken /
257
+ // setAuthToken / onAuthTokenChange — part of the exported API contract.
258
+ // eslint-disable-next-line unicorn/no-null -- public auth-token contract sentinel
259
+ authToken = null;
260
+ /**
261
+ * Optional STABLE identity subject (a user id), the basis of the offline-queue
262
+ * identity stamp when supplied. Keeps a same-user token *refresh* from looking
263
+ * like an identity change (which would discard queued writes). `undefined` =
264
+ * not supplied, so identity falls back to a hash of the raw token. See
265
+ * `setAuthToken` / `identityFingerprint`.
266
+ */
267
+ authSubject = void 0;
268
+ /**
269
+ * Identity stamp recorded against each queued offline mutation, keyed by
270
+ * the queue-assigned mutation id. Captured at enqueue from the auth token
271
+ * in effect at the time, and re-checked at flush so a queued write can
272
+ * never replay under a different identity than the one that issued it.
273
+ * See `identityFingerprint` for the fingerprint shape.
274
+ */
275
+ queuedIdentities = /* @__PURE__ */ new Map();
276
+ closed = false;
277
+ /** Subscribers to auth-token changes (see `onAuthTokenChange`). */
278
+ authTokenListeners = new Listeners();
279
+ /** Subscribers to aggregate connection-status changes (see `onConnectionStatus`). */
280
+ statusListeners = new Listeners();
281
+ /** Subscribers notified when the server drops a socket for an expired token (see `onTokenExpired`). */
282
+ tokenExpiredListeners = new Listeners();
283
+ /** Subscribers to offline-queued mutation verdicts (see `onMutationSettled`). */
284
+ mutationSettledListeners = new Listeners();
285
+ /** Subscribers to the offline-queue pending-count (see `onPendingChange`). */
286
+ pendingChangeListeners = new Listeners();
287
+ /**
288
+ * Whisper-topic handlers, keyed by `connectionKey(shardKey)` → topic → set
289
+ * of callbacks. Membership doubles as the resubscribe set replayed on every
290
+ * (re)connect so a topic survives a socket bounce.
291
+ */
292
+ whisperHandlers = /* @__PURE__ */ new Map();
293
+ /** Last status broadcast, so we only notify listeners on an actual change. */
294
+ lastStatus = "idle";
295
+ nextSubId = 0;
296
+ nextStreamId = 0;
297
+ /**
298
+ * In-flight client-side stream readers, keyed by the stream id sent on the
299
+ * wire. The handle drives the underlying iterator queue and `shardKey`
300
+ * tells us which socket to push the cancel frame onto when the consumer
301
+ * calls `.cancel()` or the iterator is garbage-collected.
302
+ */
303
+ streams = /* @__PURE__ */ new Map();
304
+ /** Live shape subscriptions (partial replication), keyed by their wire id. */
305
+ shapeSubscriptions = /* @__PURE__ */ new Map();
306
+ /** In-flight pokes being assembled between `pokeStart` and `pokeEnd`, keyed by `pokeId`. */
307
+ pokeBuffers = /* @__PURE__ */ new Map();
308
+ nextShapeId = 0;
309
+ constructor(options) {
310
+ this.url = options.url;
311
+ this.wsUrl = options.wsUrl ?? joinUrl(deriveWsUrl(options.url), WS_PATH);
312
+ this.wsToken = options.wsToken;
313
+ const authBase = options.authBasePath ?? DEFAULT_AUTH_BASE_PATH;
314
+ this.authBasePath = authBase.endsWith("/") ? authBase.slice(0, -1) : authBase;
315
+ this.fetchImpl = options.fetch ?? (typeof fetch === "function" ? fetch.bind(globalThis) : void 0);
316
+ this.WebSocketImpl = options.WebSocket ?? (typeof WebSocket === "function" ? WebSocket : void 0);
317
+ this.bookmark = options.bookmarkStorage ?? createInMemoryBookmarkStorage();
318
+ this.reconnectOptions = options.reconnect;
319
+ this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
320
+ this.connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
321
+ this.defaultConnectionContext = options.connectionContext;
322
+ this.persistence = options.persistence;
323
+ this.persistenceVersion = options.persistenceVersion;
324
+ this.queryCache = options.queryCache === false ? void 0 : options.queryCache;
325
+ this.onPersistenceError = options.offlineQueue?.onPersistenceError;
326
+ this.offlineQueue = new OfflineQueue(options.offlineQueue, {
327
+ onEvict: (entry, error) => {
328
+ this.emitItemSettled(entry, "rejected", error);
329
+ },
330
+ onSizeChange: (size) => {
331
+ this.pendingChangeListeners.emit(size);
332
+ },
333
+ persistence: options.persistence,
334
+ version: options.persistenceVersion
335
+ });
336
+ this.outbox = options.outbox;
337
+ this.clientId = options.clientId ?? `client-${nextId()}`;
338
+ if (this.persistence) {
339
+ queueMicrotask(() => {
340
+ this.hydrateAsOutboxLeader();
341
+ });
342
+ }
343
+ if (this.queryCache) {
344
+ queueMicrotask(() => {
345
+ this.hydrateQueryCache().catch(() => void 0);
346
+ });
347
+ }
348
+ }
349
+ // --- Auth helpers -------------------------------------------------------
350
+ /**
351
+ * Set (or clear) the bearer token sent on every HTTP RPC. Notifies any
352
+ * {@link onAuthTokenChange} listeners so React hooks like `useAuth` stay in
353
+ * sync across all mounted instances.
354
+ *
355
+ * Pass a STABLE `subject` (the user id) to key the offline-queue identity on
356
+ * it instead of the token bytes, so a token *refresh* (same user, new JWT)
357
+ * doesn't read as an identity change and discard queued writes. The subject is
358
+ * **sticky**: a later call that omits it (or passes `undefined`) keeps the
359
+ * established subject — so `setAuthToken(refreshedToken)` after a prior
360
+ * `setAuthToken(token, user.id)` retains the identity. Pass `null` to clear it
361
+ * (an explicit sign-out). Establishing the subject for the first time on an
362
+ * UNCHANGED token (e.g. the user id resolves a tick after the token was set)
363
+ * re-stamps any in-flight queued writes rather than dropping them — same
364
+ * credential, just a more stable label. A real user switch (the token AND
365
+ * subject both change) still drops the previous user's writes.
366
+ *
367
+ * Does NOT update the WebSocket auth — the WS token is fixed at upgrade
368
+ * time and lives in the URL. To refresh live WS auth, call
369
+ * {@link setWsToken} explicitly, which closes existing shard sockets to
370
+ * force a reconnect with the new credential.
371
+ */
372
+ setAuthToken(token, subject) {
373
+ const tokenChanged = this.authToken !== token;
374
+ const previousIdentity = this.identityFingerprint();
375
+ this.authToken = token;
376
+ if (subject !== void 0) {
377
+ this.authSubject = subject;
378
+ }
379
+ const newIdentity = this.identityFingerprint();
380
+ if (newIdentity !== previousIdentity) {
381
+ if (tokenChanged) {
382
+ this.rejectQueuedForIdentityChange();
383
+ } else {
384
+ this.restampQueuedIdentity(previousIdentity, newIdentity);
385
+ }
386
+ }
387
+ if (tokenChanged) {
388
+ this.authTokenListeners.emit(token);
389
+ }
390
+ }
391
+ getAuthToken() {
392
+ return this.authToken;
393
+ }
394
+ /**
395
+ * The current identity fingerprint (the same stamp queued offline writes
396
+ * carry). Exposed so a durable {@link OutboxSink}'s replay handler — which
397
+ * owns its own at-least-once replay outside the built-in `OfflineQueue` —
398
+ * can drop a persisted write whose captured `identity` no longer matches the
399
+ * signed-in user, the guard the queue path applies in `flushOfflineQueue`.
400
+ */
401
+ currentIdentity() {
402
+ return this.identityFingerprint();
403
+ }
404
+ /** This client's stable identifier — the watermark key the server's custom-mutator protocol advances per `clientSeq`. */
405
+ clientIdentifier() {
406
+ return this.clientId;
407
+ }
408
+ /**
409
+ * The highest custom-mutator watermark the server has echoed for this client
410
+ * on the given shard (0 if none yet). The `@lunora/db` mutator runtime seeds
411
+ * its `clientSeq` generator from this so a reload never reissues a sequence
412
+ * the server has already applied (which it would swallow as a replay, silently
413
+ * dropping the write).
414
+ */
415
+ confirmedMutationWatermark(shardKey) {
416
+ return this.clientWatermarks.get(shardKey ?? "") ?? 0;
417
+ }
418
+ /**
419
+ * Push a custom mutator to its authoritative server impl over the watermark
420
+ * protocol (Phase 4): the request carries `x-lunora-client-id` + a monotonic
421
+ * `x-lunora-client-seq`, so the DO runs it exactly once and advances this
422
+ * client's `__client_watermark`.
423
+ *
424
+ * Returns the server `result` plus `applied`: `true` when the DO ran this push
425
+ * as the next-in-order mutation, `false` when it was a replay ack (`clientSeq`
426
+ * was at or below the stored watermark — e.g. a stale sequence after a reload).
427
+ * A `false` verdict tells the caller to reissue above the now-known watermark
428
+ * (echoed into {@link confirmedMutationWatermark}) rather than treat the benign
429
+ * ack as a confirmed write. Every ack — applied or not — bumps the watermark.
430
+ *
431
+ * This is the online transport for `@lunora/db`'s client-mutator runtime; the
432
+ * optimistic overlay + durable-outbox concerns live in that runtime, not here.
433
+ */
434
+ async callMutator(functionPath, args, options) {
435
+ const clientSeq = options?.clientSeq;
436
+ if (clientSeq !== void 0 && (!Number.isInteger(clientSeq) || clientSeq <= 0)) {
437
+ throw new Error(`callMutator: clientSeq must be a positive integer, got ${String(clientSeq)}`);
438
+ }
439
+ const bucket = options?.shardKey ?? "";
440
+ let ackWatermark;
441
+ const result = await this.rpc(functionPath, args, options?.shardKey, {
442
+ captureBookmark: true,
443
+ clientId: this.clientId,
444
+ clientSeq,
445
+ onMutationAck: (lastMutationId) => {
446
+ ackWatermark = lastMutationId;
447
+ }
448
+ });
449
+ if (ackWatermark !== void 0 && ackWatermark > (this.clientWatermarks.get(bucket) ?? 0)) {
450
+ this.clientWatermarks.set(bucket, ackWatermark);
451
+ }
452
+ const applied = ackWatermark === void 0 || ackWatermark === clientSeq;
453
+ return { applied, result };
454
+ }
455
+ /**
456
+ * Subscribe to auth-token changes. Returns an unsubscribe function. The
457
+ * listener is NOT invoked on registration — use {@link getAuthToken} for
458
+ * the current value.
459
+ */
460
+ onAuthTokenChange(listener) {
461
+ return this.authTokenListeners.add(listener);
462
+ }
463
+ /**
464
+ * Fetch the currently authenticated user from better-auth's `get-session`
465
+ * endpoint, returning the `user` record or `null` when signed out. Sends
466
+ * the stored bearer token (if any) and `credentials: "include"` so a
467
+ * cookie-session is also honoured. A network/parse failure or a non-OK
468
+ * response resolves to `null` rather than throwing — callers treat "couldn't
469
+ * resolve identity" as "signed out".
470
+ *
471
+ * Framework-agnostic: pair it with {@link onAuthTokenChange} to refetch when
472
+ * the token changes (that's what `@lunora/react`'s `useAuth` does).
473
+ */
474
+ async getCurrentUser() {
475
+ if (this.closed || !this.fetchImpl) {
476
+ return null;
477
+ }
478
+ const headers = {};
479
+ if (this.authToken) {
480
+ headers["authorization"] = `Bearer ${this.authToken}`;
481
+ }
482
+ try {
483
+ const response = await this.fetchImpl(joinUrl(this.url, `${this.authBasePath}${GET_SESSION_PATH}`), {
484
+ credentials: "include",
485
+ headers,
486
+ method: "GET"
487
+ });
488
+ if (!response.ok) {
489
+ return null;
490
+ }
491
+ const body = await response.json();
492
+ return body?.user ?? null;
493
+ } catch {
494
+ return null;
495
+ }
496
+ }
497
+ /**
498
+ * Replace the token appended to WS upgrade URLs as `?token=…` and close
499
+ * every open shard socket so the reconnect picks up the new value. Call
500
+ * this whenever the user's WS credential changes (rotating the admin token
501
+ * in the studio, switching workspaces, etc.). Bearer tokens for HTTP
502
+ * RPC are independent — see {@link setAuthToken}.
503
+ */
504
+ setWsToken(token) {
505
+ if (this.wsToken === token) {
506
+ return;
507
+ }
508
+ this.wsToken = token;
509
+ for (const conn of this.connections.values()) {
510
+ if (conn.socket) {
511
+ try {
512
+ conn.socket.close();
513
+ } catch {
514
+ }
515
+ }
516
+ }
517
+ }
518
+ /**
519
+ * Register (or clear, with `undefined`) the app context sent in the `connect`
520
+ * envelope for a shard's socket, overriding the client-wide
521
+ * {@link LunoraClientOptions.connectionContext}. The server forwards it to the
522
+ * `onConnect`/`onDisconnect` lifecycle hooks as `event.context` — e.g.
523
+ * `@lunora/react`'s `usePresence` registers `{ roomId, sessionId }` so the
524
+ * presence row is removed the instant the socket drops, with no TTL lag.
525
+ *
526
+ * Stored per shard and replayed on every (re)connect. When a socket for the
527
+ * shard is already open, a fresh `connect` envelope is sent immediately so the
528
+ * server sees the new context without waiting for a reconnect.
529
+ */
530
+ setConnectionContext(context, options = {}) {
531
+ const key = connectionKey(options.shardKey);
532
+ if (context === void 0) {
533
+ this.connectionContexts.delete(key);
534
+ } else {
535
+ this.connectionContexts.set(key, context);
536
+ }
537
+ this.refreshConnectionContext(key);
538
+ }
539
+ /**
540
+ * Refcounted variant of {@link setConnectionContext}: register a connection
541
+ * `context` for a shard and get back a release function. Unlike the imperative
542
+ * setter, the context is only cleared once the *last* acquired holder releases
543
+ * it — so two components (e.g. two mounted `usePresence` hooks) on the same
544
+ * shard no longer clobber each other's context when one of them unmounts. The
545
+ * most-recently acquired live holder wins (last-writer-wins), and releasing
546
+ * the top holder falls back to the previous one rather than clearing.
547
+ *
548
+ * With a single holder the behaviour is identical to a
549
+ * `setConnectionContext(context)` / `setConnectionContext(undefined)` pair.
550
+ * Releasing more than once is a no-op (the holder is matched by reference, so
551
+ * a double release can't drop a different holder).
552
+ */
553
+ acquireConnectionContext(context, options = {}) {
554
+ const key = connectionKey(options.shardKey);
555
+ const holder = { context };
556
+ const holders = this.connectionContextHolders.get(key);
557
+ if (holders) {
558
+ holders.push(holder);
559
+ } else {
560
+ this.connectionContextHolders.set(key, [holder]);
561
+ }
562
+ this.refreshConnectionContext(key);
563
+ let released = false;
564
+ return () => {
565
+ if (released) {
566
+ return;
567
+ }
568
+ released = true;
569
+ const live = this.connectionContextHolders.get(key);
570
+ if (!live) {
571
+ return;
572
+ }
573
+ const index = live.indexOf(holder);
574
+ if (index !== -1) {
575
+ live.splice(index, 1);
576
+ }
577
+ if (live.length === 0) {
578
+ this.connectionContextHolders.delete(key);
579
+ }
580
+ this.refreshConnectionContext(key);
581
+ };
582
+ }
583
+ // --- Whispering ---------------------------------------------------------
584
+ /**
585
+ * Join a whisper `topic` and receive every ephemeral message other members
586
+ * broadcast to it on the same shard (typing indicators, live cursors,
587
+ * presence pings). Whispers never touch the server's durable state — there's
588
+ * no query, no row, no CDC entry. Returns an unsubscribe function; the topic
589
+ * is left on the server once its last local handler unsubscribes.
590
+ *
591
+ * `handler` receives the raw `data` and the sender's verified `from` user id
592
+ * (omitted for an anonymous sender). The topic is scoped to `options.shardKey`
593
+ * (the default shard when omitted) — use the same shard you target with the
594
+ * matching queries/mutations so members land on the same Durable Object.
595
+ *
596
+ * Security: whisper topics are NOT access-controlled beyond the shard
597
+ * boundary — any client that can open a socket to the shard can join, read,
598
+ * and inject on any topic name. `from` is server-stamped and unforgeable, but
599
+ * do not put data on a whisper topic that some shard members shouldn't see,
600
+ * and don't trust a whisper's `data` as authorization. Use a query/mutation
601
+ * (with RLS) for anything privileged; whispers are for transient awareness.
602
+ */
603
+ whisperSubscribe(topic, handler, options = {}) {
604
+ const key = connectionKey(options.shardKey);
605
+ let byTopic = this.whisperHandlers.get(key);
606
+ if (!byTopic) {
607
+ byTopic = /* @__PURE__ */ new Map();
608
+ this.whisperHandlers.set(key, byTopic);
609
+ }
610
+ let handlers = byTopic.get(topic);
611
+ const first = handlers === void 0;
612
+ if (!handlers) {
613
+ handlers = /* @__PURE__ */ new Set();
614
+ byTopic.set(topic, handlers);
615
+ }
616
+ handlers.add(handler);
617
+ this.ensureSocket(options.shardKey);
618
+ if (first) {
619
+ const conn = this.getConnection(options.shardKey);
620
+ if (conn) {
621
+ sendOn(conn, { topic, type: "whisper_subscribe" });
622
+ }
623
+ }
624
+ return () => {
625
+ const stillByTopic = this.whisperHandlers.get(key);
626
+ const stillHandlers = stillByTopic?.get(topic);
627
+ if (!stillHandlers?.delete(handler) || stillHandlers.size > 0) {
628
+ return;
629
+ }
630
+ stillByTopic?.delete(topic);
631
+ if (stillByTopic?.size === 0) {
632
+ this.whisperHandlers.delete(key);
633
+ }
634
+ const conn = this.getConnection(options.shardKey);
635
+ if (conn) {
636
+ sendOn(conn, { topic, type: "whisper_unsubscribe" });
637
+ }
638
+ };
639
+ }
640
+ /**
641
+ * Broadcast an ephemeral `data` payload to the other members of a whisper
642
+ * `topic` on `options.shardKey`'s shard. Fire-and-forget: the frame is
643
+ * dropped when the shard socket isn't open (whispers are transient, never
644
+ * queued), and the server silently drops it if the sender exceeds its
645
+ * whisper rate budget. The sender never receives its own whisper. Omitting
646
+ * `data` delivers JSON `null` to receivers (not `undefined`).
647
+ */
648
+ whisper(topic, data, options = {}) {
649
+ this.ensureSocket(options.shardKey);
650
+ const conn = this.getConnection(options.shardKey);
651
+ if (conn) {
652
+ sendOn(conn, { data, topic, type: "whisper" });
653
+ }
654
+ }
655
+ /**
656
+ * Subscribe to token-expiry events: invoked whenever the server drops a
657
+ * shard socket because the connection's credential lapsed (close code
658
+ * `4001`). The client already reconnects automatically (re-resolving
659
+ * identity from the cookie/token in effect); use this to refresh a
660
+ * short-lived token first — e.g. call {@link setWsToken} / {@link setAuthToken}
661
+ * with a freshly minted one. Returns an unsubscribe function.
662
+ */
663
+ onTokenExpired(listener) {
664
+ return this.tokenExpiredListeners.add(listener);
665
+ }
666
+ // --- Connection status --------------------------------------------------
667
+ /**
668
+ * Current aggregate live-socket status across all shard connections. See
669
+ * {@link ConnectionStatus}.
670
+ */
671
+ connectionStatus() {
672
+ return this.computeStatus();
673
+ }
674
+ /**
675
+ * Subscribe to aggregate connection-status changes. Invokes `listener`
676
+ * immediately with the current status, then on every transition. Returns an
677
+ * unsubscribe function.
678
+ */
679
+ onConnectionStatus(listener) {
680
+ const unsubscribe = this.statusListeners.add(listener);
681
+ listener(this.computeStatus());
682
+ return unsubscribe;
683
+ }
684
+ /**
685
+ * Number of offline writes waiting in the built-in queue to be sent — the
686
+ * depth for a "N changes waiting to sync" indicator. Counts writes that are
687
+ * queued (offline / mid-reconnect), not ones already in flight on the wire.
688
+ * A `@lunora/db` app whose writes ride the unified outbox should read
689
+ * `LunoraDb.pendingCount()` instead (this counts only the built-in queue).
690
+ */
691
+ pendingCount() {
692
+ return this.offlineQueue.size;
693
+ }
694
+ /**
695
+ * Subscribe to changes in {@link pendingCount}. Invokes `listener` immediately
696
+ * with the current count, then whenever the queue depth changes (a write is
697
+ * enqueued, flushed, or discarded). Returns an unsubscribe function.
698
+ */
699
+ onPendingChange(listener) {
700
+ const unsubscribe = this.pendingChangeListeners.add(listener);
701
+ listener(this.offlineQueue.size);
702
+ return unsubscribe;
703
+ }
704
+ /**
705
+ * Subscribe to terminal verdicts for offline-queued mutations. The listener
706
+ * fires once per queued write that commits or is rejected — including a write
707
+ * restored from durable storage after a reload, whose original `mutation()`
708
+ * Promise no longer exists (`hadAwaiter: false`), and a write the queue
709
+ * evicts on overflow or discards on an identity change. This is the durable
710
+ * channel for surfacing a rolled-back optimistic write to the UI; an online
711
+ * mutation that never queued still surfaces through the Promise `mutation()`
712
+ * returns. The listener is NOT invoked on registration. Returns an
713
+ * unsubscribe function. See {@link MutationSettledEvent}.
714
+ */
715
+ onMutationSettled(listener) {
716
+ return this.mutationSettledListeners.add(listener);
717
+ }
718
+ // --- RPC ---------------------------------------------------------------
719
+ async query(function_, args, options = {}) {
720
+ if (this.closed) {
721
+ throw new Error("LunoraClient is closed");
722
+ }
723
+ return await this.rpc(function_.__lunoraRef, args, options.shardKey, { attachBookmark: true });
724
+ }
725
+ /**
726
+ * Invoke a mutation. Errors propagate as rejections.
727
+ *
728
+ * Offline-queue semantics: a mutation is queued (and replayed on reconnect)
729
+ * only when the targeted shard's socket was open at least once already
730
+ * (`wasEverConnected`), so the registry / resubscribe handshake has run.
731
+ * Mutations issued before the very first WS connect to a shard fail fast.
732
+ * Opt into queueing-before-first-connect via
733
+ * `OfflineQueueOptions.queueBeforeFirstConnect`.
734
+ */
735
+ async mutation(function_, args, options = {}) {
736
+ if (this.closed) {
737
+ throw new Error("LunoraClient is closed");
738
+ }
739
+ const argsRecord = args;
740
+ const mutationId = options.mutationId ?? nextId();
741
+ const { confirms: optimisticConfirms, rollbacks: optimisticRollbacks } = this.applyOptimisticUpdates(
742
+ function_.__lunoraRef,
743
+ argsRecord,
744
+ options.shardKey,
745
+ options.optimistic
746
+ );
747
+ if (options.optimisticUpdate) {
748
+ this.applyOptimisticUpdate(options.optimisticUpdate, args, options.shardKey, optimisticRollbacks, optimisticConfirms);
749
+ }
750
+ const conn = this.getConnection(options.shardKey);
751
+ const wsState = conn?.wsState ?? "idle";
752
+ const hasSocket = conn?.socket !== void 0;
753
+ const wasEverConnected = conn?.wasEverConnected ?? false;
754
+ const { queueBeforeFirstConnect } = this.offlineQueue;
755
+ const connectedGate = wasEverConnected || queueBeforeFirstConnect;
756
+ const shouldQueueOffline = this.WebSocketImpl !== void 0 && connectedGate;
757
+ const midReconnect = wsState === "connecting" && connectedGate;
758
+ if (wsState !== "open" && !hasSocket && shouldQueueOffline || midReconnect) {
759
+ return this.enqueueOfflineMutation(function_, argsRecord, options.shardKey, mutationId, optimisticRollbacks, optimisticConfirms);
760
+ }
761
+ try {
762
+ let commitCursor;
763
+ const result = await this.rpc(function_.__lunoraRef, argsRecord, options.shardKey, {
764
+ captureBookmark: true,
765
+ mutationId,
766
+ onCommitCursor: (cursor) => {
767
+ commitCursor = cursor;
768
+ }
769
+ });
770
+ for (const confirm of optimisticConfirms) {
771
+ confirm(commitCursor);
772
+ }
773
+ return result;
774
+ } catch (error) {
775
+ rollbackOptimistic(optimisticRollbacks);
776
+ throw error;
777
+ }
778
+ }
779
+ async action(function_, args, options = {}) {
780
+ if (this.closed) {
781
+ throw new Error("LunoraClient is closed");
782
+ }
783
+ return await this.rpc(function_.__lunoraRef, args, options.shardKey);
784
+ }
785
+ // --- Advisor admin ------------------------------------------------------
786
+ /**
787
+ * Read the cross-shard request distribution for a `.shardBy(...)` table —
788
+ * the feed the studio's `hot_shard` advisor lint consumes. Hits the
789
+ * admin-gated `POST /_lunora/admin/shard-traffic` endpoint, which fans the
790
+ * cheap per-shard `getMetrics` read out across every live shard and returns
791
+ * each shard's `{ shardKey, requests }` total (a failed shard surfaces with
792
+ * `requests: 0`). Requires the worker to be built with a `queryCoordinator`
793
+ * and `adminToken`, and this client's auth token to match; defaults any
794
+ * absent field so an older worker yields an empty-but-valid shape.
795
+ */
796
+ async shardTraffic(table) {
797
+ if (this.closed) {
798
+ throw new Error("LunoraClient is closed");
799
+ }
800
+ const body = await this.adminFetch(SHARD_TRAFFIC_PATH, "POST", { table });
801
+ return { failed: body.failed ?? 0, ok: body.ok ?? 0, shards: body.shards ?? [] };
802
+ }
803
+ // --- Scheduler admin ----------------------------------------------------
804
+ /**
805
+ * List the functions queued via `runAfter` / `runAt`, soonest-due last
806
+ * (the worker returns them in storage order). Hits the admin-gated
807
+ * `/_lunora/admin/scheduled` endpoint, so the worker must be built with a
808
+ * `schedulerDO` namespace and `adminToken`, and this client's auth token
809
+ * must match. Powers `@lunora/studio`'s scheduled-jobs panel.
810
+ */
811
+ async listScheduledJobs() {
812
+ if (this.closed) {
813
+ throw new Error("LunoraClient is closed");
814
+ }
815
+ const body = await this.adminFetch(SCHEDULED_PATH, "GET");
816
+ return body.records ?? [];
817
+ }
818
+ /**
819
+ * Read the app-level workpool backlog that powers `@lunora/studio`'s SLO
820
+ * view: per-pool `{ name, queued, inFlight, maxConcurrency }` plus the
821
+ * app-wide `backlog` (total queued) and `inFlight` (total held slots) sums.
822
+ * Hits the admin-gated `GET /_lunora/admin/scheduled/status` endpoint, so the
823
+ * same preconditions as {@link listScheduledJobs} apply (a `schedulerDO`
824
+ * namespace + `adminToken` on the worker and a matching auth token here).
825
+ * Defaults any absent field so an older worker still yields a valid shape.
826
+ */
827
+ async schedulerStatus() {
828
+ if (this.closed) {
829
+ throw new Error("LunoraClient is closed");
830
+ }
831
+ const body = await this.adminFetch(SCHEDULED_STATUS_PATH, "GET");
832
+ return {
833
+ backlog: body.backlog ?? 0,
834
+ inFlight: body.inFlight ?? 0,
835
+ pools: body.pools ?? []
836
+ };
837
+ }
838
+ /** Cancel a pending scheduled job by id. Returns whether a job was removed. */
839
+ async cancelScheduledJob(id) {
840
+ if (this.closed) {
841
+ throw new Error("LunoraClient is closed");
842
+ }
843
+ const body = await this.adminFetch(SCHEDULED_CANCEL_PATH, "POST", { id });
844
+ return { cancelled: body.cancelled === true };
845
+ }
846
+ /**
847
+ * List the dead-letter jobs: schedules that exhausted their retry budget
848
+ * and were parked instead of dropped. These never appear in
849
+ * {@link listScheduledJobs} (their live header is gone), so this is the only
850
+ * way the studio surfaces a permanently-failed job. Hits the admin-gated
851
+ * `GET /_lunora/admin/scheduled/dead`; same preconditions as
852
+ * {@link listScheduledJobs}. Powers `@lunora/studio`'s dead-letter panel.
853
+ */
854
+ async listDeadJobs() {
855
+ if (this.closed) {
856
+ throw new Error("LunoraClient is closed");
857
+ }
858
+ const body = await this.adminFetch(SCHEDULED_DEAD_PATH, "GET");
859
+ return body.records ?? [];
860
+ }
861
+ /**
862
+ * Resurrect a dead-letter job by id: it re-enters the schedule with a fresh
863
+ * retry budget and fires on the next drain. Returns whether a parked record
864
+ * matched. Hits the admin-gated `POST /_lunora/admin/scheduled/dead/retry`.
865
+ */
866
+ async retryDeadJob(id) {
867
+ if (this.closed) {
868
+ throw new Error("LunoraClient is closed");
869
+ }
870
+ const body = await this.adminFetch(SCHEDULED_DEAD_RETRY_PATH, "POST", { id });
871
+ return { retried: body.retried === true };
872
+ }
873
+ /**
874
+ * Permanently drop a dead-letter job by id (the operator has decided not to
875
+ * recover it). Returns whether a parked record was removed. Hits the
876
+ * admin-gated `POST /_lunora/admin/scheduled/dead/cancel`.
877
+ */
878
+ async removeDeadJob(id) {
879
+ if (this.closed) {
880
+ throw new Error("LunoraClient is closed");
881
+ }
882
+ const body = await this.adminFetch(SCHEDULED_DEAD_CANCEL_PATH, "POST", { id });
883
+ return { removed: body.removed === true };
884
+ }
885
+ /**
886
+ * List a workflow's instances via the admin Workflows proxy
887
+ * (`/_lunora/admin/workflows/instances`) — the Cloudflare control-plane data
888
+ * the `Workflow` binding can't expose. Requires the worker to be built with a
889
+ * `workflowsClient` (Cloudflare account id + API token). When one isn't
890
+ * configured this does NOT reject: the proxy returns a `200 { configured:
891
+ * false }` sentinel, so the result resolves with `configured === false` and an
892
+ * empty `instances` list — callers should branch on that flag rather than
893
+ * try/catch. (The instance-detail / status endpoints still reject with 501.)
894
+ * `name` is the deployed workflow name.
895
+ */
896
+ async listWorkflowInstances(options) {
897
+ if (this.closed) {
898
+ throw new Error("LunoraClient is closed");
899
+ }
900
+ const query = new URLSearchParams({ name: options.name });
901
+ if (options.status !== void 0) {
902
+ query.set("status", options.status);
903
+ }
904
+ if (options.page !== void 0) {
905
+ query.set("page", String(options.page));
906
+ }
907
+ if (options.perPage !== void 0) {
908
+ query.set("perPage", String(options.perPage));
909
+ }
910
+ const body = await this.adminFetch(`${WORKFLOWS_INSTANCES_PATH}?${query.toString()}`, "GET");
911
+ return {
912
+ configured: body.configured,
913
+ instances: body.instances ?? [],
914
+ page: body.page ?? 1,
915
+ perPage: body.perPage ?? options.perPage ?? 0,
916
+ totalCount: body.totalCount
917
+ };
918
+ }
919
+ /** Read one workflow instance with its step timeline (`/_lunora/admin/workflows/instance`). */
920
+ async getWorkflowInstance(options) {
921
+ if (this.closed) {
922
+ throw new Error("LunoraClient is closed");
923
+ }
924
+ const query = new URLSearchParams({ id: options.id, name: options.name });
925
+ const body = await this.adminFetch(`${WORKFLOWS_INSTANCE_PATH}?${query.toString()}`, "GET");
926
+ return {
927
+ createdOn: body.createdOn,
928
+ endedOn: body.endedOn,
929
+ error: body.error,
930
+ id: body.id ?? options.id,
931
+ output: body.output,
932
+ params: body.params,
933
+ startedOn: body.startedOn,
934
+ status: body.status ?? "unknown",
935
+ steps: body.steps ?? []
936
+ };
937
+ }
938
+ /** Pause / resume / terminate a workflow instance (`/_lunora/admin/workflows/status`). Needs an Edit-scoped Cloudflare token. */
939
+ async setWorkflowInstanceStatus(options) {
940
+ if (this.closed) {
941
+ throw new Error("LunoraClient is closed");
942
+ }
943
+ const body = await this.adminFetch(WORKFLOWS_STATUS_PATH, "POST", { action: options.action, id: options.id, name: options.name });
944
+ return { status: body.status ?? "unknown" };
945
+ }
946
+ /**
947
+ * Subscribe to the live scheduled-jobs list over the SchedulerDO's admin
948
+ * WebSocket. `onJobs` fires with the full list on connect and on every
949
+ * change (schedule / cancel / alarm-fire). Reconnects with the client's
950
+ * configured backoff. Requires `wsToken` to be set to the admin token (the
951
+ * browser can't send an `Authorization` header on a WS). Returns an
952
+ * unsubscribe function that closes the socket and stops reconnecting.
953
+ */
954
+ subscribeScheduledJobs(onJobs) {
955
+ if (this.closed) {
956
+ throw new Error("LunoraClient is closed");
957
+ }
958
+ if (this.WebSocketImpl === void 0) {
959
+ return () => void 0;
960
+ }
961
+ const base = joinUrl(deriveWsUrl(this.url), SCHEDULED_WS_PATH);
962
+ const reconnect = createReconnect(this.reconnectOptions);
963
+ let socket;
964
+ let timer;
965
+ let closed = false;
966
+ const connect = () => {
967
+ if (closed || this.WebSocketImpl === void 0) {
968
+ return;
969
+ }
970
+ const url = this.wsToken === void 0 ? base : `${base}?token=${encodeURIComponent(this.wsToken)}`;
971
+ socket = new this.WebSocketImpl(url);
972
+ socket.addEventListener("open", () => {
973
+ reconnect.reset();
974
+ });
975
+ socket.addEventListener("message", (event) => {
976
+ try {
977
+ const message = JSON.parse(typeof event.data === "string" ? event.data : "");
978
+ if (message.type === "jobs" && Array.isArray(message.records)) {
979
+ onJobs(message.records);
980
+ }
981
+ } catch {
982
+ }
983
+ });
984
+ socket.addEventListener("close", () => {
985
+ socket = void 0;
986
+ if (!closed) {
987
+ timer = setTimeout(connect, reconnect.next());
988
+ }
989
+ });
990
+ socket.addEventListener("error", () => {
991
+ });
992
+ };
993
+ connect();
994
+ return () => {
995
+ closed = true;
996
+ if (timer !== void 0) {
997
+ clearTimeout(timer);
998
+ }
999
+ socket?.close();
1000
+ };
1001
+ }
1002
+ // --- Functions admin ----------------------------------------------------
1003
+ /**
1004
+ * List the registered public functions (queries / mutations / actions) with
1005
+ * their kinds. Hits the admin-gated `GET /_lunora/admin/functions` endpoint —
1006
+ * the worker must be built with a `functions` registry and `adminToken`, and
1007
+ * this client's auth token must match. Powers `@lunora/studio`'s function
1008
+ * runner auto-discovery.
1009
+ */
1010
+ async listFunctions() {
1011
+ if (this.closed) {
1012
+ throw new Error("LunoraClient is closed");
1013
+ }
1014
+ const body = await this.adminFetch(FUNCTIONS_PATH, "GET");
1015
+ return body.functions ?? [];
1016
+ }
1017
+ /**
1018
+ * List the code-defined cron triggers (the `cronJobs()` map injected on the
1019
+ * worker), each flattened to its firing `cron` expression. Hits the
1020
+ * admin-gated `GET /_lunora/admin/cron-jobs` endpoint — the worker must be
1021
+ * built with a `cronJobs` map and `adminToken`, and this client's auth token
1022
+ * must match. These are static (Cloudflare exposes no runtime cron
1023
+ * introspection), so the studio renders them read-only alongside the dynamic
1024
+ * scheduler jobs.
1025
+ */
1026
+ async getCronJobs() {
1027
+ if (this.closed) {
1028
+ throw new Error("LunoraClient is closed");
1029
+ }
1030
+ const body = await this.adminFetch(CRON_JOBS_PATH, "GET");
1031
+ return body.jobs ?? [];
1032
+ }
1033
+ /**
1034
+ * Manually fire one code-defined cron job by name — the same dispatch the
1035
+ * scheduled trigger runs (dispatch the function, or start the durable
1036
+ * workflow), on demand. Hits the admin-gated `POST /_lunora/admin/cron-jobs/run`
1037
+ * endpoint; the worker must be built with a `cronJobs` map and `adminToken`,
1038
+ * and this client's auth token must match. Resolves when the job has run (a
1039
+ * function job's shard response is 2xx, or the workflow instance was created)
1040
+ * and rejects with the dispatch error otherwise.
1041
+ */
1042
+ async runCronJob(name) {
1043
+ if (this.closed) {
1044
+ throw new Error("LunoraClient is closed");
1045
+ }
1046
+ const body = await this.adminFetch(CRON_JOBS_RUN_PATH, "POST", { name });
1047
+ return { name: body.name ?? name, ran: body.ran === true };
1048
+ }
1049
+ /**
1050
+ * Fetch the generated OpenAPI 3.1 document. Hits the admin-gated
1051
+ * `GET /_lunora/admin/openapi` endpoint — the worker must be built with an
1052
+ * `openApiSpec` and `adminToken`, and this client's auth token must match.
1053
+ * Powers `@lunora/studio`'s API-reference (Scalar) view. When the worker has
1054
+ * no spec wired, the endpoint still resolves with an empty-but-valid OpenAPI
1055
+ * document (no `paths`), so callers can render a "not configured" state.
1056
+ */
1057
+ async fetchOpenApi() {
1058
+ if (this.closed) {
1059
+ throw new Error("LunoraClient is closed");
1060
+ }
1061
+ return await this.adminFetch(OPENAPI_PATH, "GET");
1062
+ }
1063
+ /**
1064
+ * Fetch the generated OpenRPC 1.x document. Hits the admin-gated
1065
+ * `GET /_lunora/admin/openrpc` endpoint — the worker must be built with an
1066
+ * `openRpcSpec` and `adminToken`, and this client's auth token must match.
1067
+ * OpenRPC is the RPC-native spec (a `methods` array over the JSON-RPC-shaped
1068
+ * `POST /_lunora/rpc` transport); it documents the RPC functions only.
1069
+ * Powers `@lunora/studio`'s OpenRPC API-reference view. When the worker has
1070
+ * no spec wired, the endpoint still resolves with an empty-but-valid OpenRPC
1071
+ * document (no `methods`), so callers can render a "not configured" state.
1072
+ */
1073
+ async fetchOpenRpc() {
1074
+ if (this.closed) {
1075
+ throw new Error("LunoraClient is closed");
1076
+ }
1077
+ return await this.adminFetch(OPENRPC_PATH, "GET");
1078
+ }
1079
+ // --- Storage admin ------------------------------------------------------
1080
+ /**
1081
+ * List objects in the storage bucket, optionally under a `prefix` and from a
1082
+ * pagination `cursor`. Hits the admin-gated `GET /_lunora/admin/storage`
1083
+ * endpoint — the worker must be built with a `storageList` function and
1084
+ * `adminToken`, and this client's auth token must match. Powers
1085
+ * `@lunora/studio`'s file browser.
1086
+ */
1087
+ async listStorageObjects(options = {}) {
1088
+ if (this.closed) {
1089
+ throw new Error("LunoraClient is closed");
1090
+ }
1091
+ const params = new URLSearchParams();
1092
+ if (options.prefix !== void 0 && options.prefix !== "") {
1093
+ params.set("prefix", options.prefix);
1094
+ }
1095
+ if (options.cursor !== void 0 && options.cursor !== "") {
1096
+ params.set("cursor", options.cursor);
1097
+ }
1098
+ if (options.limit !== void 0) {
1099
+ params.set("limit", String(options.limit));
1100
+ }
1101
+ if (options.bucket !== void 0 && options.bucket !== "") {
1102
+ params.set("bucket", options.bucket);
1103
+ }
1104
+ const query = params.toString();
1105
+ const path = query === "" ? STORAGE_PATH : `${STORAGE_PATH}?${query}`;
1106
+ const body = await this.adminFetch(path, "GET");
1107
+ return { cursor: body.cursor, objects: body.objects ?? [] };
1108
+ }
1109
+ /**
1110
+ * Delete one object from the storage bucket by key. Hits the admin-gated
1111
+ * `DELETE /_lunora/admin/storage?key=…` endpoint — the worker must be built
1112
+ * with a `storageDelete` function and `adminToken`. Powers the studio file
1113
+ * browser's per-row delete; resolves `{ deleted, key }`.
1114
+ */
1115
+ async deleteStorageObject(key, options) {
1116
+ if (this.closed) {
1117
+ throw new Error("LunoraClient is closed");
1118
+ }
1119
+ const path = `${STORAGE_PATH}?key=${encodeURIComponent(key)}${bucketQuery(options?.bucket)}`;
1120
+ const body = await this.adminFetch(path, "DELETE");
1121
+ return { deleted: body.deleted ?? true, key: body.key ?? key };
1122
+ }
1123
+ /**
1124
+ * List the storage bucket names the worker exposes, for the studio file
1125
+ * browser's bucket picker. Hits the admin-gated
1126
+ * `GET /_lunora/admin/storage/buckets` endpoint — always resolves (an empty
1127
+ * array when the worker configures no `storageBuckets`, i.e. single-bucket).
1128
+ */
1129
+ async listStorageBuckets() {
1130
+ if (this.closed) {
1131
+ throw new Error("LunoraClient is closed");
1132
+ }
1133
+ const body = await this.adminFetch(STORAGE_BUCKETS_PATH, "GET");
1134
+ return body.buckets ?? [];
1135
+ }
1136
+ /**
1137
+ * Upload one object to the storage bucket. Hits the admin-gated
1138
+ * `PUT /_lunora/admin/storage?key=…` endpoint with the raw body and an
1139
+ * optional `contentType` header — the worker must be built with a
1140
+ * `storageUpload` function and `adminToken`. Powers the studio file
1141
+ * browser's upload control; resolves `{ etag?, key }`.
1142
+ */
1143
+ async uploadStorageObject(options) {
1144
+ if (this.closed) {
1145
+ throw new Error("LunoraClient is closed");
1146
+ }
1147
+ const path = `${STORAGE_PATH}?key=${encodeURIComponent(options.key)}${bucketQuery(options.bucket)}`;
1148
+ const body = await this.adminFetch(path, "PUT", options.body, options.contentType);
1149
+ return { etag: body.etag, key: body.key ?? options.key };
1150
+ }
1151
+ /**
1152
+ * Build a (signed or public) URL for one object. Hits the admin-gated
1153
+ * `GET /_lunora/admin/storage/url?key=…` endpoint — the worker must be built
1154
+ * with a `storageSignedUrl` function and `adminToken`. Powers the studio
1155
+ * file browser's copy-URL action; resolves the URL string.
1156
+ *
1157
+ * `options.expiresInSeconds` requests a share-link lifetime, which is
1158
+ * validated/clamped server-side. The options object mirrors the worker's
1159
+ * `StorageSignedUrlFunction` options (a `password` / download-limit are noted
1160
+ * as future fields there).
1161
+ */
1162
+ async signedStorageUrl(key, options) {
1163
+ if (this.closed) {
1164
+ throw new Error("LunoraClient is closed");
1165
+ }
1166
+ const expiresInSeconds = options?.expiresInSeconds;
1167
+ const expiryQuery = expiresInSeconds === void 0 ? "" : `&expiresIn=${encodeURIComponent(expiresInSeconds.toString())}`;
1168
+ const path = `${STORAGE_URL_PATH}?key=${encodeURIComponent(key)}${expiryQuery}${bucketQuery(options?.bucket)}`;
1169
+ const body = await this.adminFetch(path, "GET");
1170
+ if (typeof body.url !== "string") {
1171
+ throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");
1172
+ }
1173
+ return body.url;
1174
+ }
1175
+ // --- Global (D1) tables admin -------------------------------------------
1176
+ /**
1177
+ * List the `.global()` (D1-backed) tables with their row counts. Hits the
1178
+ * admin-gated `GET /_lunora/admin/global/tables` endpoint — the worker must
1179
+ * be built with a `globalIntrospector` and `adminToken`. Powers the data
1180
+ * browser's global mode.
1181
+ */
1182
+ async listGlobalTables() {
1183
+ if (this.closed) {
1184
+ throw new Error("LunoraClient is closed");
1185
+ }
1186
+ return await this.adminFetch(GLOBAL_TABLES_PATH, "GET");
1187
+ }
1188
+ /**
1189
+ * Read a page of rows from one `.global()` table. `filters` AND-narrows the
1190
+ * page to rows matching each `column = value` eq constraint — the drill-down a
1191
+ * facet-value click applies; the array is JSON-encoded into the `filters`
1192
+ * query param and the values are bound server-side.
1193
+ */
1194
+ async readGlobalTablePage(options) {
1195
+ if (this.closed) {
1196
+ throw new Error("LunoraClient is closed");
1197
+ }
1198
+ const params = new URLSearchParams({ table: options.table });
1199
+ if (options.limit !== void 0) {
1200
+ params.set("limit", String(options.limit));
1201
+ }
1202
+ if (options.offset !== void 0) {
1203
+ params.set("offset", String(options.offset));
1204
+ }
1205
+ if (options.filters !== void 0 && options.filters.length > 0) {
1206
+ params.set("filters", JSON.stringify(options.filters));
1207
+ }
1208
+ return await this.adminFetch(`${GLOBAL_TABLE_PATH}?${params.toString()}`, "GET");
1209
+ }
1210
+ /**
1211
+ * Summarise the distinct values of one column in a `.global()` table over the
1212
+ * active view (the same eq `filters` the browser is previewing) — the global
1213
+ * twin of the shard browser's facet. Hits the admin-gated
1214
+ * `GET /_lunora/admin/global/facet` endpoint; `column` is validated + bound
1215
+ * server-side. Powers the global data browser's facet sidebar.
1216
+ */
1217
+ async facetGlobalColumn(options) {
1218
+ if (this.closed) {
1219
+ throw new Error("LunoraClient is closed");
1220
+ }
1221
+ const params = new URLSearchParams({ column: options.column, table: options.table });
1222
+ if (options.limit !== void 0) {
1223
+ params.set("limit", String(options.limit));
1224
+ }
1225
+ if (options.filters !== void 0 && options.filters.length > 0) {
1226
+ params.set("filters", JSON.stringify(options.filters));
1227
+ }
1228
+ return await this.adminFetch(`${GLOBAL_FACET_PATH}?${params.toString()}`, "GET");
1229
+ }
1230
+ // --- Vector indexes admin -----------------------------------------------
1231
+ /**
1232
+ * List the schema's Vectorize indexes with their declared shape (table,
1233
+ * field, dimensions, metric, metadata) and live stats (vector count,
1234
+ * processing watermark) when the binding is reachable. Hits the admin-gated
1235
+ * `GET /_lunora/admin/vector/indexes` endpoint — the worker must be built
1236
+ * with a `vectorIntrospector` and `adminToken`. Powers the studio's vector
1237
+ * browser. Vectorize can't enumerate indexes at runtime, so this list comes
1238
+ * from the generated `LUNORA_VECTOR_INDEXES` registry.
1239
+ */
1240
+ async listVectorIndexes() {
1241
+ if (this.closed) {
1242
+ throw new Error("LunoraClient is closed");
1243
+ }
1244
+ const body = await this.adminFetch(VECTOR_INDEXES_PATH, "GET");
1245
+ return body.indexes ?? [];
1246
+ }
1247
+ /**
1248
+ * Run a nearest-neighbour similarity query against one vector index: the
1249
+ * worker embeds `text` via the index's embedder and returns the top matches.
1250
+ * Hits the admin-gated `POST /_lunora/admin/vector/query` endpoint. Throws
1251
+ * `VECTOR_QUERY_UNSUPPORTED` when the worker's introspector has no embedder
1252
+ * wired (the index lists read-only).
1253
+ */
1254
+ async queryVectorIndex(options) {
1255
+ if (this.closed) {
1256
+ throw new Error("LunoraClient is closed");
1257
+ }
1258
+ const body = await this.adminFetch(VECTOR_QUERY_PATH, "POST", options);
1259
+ return body.matches ?? [];
1260
+ }
1261
+ // --- Auth admin ---------------------------------------------------------
1262
+ /**
1263
+ * List authenticated users, paged and optionally searched / filtered / sorted.
1264
+ * Hits the admin-gated `GET /_lunora/admin/auth/users` endpoint — the worker
1265
+ * must be built with an `authAdmin` and `adminToken`. Powers the studio's
1266
+ * users dashboard.
1267
+ */
1268
+ async listAuthUsers(options = {}) {
1269
+ if (this.closed) {
1270
+ throw new Error("LunoraClient is closed");
1271
+ }
1272
+ const path = withQuery(AUTH_USERS_PATH, {
1273
+ filterField: options.filterField,
1274
+ filterValue: options.filterValue,
1275
+ limit: options.limit,
1276
+ offset: options.offset,
1277
+ search: options.search,
1278
+ searchField: options.searchField,
1279
+ sortBy: options.sortBy,
1280
+ sortDirection: options.sortDirection
1281
+ });
1282
+ return await this.adminFetch(path, "GET");
1283
+ }
1284
+ /**
1285
+ * Create a user. Hits the admin-gated `POST /_lunora/admin/auth/users/create`
1286
+ * endpoint (requires the worker's `authAdmin` to implement `createUser`).
1287
+ * `data` carries any app-defined `user.additionalFields`.
1288
+ */
1289
+ async createAuthUser(input) {
1290
+ return await this.adminFetch(AUTH_CREATE_USER_PATH, "POST", input);
1291
+ }
1292
+ /** Set a user's role (string, or array joined comma-wise server-side). */
1293
+ async setAuthUserRole(input) {
1294
+ return await this.adminFetch(AUTH_SET_ROLE_PATH, "POST", input);
1295
+ }
1296
+ /** Ban a user. `expiresInSeconds` sets a temporary ban; omit it for a permanent one. Revokes the user's live sessions. */
1297
+ async banAuthUser(input) {
1298
+ return await this.adminFetch(AUTH_BAN_PATH, "POST", input);
1299
+ }
1300
+ /** Lift a user's ban. */
1301
+ async unbanAuthUser(input) {
1302
+ return await this.adminFetch(AUTH_UNBAN_PATH, "POST", input);
1303
+ }
1304
+ /** Set a user's password (admin override — no current-password challenge). */
1305
+ async setAuthUserPassword(input) {
1306
+ await this.adminFetch(AUTH_SET_PASSWORD_PATH, "POST", input);
1307
+ }
1308
+ /** Permanently delete a user and revoke their sessions. */
1309
+ async removeAuthUser(input) {
1310
+ await this.adminFetch(AUTH_REMOVE_USER_PATH, "POST", input);
1311
+ }
1312
+ /**
1313
+ * Mint an impersonation session for a user, returning its bearer `token`.
1314
+ * The caller is responsible for using the token (e.g. setting the session
1315
+ * cookie); the server performs no cookie round-trip.
1316
+ */
1317
+ async impersonateAuthUser(input) {
1318
+ return await this.adminFetch(AUTH_IMPERSONATE_PATH, "POST", input);
1319
+ }
1320
+ /** Revoke a single session by its id (force sign-out of one device). */
1321
+ async revokeAuthSession(input) {
1322
+ await this.adminFetch(AUTH_REVOKE_SESSION_PATH, "POST", input);
1323
+ }
1324
+ /** Revoke every session for a user (force sign-out everywhere). */
1325
+ async revokeAuthUserSessions(input) {
1326
+ await this.adminFetch(AUTH_REVOKE_SESSIONS_PATH, "POST", input);
1327
+ }
1328
+ /**
1329
+ * Report which auth dashboard surfaces are available — derived server-side
1330
+ * from the enabled better-auth plugins. The studio renders only the panels
1331
+ * whose capability is `true`.
1332
+ */
1333
+ async getAuthCapabilities() {
1334
+ return await this.adminFetch(AUTH_CAPABILITIES_PATH, "GET");
1335
+ }
1336
+ /** Update a user's fields (name/email/app-defined `additionalFields`). */
1337
+ async updateAuthUser(input) {
1338
+ return await this.adminFetch(AUTH_UPDATE_USER_PATH, "POST", input);
1339
+ }
1340
+ /** List a user's linked accounts (credential / OAuth providers). Token material is stripped server-side. */
1341
+ async listAuthAccounts(input) {
1342
+ return await this.adminFetch(withQuery(AUTH_ACCOUNTS_PATH, { userId: input.userId }), "GET");
1343
+ }
1344
+ /** Unlink a linked account from a user. */
1345
+ async unlinkAuthAccount(input) {
1346
+ await this.adminFetch(AUTH_UNLINK_ACCOUNT_PATH, "POST", input);
1347
+ }
1348
+ /** List a user's registered passkeys (requires the passkey plugin). */
1349
+ async listAuthPasskeys(input) {
1350
+ return await this.adminFetch(withQuery(AUTH_PASSKEYS_PATH, { userId: input.userId }), "GET");
1351
+ }
1352
+ /** Delete a passkey by id (requires the passkey plugin). */
1353
+ async deleteAuthPasskey(input) {
1354
+ await this.adminFetch(AUTH_DELETE_PASSKEY_PATH, "POST", input);
1355
+ }
1356
+ /** Disable two-factor auth for a user (requires the two-factor plugin). */
1357
+ async disableAuthTwoFactor(input) {
1358
+ await this.adminFetch(AUTH_DISABLE_2FA_PATH, "POST", input);
1359
+ }
1360
+ /** List organizations, paged (requires the organization plugin). */
1361
+ async listAuthOrganizations(options = {}) {
1362
+ return await this.adminFetch(withQuery(AUTH_ORGS_PATH, { limit: options.limit, offset: options.offset }), "GET");
1363
+ }
1364
+ /** List the members of an organization (requires the organization plugin). */
1365
+ async listAuthOrgMembers(input) {
1366
+ const path = withQuery(AUTH_ORG_MEMBERS_PATH, { limit: input.limit, offset: input.offset, organizationId: input.organizationId });
1367
+ return await this.adminFetch(path, "GET");
1368
+ }
1369
+ /** List an organization's pending invitations (requires the organization plugin). */
1370
+ async listAuthOrgInvitations(input) {
1371
+ const path = withQuery(AUTH_ORG_INVITATIONS_PATH, { limit: input.limit, offset: input.offset, organizationId: input.organizationId });
1372
+ return await this.adminFetch(path, "GET");
1373
+ }
1374
+ /** Remove a member from an organization. */
1375
+ async removeAuthOrgMember(input) {
1376
+ await this.adminFetch(AUTH_REMOVE_MEMBER_PATH, "POST", input);
1377
+ }
1378
+ /** Cancel a pending organization invitation. */
1379
+ async cancelAuthOrgInvitation(input) {
1380
+ await this.adminFetch(AUTH_CANCEL_INVITATION_PATH, "POST", input);
1381
+ }
1382
+ /** List auth sessions, paged and optionally filtered to one user. */
1383
+ async listAuthSessions(options = {}) {
1384
+ if (this.closed) {
1385
+ throw new Error("LunoraClient is closed");
1386
+ }
1387
+ const params = new URLSearchParams();
1388
+ if (options.userId !== void 0 && options.userId !== "") {
1389
+ params.set("userId", options.userId);
1390
+ }
1391
+ if (options.limit !== void 0) {
1392
+ params.set("limit", String(options.limit));
1393
+ }
1394
+ if (options.offset !== void 0) {
1395
+ params.set("offset", String(options.offset));
1396
+ }
1397
+ const query = params.toString();
1398
+ return await this.adminFetch(query === "" ? AUTH_SESSIONS_PATH : `${AUTH_SESSIONS_PATH}?${query}`, "GET");
1399
+ }
1400
+ // --- Subscriptions ------------------------------------------------------
1401
+ subscribe(function_, args, callback, options = {}) {
1402
+ if (this.closed) {
1403
+ throw new Error("LunoraClient is closed");
1404
+ }
1405
+ const argsRecord = args ?? {};
1406
+ const key = SubscriptionRegistry.key(function_.__lunoraRef, argsRecord, options.shardKey);
1407
+ let state = this.subscriptions.get(key);
1408
+ const subscriptionCallback = callback;
1409
+ const errorCallback = options.onError;
1410
+ if (!state) {
1411
+ this.nextSubId += 1;
1412
+ const id = `sub_${this.nextSubId.toString()}`;
1413
+ const argsKey = stableStringify(argsRecord);
1414
+ const cached = this.takeHydratedCache(function_.__lunoraRef, argsKey, options.shardKey);
1415
+ state = {
1416
+ acked: false,
1417
+ args: argsRecord,
1418
+ argsKey,
1419
+ callbacks: /* @__PURE__ */ new Set(),
1420
+ checkpointCallbacks: /* @__PURE__ */ new Set(),
1421
+ errorCallbacks: /* @__PURE__ */ new Set(),
1422
+ fn: function_,
1423
+ id,
1424
+ lastValue: cached?.value,
1425
+ optimisticLayers: [],
1426
+ serverBase: cached?.value,
1427
+ serverCursor: cached?.serverCursor,
1428
+ shardKey: options.shardKey,
1429
+ ...cached?.serverEpoch === void 0 ? {} : { serverEpoch: cached.serverEpoch }
1430
+ };
1431
+ this.subscriptions.add(state);
1432
+ }
1433
+ state.callbacks.add(subscriptionCallback);
1434
+ if (errorCallback) {
1435
+ state.errorCallbacks.add(errorCallback);
1436
+ }
1437
+ if (options.onCheckpoint) {
1438
+ state.checkpointCallbacks.add(options.onCheckpoint);
1439
+ }
1440
+ if (state.lastValue !== void 0) {
1441
+ try {
1442
+ subscriptionCallback(state.lastValue);
1443
+ } catch {
1444
+ }
1445
+ }
1446
+ this.ensureSocket(options.shardKey);
1447
+ this.sendSubscribeIfOpen(state);
1448
+ const subscriptionState = state;
1449
+ return () => {
1450
+ subscriptionState.callbacks.delete(subscriptionCallback);
1451
+ if (errorCallback) {
1452
+ subscriptionState.errorCallbacks.delete(errorCallback);
1453
+ }
1454
+ if (options.onCheckpoint) {
1455
+ subscriptionState.checkpointCallbacks.delete(options.onCheckpoint);
1456
+ }
1457
+ if (subscriptionState.callbacks.size === 0) {
1458
+ const conn = this.getConnection(subscriptionState.shardKey);
1459
+ const ok = conn ? sendOn(conn, { id: subscriptionState.id, type: "unsubscribe" }) : false;
1460
+ if (!ok && conn) {
1461
+ conn.pendingUnsubscribes.push({ id: subscriptionState.id, type: "unsubscribe" });
1462
+ }
1463
+ this.subscriptions.remove(subscriptionState);
1464
+ }
1465
+ };
1466
+ }
1467
+ /**
1468
+ * Subscribe to a declarative **shape** — server-side partial replication
1469
+ * scoped by `shardBy` + the shape's predicate + RLS. The parallel to
1470
+ * {@link subscribe} for the poke protocol: the client sends the shape *name* +
1471
+ * validated `args` (never a `where` the client could forge), the server seeds
1472
+ * the current membership as an insert-poke and streams live membership diffs.
1473
+ * Each applied poke materializes the shape's rowset and invokes `callback`.
1474
+ *
1475
+ * Unlike {@link subscribe}, shape subscriptions are NOT deduped by
1476
+ * (name, args): the server resolves them under the socket's verified identity,
1477
+ * so every call gets its own id + view. The returned function unsubscribes.
1478
+ */
1479
+ subscribeShape(shape, callback, options = {}) {
1480
+ if (this.closed) {
1481
+ throw new Error("LunoraClient is closed");
1482
+ }
1483
+ this.nextShapeId += 1;
1484
+ const id = `shape_${this.nextShapeId.toString()}`;
1485
+ const state = {
1486
+ args: shape.args,
1487
+ callbacks: /* @__PURE__ */ new Set([callback]),
1488
+ errorCallbacks: options.onError ? /* @__PURE__ */ new Set([options.onError]) : /* @__PURE__ */ new Set(),
1489
+ id,
1490
+ name: shape.name,
1491
+ onCheckpoint: options.onCheckpoint,
1492
+ rows: /* @__PURE__ */ new Map(),
1493
+ shardKey: options.shardKey
1494
+ };
1495
+ this.shapeSubscriptions.set(id, state);
1496
+ this.ensureSocket(options.shardKey);
1497
+ this.sendShapeSubscribeIfOpen(state);
1498
+ return () => {
1499
+ this.shapeSubscriptions.delete(id);
1500
+ const conn = this.getConnection(state.shardKey);
1501
+ const ok = conn ? sendOn(conn, { id, type: "shape_unsubscribe" }) : false;
1502
+ if (!ok && conn) {
1503
+ conn.pendingUnsubscribes.push({ id, type: "shape_unsubscribe" });
1504
+ }
1505
+ };
1506
+ }
1507
+ /**
1508
+ * Open a streaming query. The function reference must be a
1509
+ * `kind:"stream"` registration (built with `c.query.input(...).stream(...)`);
1510
+ * the type constraint catches accidental use of a query/mutation/action
1511
+ * reference at compile time. The returned iterable yields one element per
1512
+ * chunk frame the server pushes, terminating when the server sends
1513
+ * `complete` or the consumer calls `.cancel()`. Errors arrive as a
1514
+ * rejection on the next `next()`.
1515
+ *
1516
+ * Streams ride the same WS as subscriptions and share the unsubscribe
1517
+ * channel: cancelling sends `{type:"unsubscribe", id}` with the stream id,
1518
+ * which the DO recognises as an abort signal for the in-flight iterator.
1519
+ *
1520
+ * Stream-start frames buffered while the socket is (re)connecting are
1521
+ * capped at {@link MAX_PENDING_STREAMS} per connection — overflowing the
1522
+ * cap drops the oldest queued frame (and fails its consumer) so a stuck
1523
+ * reconnect can't OOM the page.
1524
+ */
1525
+ stream(function_, args, options = {}) {
1526
+ if (this.closed) {
1527
+ throw new Error("LunoraClient is closed");
1528
+ }
1529
+ if (this.WebSocketImpl === void 0) {
1530
+ throw new Error("LunoraClient: streams require a WebSocket implementation");
1531
+ }
1532
+ this.nextStreamId += 1;
1533
+ const id = `stream_${this.nextStreamId.toString()}`;
1534
+ const { shardKey } = options;
1535
+ const argsRecord = args ?? {};
1536
+ const { handle, iterable } = createStream({
1537
+ maxBuffer: options.maxBuffer,
1538
+ onCancel: () => {
1539
+ const conn2 = this.getConnection(shardKey);
1540
+ if (conn2) {
1541
+ sendOn(conn2, { id, type: "unsubscribe" });
1542
+ }
1543
+ this.streams.delete(id);
1544
+ }
1545
+ });
1546
+ this.streams.set(id, { handle, shardKey });
1547
+ this.ensureSocket(shardKey);
1548
+ const conn = this.getConnection(shardKey);
1549
+ const message = {
1550
+ id,
1551
+ query: { args: argsRecord, functionPath: function_.__lunoraRef, shardKey },
1552
+ type: "stream"
1553
+ };
1554
+ const sentImmediately = conn?.wsState === "open" && sendOn(conn, message);
1555
+ if (!sentImmediately && conn) {
1556
+ conn.pendingStreams = conn.pendingStreams ?? [];
1557
+ while (conn.pendingStreams.length >= MAX_PENDING_STREAMS) {
1558
+ const dropped = conn.pendingStreams.shift();
1559
+ const droppedId = dropped?.id;
1560
+ const droppedStream = droppedId ? this.streams.get(droppedId) : void 0;
1561
+ if (droppedStream) {
1562
+ droppedStream.handle.fail(
1563
+ Object.assign(new Error("stream-start frame evicted while socket was unreachable"), { code: "STREAM_QUEUE_OVERFLOW" })
1564
+ );
1565
+ this.streams.delete(droppedId);
1566
+ }
1567
+ }
1568
+ conn.pendingStreams.push(message);
1569
+ }
1570
+ return iterable;
1571
+ }
1572
+ close() {
1573
+ this.closed = true;
1574
+ this.outboxLeaderRelease?.();
1575
+ this.outboxLeaderRelease = void 0;
1576
+ for (const stream of this.streams.values()) {
1577
+ stream.handle.fail(Object.assign(new Error("LunoraClient closed"), { code: "CLIENT_CLOSED" }));
1578
+ }
1579
+ this.streams.clear();
1580
+ for (const conn of this.connections.values()) {
1581
+ if (conn.reconnectTimer !== void 0) {
1582
+ clearTimeout(conn.reconnectTimer);
1583
+ conn.reconnectTimer = void 0;
1584
+ }
1585
+ if (conn.connectTimer !== void 0) {
1586
+ clearTimeout(conn.connectTimer);
1587
+ conn.connectTimer = void 0;
1588
+ }
1589
+ this.stopHeartbeat(conn);
1590
+ if (conn.socket) {
1591
+ try {
1592
+ conn.socket.close();
1593
+ } catch {
1594
+ }
1595
+ conn.socket = void 0;
1596
+ }
1597
+ conn.wsState = "closed";
1598
+ }
1599
+ this.offlineQueue.clear();
1600
+ this.queuedIdentities.clear();
1601
+ if (this.cacheFlushTimer !== void 0) {
1602
+ clearTimeout(this.cacheFlushTimer);
1603
+ this.cacheFlushTimer = void 0;
1604
+ }
1605
+ if (this.pendingCacheWrites.size > 0) {
1606
+ this.flushQueryCacheWrites().catch(() => void 0);
1607
+ }
1608
+ this.authTokenListeners.clear();
1609
+ this.statusListeners.clear();
1610
+ this.tokenExpiredListeners.clear();
1611
+ this.mutationSettledListeners.clear();
1612
+ this.pendingChangeListeners.clear();
1613
+ this.whisperHandlers.clear();
1614
+ this.shapeSubscriptions.clear();
1615
+ this.pokeBuffers.clear();
1616
+ }
1617
+ // --- Internals ----------------------------------------------------------
1618
+ /**
1619
+ * Persist a mutation that can't go out on the wire right now (offline, or
1620
+ * mid-reconnect after a prior connect). The optimistic update has already
1621
+ * been applied by `mutation`; this only chooses the durable write path and
1622
+ * rolls the optimistic write back if persistence is rejected.
1623
+ *
1624
+ * Two paths: when an `outbox` sink is wired (the `@lunora/db` executor) it
1625
+ * owns persistence + at-least-once replay, so we delegate and return
1626
+ * optimistically (confirmation rides the synced view). Otherwise the
1627
+ * built-in `OfflineQueue` resolves/rejects the returned promise on replay.
1628
+ */
1629
+ async enqueueOfflineMutation(function_, argsRecord, shardKey, mutationId, optimisticRollbacks, optimisticConfirms) {
1630
+ const issuingIdentity = this.identityFingerprint();
1631
+ if (this.outbox) {
1632
+ this.outboxMutationCounter += 1;
1633
+ const outboxMutationId = this.outboxMutationCounter;
1634
+ try {
1635
+ await this.outbox.enqueue({
1636
+ args: argsRecord,
1637
+ clientId: this.clientId,
1638
+ functionPath: function_.__lunoraRef,
1639
+ idempotencyKey: `${this.clientId}:${String(outboxMutationId)}`,
1640
+ identity: issuingIdentity,
1641
+ mutationId: outboxMutationId,
1642
+ shardKey
1643
+ });
1644
+ } catch (error) {
1645
+ rollbackOptimistic(optimisticRollbacks);
1646
+ throw error instanceof Error ? error : new Error(String(error));
1647
+ }
1648
+ for (const confirm of optimisticConfirms) {
1649
+ confirm(void 0);
1650
+ }
1651
+ return void 0;
1652
+ }
1653
+ return new Promise((resolve, reject) => {
1654
+ const entry = {
1655
+ args: argsRecord,
1656
+ functionPath: function_.__lunoraRef,
1657
+ // A live caller is awaiting this Promise, so a terminal verdict
1658
+ // reaches them directly; the observer event carries
1659
+ // `hadAwaiter: true`. Hydrated replays leave this unset.
1660
+ liveAwaiter: true,
1661
+ // Reuse the call's idempotency key as the queue id so the replay
1662
+ // carries the same `x-lunora-mutation-id` the server dedups on.
1663
+ id: mutationId,
1664
+ // Persist the stamp alongside the record so a hydrated write can
1665
+ // only replay under the identity that queued it.
1666
+ identity: issuingIdentity,
1667
+ // Confirm the per-call optimistic layer(s) against the commit cursor
1668
+ // the flush replay echoes (see flushOfflineQueue).
1669
+ onCommit: (commitCursor) => {
1670
+ for (const confirm of optimisticConfirms) {
1671
+ confirm(commitCursor);
1672
+ }
1673
+ },
1674
+ reject: (error) => {
1675
+ this.queuedIdentities.delete(mutationId);
1676
+ rollbackOptimistic(optimisticRollbacks);
1677
+ reject(error instanceof Error ? error : new Error(String(error)));
1678
+ },
1679
+ resolve,
1680
+ shardKey
1681
+ };
1682
+ this.offlineQueue.enqueue(entry);
1683
+ if (entry.id !== void 0) {
1684
+ this.queuedIdentities.set(entry.id, issuingIdentity);
1685
+ }
1686
+ });
1687
+ }
1688
+ /**
1689
+ * Restore offline mutations persisted in a prior session and open a socket
1690
+ * for each shard they target so they flush once the WS reconnects. Failures
1691
+ * are swallowed — a broken durable store must not stop the client booting.
1692
+ */
1693
+ async hydratePersistedQueue() {
1694
+ try {
1695
+ const shardKeys = await this.offlineQueue.hydrate();
1696
+ for (const shardKey of shardKeys) {
1697
+ this.ensureSocket(shardKey);
1698
+ }
1699
+ } catch {
1700
+ }
1701
+ }
1702
+ /**
1703
+ * Re-queue the durable offline writes — but only as the multi-tab LEADER. The
1704
+ * persisted queue is shared across a profile's tabs; without coordination
1705
+ * every tab would re-queue and replay the same writes (correct only because
1706
+ * the server dedups by idempotency key, but wasteful + racy). A Web Lock makes
1707
+ * exactly one tab hydrate; it holds the lock for its lifetime, so when it
1708
+ * closes another tab acquires the lock and takes over. Falls back to
1709
+ * unconditional hydration where Web Locks are unavailable (React Native, older
1710
+ * browsers, SSR) — single-context there, so no coordination is needed.
1711
+ */
1712
+ hydrateAsOutboxLeader() {
1713
+ const hydrate = () => {
1714
+ this.hydratePersistedQueue().catch(() => void 0);
1715
+ };
1716
+ const locks = globalThis.navigator?.locks;
1717
+ if (!locks) {
1718
+ hydrate();
1719
+ return;
1720
+ }
1721
+ locks.request(`lunora:outbox-leader:${this.url}`, () => {
1722
+ if (!this.closed) {
1723
+ hydrate();
1724
+ }
1725
+ return new Promise((resolve) => {
1726
+ if (this.closed) {
1727
+ resolve();
1728
+ return;
1729
+ }
1730
+ this.outboxLeaderRelease = resolve;
1731
+ });
1732
+ }).catch(hydrate);
1733
+ }
1734
+ /**
1735
+ * Load every cached query into {@link hydratedQueryCache} so the next
1736
+ * `subscribe()` for each key seeds its initial value off disk. A
1737
+ * subscription created before this resolves simply misses the cache (it
1738
+ * gets a live snapshot as before); the gate at seed time also drops any
1739
+ * entry whose stamped identity no longer matches the current one.
1740
+ */
1741
+ async hydrateQueryCache() {
1742
+ if (!this.queryCache) {
1743
+ return;
1744
+ }
1745
+ try {
1746
+ const entries = await this.queryCache.load();
1747
+ for (const { key, ...entry } of entries) {
1748
+ if (isStaleVersion(this.persistenceVersion, entry.version)) {
1749
+ this.queryCache.remove(key).catch(() => void 0);
1750
+ continue;
1751
+ }
1752
+ this.hydratedQueryCache.set(key, entry);
1753
+ }
1754
+ } catch {
1755
+ }
1756
+ }
1757
+ /**
1758
+ * Consume the hydrated read-cache entry for a key (if any), gated on
1759
+ * identity. The entry is removed whether or not it matches — the cache only
1760
+ * ever seeds a subscription's first value. A mismatch (the cache was written
1761
+ * under a different identity) yields `undefined` so a signed-out cache never
1762
+ * leaks into a new session.
1763
+ */
1764
+ takeHydratedCache(functionPath, argsKey, shardKey) {
1765
+ const key = queryCacheKey(functionPath, argsKey, shardKey);
1766
+ const entry = this.hydratedQueryCache.get(key);
1767
+ if (entry === void 0) {
1768
+ return void 0;
1769
+ }
1770
+ this.hydratedQueryCache.delete(key);
1771
+ return entry.identity === this.identityFingerprint() ? entry : void 0;
1772
+ }
1773
+ /**
1774
+ * Queue a coalesced read-cache write for a subscription's current value.
1775
+ * Latest-wins per key; flushed on a short debounce so a delta burst writes
1776
+ * once. No-op when the read cache is disabled or the value is undefined
1777
+ * (nothing to render offline).
1778
+ */
1779
+ persistQueryValue(state) {
1780
+ const authoritative = state.serverBase;
1781
+ if (!this.queryCache || authoritative === void 0) {
1782
+ return;
1783
+ }
1784
+ const key = queryCacheKey(state.fn.__lunoraRef, state.argsKey, state.shardKey);
1785
+ this.pendingCacheWrites.set(key, {
1786
+ identity: this.identityFingerprint(),
1787
+ serverCursor: state.serverCursor,
1788
+ ts: Date.now(),
1789
+ value: authoritative,
1790
+ ...state.serverEpoch === void 0 ? {} : { serverEpoch: state.serverEpoch },
1791
+ ...this.persistenceVersion === void 0 ? {} : { version: this.persistenceVersion }
1792
+ });
1793
+ this.cacheFlushTimer ??= setTimeout(() => {
1794
+ this.flushQueryCacheWrites().catch(() => void 0);
1795
+ }, QUERY_CACHE_DEBOUNCE_MS);
1796
+ }
1797
+ /** Drain {@link pendingCacheWrites} to the durable store. */
1798
+ async flushQueryCacheWrites() {
1799
+ this.cacheFlushTimer = void 0;
1800
+ const { queryCache } = this;
1801
+ if (!queryCache) {
1802
+ this.pendingCacheWrites.clear();
1803
+ return;
1804
+ }
1805
+ const batch = [...this.pendingCacheWrites.entries()];
1806
+ this.pendingCacheWrites.clear();
1807
+ await Promise.allSettled(batch.map(([key, entry]) => queryCache.put(key, entry)));
1808
+ }
1809
+ /** Derive the aggregate status from the per-shard socket states. */
1810
+ computeStatus() {
1811
+ const conns = [...this.connections.values()];
1812
+ if (conns.length === 0) {
1813
+ return "idle";
1814
+ }
1815
+ if (conns.some((conn) => conn.wsState === "open")) {
1816
+ return "connected";
1817
+ }
1818
+ if (conns.some((conn) => conn.wsState === "connecting")) {
1819
+ return "connecting";
1820
+ }
1821
+ return "offline";
1822
+ }
1823
+ /** Recompute the aggregate status and notify listeners if it changed. */
1824
+ emitConnectionStatus() {
1825
+ const next = this.computeStatus();
1826
+ if (next === this.lastStatus) {
1827
+ return;
1828
+ }
1829
+ this.lastStatus = next;
1830
+ this.statusListeners.emit(next);
1831
+ }
1832
+ /**
1833
+ * Build a {@link MutationSettledEvent} from a queued entry and emit it on the
1834
+ * {@link onMutationSettled} channel. `item.id` is always assigned by the time
1835
+ * a write settles (`enqueue`/`hydrate` guarantee it), so the `?? ""` fallback
1836
+ * is unreachable — present only to satisfy the optional queue-id type.
1837
+ */
1838
+ emitItemSettled(item, status, error) {
1839
+ this.mutationSettledListeners.emit({
1840
+ args: item.args,
1841
+ code: error === void 0 ? void 0 : error.code,
1842
+ error,
1843
+ functionPath: item.functionPath,
1844
+ hadAwaiter: item.liveAwaiter ?? false,
1845
+ id: item.id ?? "",
1846
+ shardKey: item.shardKey,
1847
+ status
1848
+ });
1849
+ }
1850
+ /**
1851
+ * Apply an optimistic update to the subscription that matches the mutation's
1852
+ * `(functionRef, args, shardKey)` triple, returning the rollback callbacks to
1853
+ * invoke if the mutation later fails.
1854
+ *
1855
+ * The registry is already indexed by exactly this triple via
1856
+ * `SubscriptionRegistry.key`, so at most one subscription can match. A direct
1857
+ * O(1) keyed lookup replaces the former O(N) linear scan over all subscriptions.
1858
+ *
1859
+ * `shardKey` normalization: both `undefined` and `""` map to the empty string
1860
+ * inside `SubscriptionRegistry.key` (via `?? ""`), so a mutation fired without
1861
+ * a shardKey correctly matches a subscription registered without one regardless
1862
+ * of whether the caller passed `undefined` or omitted the field.
1863
+ */
1864
+ applyOptimisticUpdates(functionRef, argsRecord, mutationShardKey, optimistic) {
1865
+ const confirms = [];
1866
+ const rollbacks = [];
1867
+ if (!optimistic) {
1868
+ return { confirms, rollbacks };
1869
+ }
1870
+ const matchKey = SubscriptionRegistry.key(functionRef, argsRecord, mutationShardKey);
1871
+ const state = this.subscriptions.get(matchKey);
1872
+ if (state) {
1873
+ const handle = applyOptimisticLayer(state, optimistic);
1874
+ if (handle) {
1875
+ confirms.push(handle.confirm);
1876
+ rollbacks.push(handle.rollback);
1877
+ }
1878
+ }
1879
+ return { confirms, rollbacks };
1880
+ }
1881
+ /**
1882
+ * Run a Convex-parity `optimisticUpdate` callback against a localStore bound
1883
+ * to the live subscription registry. Each `setQuery` registers a constant
1884
+ * optimistic LAYER on its target subscription (via the same engine the
1885
+ * per-call `optimistic` path uses), so the multi-query patch rebases onto
1886
+ * incoming deltas and drops gaplessly on its commit cursor — its `confirm` /
1887
+ * `rollback` closures are appended to the mutation's settle lists. A throwing
1888
+ * callback unwinds its own partial writes — LIFO over just the rollbacks it
1889
+ * produced — and is swallowed, so a buggy optimistic update can never fail the
1890
+ * mutation or leave a partial patch live.
1891
+ */
1892
+ applyOptimisticUpdate(optimisticUpdate, args, shardKey, optimisticRollbacks, optimisticConfirms) {
1893
+ const { confirms, rollbacks, store } = createLocalStore(this.subscriptions, shardKey, stableStringify);
1894
+ try {
1895
+ optimisticUpdate(store, args);
1896
+ } catch {
1897
+ for (let index = rollbacks.length - 1; index >= 0; index -= 1) {
1898
+ rollbacks[index]?.();
1899
+ }
1900
+ return;
1901
+ }
1902
+ optimisticRollbacks.push(...rollbacks);
1903
+ optimisticConfirms.push(...confirms);
1904
+ }
1905
+ getConnection(shardKey) {
1906
+ return this.connections.get(connectionKey(shardKey));
1907
+ }
1908
+ getOrCreateConnection(shardKey) {
1909
+ const key = connectionKey(shardKey);
1910
+ let conn = this.connections.get(key);
1911
+ if (!conn) {
1912
+ conn = {
1913
+ connectTimer: void 0,
1914
+ heartbeatTimer: void 0,
1915
+ pendingUnsubscribes: [],
1916
+ reconnect: createReconnect(this.reconnectOptions),
1917
+ reconnectTimer: void 0,
1918
+ shardKey,
1919
+ socket: void 0,
1920
+ wasEverConnected: false,
1921
+ wsState: "idle"
1922
+ };
1923
+ this.connections.set(key, conn);
1924
+ }
1925
+ return conn;
1926
+ }
1927
+ wsUrlFor(shardKey) {
1928
+ const params = [];
1929
+ if (shardKey !== void 0) {
1930
+ params.push(`shard=${encodeURIComponent(shardKey)}`);
1931
+ }
1932
+ if (this.wsToken !== void 0) {
1933
+ params.push(`token=${encodeURIComponent(this.wsToken)}`);
1934
+ }
1935
+ if (params.length === 0) {
1936
+ return this.wsUrl;
1937
+ }
1938
+ const separator = this.wsUrl.includes("?") ? "&" : "?";
1939
+ return `${this.wsUrl}${separator}${params.join("&")}`;
1940
+ }
1941
+ /**
1942
+ * Build the outbound RPC headers: JSON content type, optional bearer auth,
1943
+ * the optional mutation-replay idempotency key, and the D1 read-your-writes
1944
+ * bookmark when the caller opted into `attachBookmark`. The mutation id
1945
+ * rides both the direct send and any offline-queue replay of the same write,
1946
+ * so a mutation the server already committed returns its cached result
1947
+ * instead of running twice.
1948
+ */
1949
+ rpcRequestHeaders(flags) {
1950
+ const headers = { "content-type": "application/json" };
1951
+ if (this.authToken) {
1952
+ headers["authorization"] = `Bearer ${this.authToken}`;
1953
+ }
1954
+ if (flags.mutationId) {
1955
+ headers["x-lunora-mutation-id"] = flags.mutationId;
1956
+ }
1957
+ if (flags.clientId !== void 0) {
1958
+ headers["x-lunora-client-id"] = flags.clientId;
1959
+ }
1960
+ if (flags.clientSeq !== void 0) {
1961
+ headers["x-lunora-client-seq"] = flags.clientSeq.toString();
1962
+ }
1963
+ if (flags.attachBookmark) {
1964
+ const bookmark = this.bookmark.get();
1965
+ if (bookmark) {
1966
+ headers["x-d1-bookmark"] = bookmark;
1967
+ }
1968
+ }
1969
+ return headers;
1970
+ }
1971
+ async rpc(functionPath, args, shardKey, flags = {}) {
1972
+ if (!this.fetchImpl) {
1973
+ throw new Error("LunoraClient: no `fetch` implementation available");
1974
+ }
1975
+ const headers = this.rpcRequestHeaders(flags);
1976
+ const response = await this.fetchImpl(joinUrl(this.url, RPC_PATH), {
1977
+ body: JSON.stringify({ args, functionPath, shardKey }),
1978
+ headers,
1979
+ method: "POST"
1980
+ });
1981
+ if (flags.captureBookmark) {
1982
+ const value = response.headers.get("x-d1-bookmark");
1983
+ if (value) {
1984
+ this.bookmark.set(value);
1985
+ }
1986
+ }
1987
+ let body;
1988
+ try {
1989
+ body = await response.json();
1990
+ } catch {
1991
+ const statusText = response.statusText ? ` ${response.statusText}` : "";
1992
+ throw new Error(`LunoraClient: response was not JSON (status ${response.status.toString()}${statusText})`);
1993
+ }
1994
+ if ("error" in body) {
1995
+ const error = new Error(body.error.message);
1996
+ error.code = body.error.code;
1997
+ throw error;
1998
+ }
1999
+ if (!response.ok) {
2000
+ const statusText = response.statusText ? ` ${response.statusText}` : "";
2001
+ throw new Error(`LunoraClient: request failed (status ${response.status.toString()}${statusText})`);
2002
+ }
2003
+ flags.onMutationAck?.(body.lastMutationId);
2004
+ flags.onCommitCursor?.(body.commitCursor);
2005
+ return body.result;
2006
+ }
2007
+ /**
2008
+ * Authenticated request to a non-RPC admin endpoint (the scheduler list /
2009
+ * cancel routes). Attaches the bearer token, parses JSON, and surfaces the
2010
+ * worker's `{ error: { code, message } }` envelope as a coded `Error` —
2011
+ * mirroring {@link rpc} so callers see the same failure shape.
2012
+ */
2013
+ async adminFetch(path, method, payload, contentType) {
2014
+ if (!this.fetchImpl) {
2015
+ throw new Error("LunoraClient: no `fetch` implementation available");
2016
+ }
2017
+ const headers = {};
2018
+ if (this.authToken) {
2019
+ headers["authorization"] = `Bearer ${this.authToken}`;
2020
+ }
2021
+ const isBinary = payload instanceof ArrayBuffer || payload instanceof Blob;
2022
+ let requestBody;
2023
+ if (payload === void 0) {
2024
+ requestBody = void 0;
2025
+ } else if (isBinary) {
2026
+ requestBody = payload;
2027
+ if (contentType !== void 0) {
2028
+ headers["content-type"] = contentType;
2029
+ }
2030
+ } else {
2031
+ requestBody = JSON.stringify(payload);
2032
+ headers["content-type"] = "application/json";
2033
+ }
2034
+ const response = await this.fetchImpl(joinUrl(this.url, path), {
2035
+ body: requestBody,
2036
+ headers,
2037
+ method
2038
+ });
2039
+ let body;
2040
+ try {
2041
+ body = await response.json();
2042
+ } catch {
2043
+ const statusText = response.statusText ? ` ${response.statusText}` : "";
2044
+ throw new Error(`LunoraClient: response was not JSON (status ${response.status.toString()}${statusText})`);
2045
+ }
2046
+ if (typeof body === "object" && body !== null && "error" in body) {
2047
+ const envelope = body.error;
2048
+ const error = new Error(envelope.message ?? "admin request failed");
2049
+ error.code = envelope.code;
2050
+ throw error;
2051
+ }
2052
+ if (!response.ok) {
2053
+ const statusText = response.statusText ? ` ${response.statusText}` : "";
2054
+ throw new Error(`LunoraClient: admin request failed (status ${response.status.toString()}${statusText})`);
2055
+ }
2056
+ return body;
2057
+ }
2058
+ /**
2059
+ * Resolve the effective connection context for a shard: the most-recently
2060
+ * acquired refcounted holder ({@link acquireConnectionContext}) wins, falling
2061
+ * back to the imperative {@link setConnectionContext} override, then the
2062
+ * client-wide default. Returns `undefined` when none apply.
2063
+ */
2064
+ effectiveConnectionContext(key) {
2065
+ const holders = this.connectionContextHolders.get(key);
2066
+ if (holders && holders.length > 0) {
2067
+ return holders[holders.length - 1]?.context;
2068
+ }
2069
+ return this.connectionContexts.get(key) ?? this.defaultConnectionContext;
2070
+ }
2071
+ /** Re-send the `connect` envelope for a shard whose effective context just changed (if its socket is open). */
2072
+ refreshConnectionContext(key) {
2073
+ const conn = this.connections.get(key);
2074
+ if (conn?.wsState === "open") {
2075
+ this.sendConnectEnvelope(conn);
2076
+ }
2077
+ }
2078
+ /**
2079
+ * Send the one-shot `connect` envelope on an open shard socket. Always sent
2080
+ * once per socket open, so the server's `onConnect` hooks fire symmetrically
2081
+ * with `onDisconnect` (which the DO dispatches unconditionally at close for
2082
+ * every lifecycle-aware socket). The DO no-ops cheaply when no `onConnect`
2083
+ * hooks are registered, so the single frame costs nothing in the common case.
2084
+ *
2085
+ * The shard's registered context (or the client-wide default) rides along
2086
+ * when one is set — the DO records it on the attachment for replay to
2087
+ * `onDisconnect`. A socket with no registered context still announces itself;
2088
+ * the envelope simply omits `context`, which is optional on the wire.
2089
+ * Register a context — e.g. `setConnectionContext({})` — to attach app state
2090
+ * to the lifecycle dispatch.
2091
+ */
2092
+ sendConnectEnvelope(conn) {
2093
+ const context = this.effectiveConnectionContext(connectionKey(conn.shardKey));
2094
+ sendOn(conn, {
2095
+ // Lets the server scope this connection's `__client_watermark` so
2096
+ // custom-mutator pokes can echo this client's `lastMutationId`.
2097
+ clientId: this.clientId,
2098
+ id: "connect",
2099
+ type: "connect",
2100
+ ...context === void 0 ? {} : { context }
2101
+ });
2102
+ }
2103
+ /**
2104
+ * Re-send every shape subscription bound to `shardKey` over its (now open)
2105
+ * socket. Each frame carries the shape's last applied checkpoint, so the
2106
+ * server resumes from it — or re-seeds when the cursor fell below CDC
2107
+ * retention or the epoch forked.
2108
+ */
2109
+ resendShapeSubscriptions(shardKey) {
2110
+ for (const state of this.shapeSubscriptions.values()) {
2111
+ if (connectionKey(state.shardKey) === connectionKey(shardKey)) {
2112
+ this.sendShapeSubscribeIfOpen(state);
2113
+ }
2114
+ }
2115
+ }
2116
+ ensureSocket(shardKey) {
2117
+ if (this.closed || this.WebSocketImpl === void 0) {
2118
+ return;
2119
+ }
2120
+ const conn = this.getOrCreateConnection(shardKey);
2121
+ if (conn.wsState === "open" || conn.wsState === "connecting") {
2122
+ return;
2123
+ }
2124
+ conn.wsState = "connecting";
2125
+ this.emitConnectionStatus();
2126
+ const socket = new this.WebSocketImpl(this.wsUrlFor(shardKey));
2127
+ conn.socket = socket;
2128
+ if (this.connectTimeoutMs > 0) {
2129
+ conn.connectTimer = setTimeout(() => {
2130
+ conn.connectTimer = void 0;
2131
+ if (conn.socket !== socket || conn.wsState !== "connecting") {
2132
+ return;
2133
+ }
2134
+ try {
2135
+ socket.close();
2136
+ } catch {
2137
+ }
2138
+ this.handleDisconnect(conn);
2139
+ }, this.connectTimeoutMs);
2140
+ }
2141
+ socket.addEventListener("open", () => {
2142
+ if (conn.socket !== socket) {
2143
+ return;
2144
+ }
2145
+ if (conn.connectTimer !== void 0) {
2146
+ clearTimeout(conn.connectTimer);
2147
+ conn.connectTimer = void 0;
2148
+ }
2149
+ conn.wsState = "open";
2150
+ conn.wasEverConnected = true;
2151
+ conn.reconnect.reset();
2152
+ this.emitConnectionStatus();
2153
+ this.sendConnectEnvelope(conn);
2154
+ this.markShardPendingAck(shardKey);
2155
+ for (const state of this.subscriptions.all()) {
2156
+ if (connectionKey(state.shardKey) === connectionKey(shardKey)) {
2157
+ this.sendSubscribeIfOpen(state);
2158
+ }
2159
+ }
2160
+ this.resendShapeSubscriptions(shardKey);
2161
+ if (conn.pendingUnsubscribes.length > 0) {
2162
+ const pending = conn.pendingUnsubscribes;
2163
+ conn.pendingUnsubscribes = [];
2164
+ for (const { id, type } of pending) {
2165
+ sendOn(conn, { id, type });
2166
+ }
2167
+ }
2168
+ if (conn.pendingStreams && conn.pendingStreams.length > 0) {
2169
+ const pending = conn.pendingStreams;
2170
+ conn.pendingStreams = [];
2171
+ for (const message of pending) {
2172
+ sendOn(conn, message);
2173
+ }
2174
+ }
2175
+ const byTopic = this.whisperHandlers.get(connectionKey(shardKey));
2176
+ if (byTopic) {
2177
+ for (const topic of byTopic.keys()) {
2178
+ sendOn(conn, { topic, type: "whisper_subscribe" });
2179
+ }
2180
+ }
2181
+ this.flushOfflineQueue(shardKey).catch(() => void 0);
2182
+ this.startHeartbeat(conn);
2183
+ });
2184
+ socket.addEventListener("message", (event) => {
2185
+ this.handleServerMessage(event.data, shardKey);
2186
+ });
2187
+ socket.addEventListener("close", (event) => {
2188
+ if (conn.socket !== socket) {
2189
+ return;
2190
+ }
2191
+ if (event?.code === 4001) {
2192
+ this.notifyTokenExpired();
2193
+ }
2194
+ this.handleDisconnect(conn);
2195
+ });
2196
+ socket.addEventListener("error", () => {
2197
+ if (conn.socket !== socket) {
2198
+ return;
2199
+ }
2200
+ if (conn.wsState === "connecting" || conn.wsState === "open") {
2201
+ this.handleDisconnect(conn);
2202
+ }
2203
+ });
2204
+ }
2205
+ handleDisconnect(conn) {
2206
+ if (this.closed) {
2207
+ return;
2208
+ }
2209
+ if (conn.wsState === "idle" || conn.wsState === "closed") {
2210
+ return;
2211
+ }
2212
+ this.stopHeartbeat(conn);
2213
+ if (conn.connectTimer !== void 0) {
2214
+ clearTimeout(conn.connectTimer);
2215
+ conn.connectTimer = void 0;
2216
+ }
2217
+ conn.socket = void 0;
2218
+ conn.wsState = "idle";
2219
+ this.emitConnectionStatus();
2220
+ this.markShardPendingAck(conn.shardKey);
2221
+ if (this.WebSocketImpl === void 0) {
2222
+ return;
2223
+ }
2224
+ const delay = conn.reconnect.next();
2225
+ conn.reconnectTimer = setTimeout(() => {
2226
+ conn.reconnectTimer = void 0;
2227
+ this.ensureSocket(conn.shardKey);
2228
+ }, delay);
2229
+ }
2230
+ /**
2231
+ * Begin the keepalive heartbeat on an open connection. Each tick sends a
2232
+ * {@link WS_KEEPALIVE_PING} text frame the server answers from its
2233
+ * hibernation auto-response without waking the DO. A no-op when the
2234
+ * heartbeat is disabled (an interval of zero or less); idempotent — any
2235
+ * existing timer is cleared first so a reconnect can't leak intervals.
2236
+ */
2237
+ startHeartbeat(conn) {
2238
+ this.stopHeartbeat(conn);
2239
+ if (this.heartbeatIntervalMs <= 0) {
2240
+ return;
2241
+ }
2242
+ conn.heartbeatTimer = setInterval(() => {
2243
+ if (conn.wsState !== "open" || !conn.socket) {
2244
+ return;
2245
+ }
2246
+ try {
2247
+ conn.socket.send(WS_KEEPALIVE_PING);
2248
+ } catch {
2249
+ }
2250
+ }, this.heartbeatIntervalMs);
2251
+ }
2252
+ /** Clear a connection's keepalive timer, if any. Safe to call repeatedly. */
2253
+ // eslint-disable-next-line class-methods-use-this -- cohesive connection helper; pairs with startHeartbeat
2254
+ stopHeartbeat(conn) {
2255
+ if (conn.heartbeatTimer !== void 0) {
2256
+ clearInterval(conn.heartbeatTimer);
2257
+ conn.heartbeatTimer = void 0;
2258
+ }
2259
+ }
2260
+ /** Mark every subscription bound to `shardKey` as needing a fresh ack. */
2261
+ markShardPendingAck(shardKey) {
2262
+ const key = connectionKey(shardKey);
2263
+ for (const state of this.subscriptions.all()) {
2264
+ if (connectionKey(state.shardKey) === key) {
2265
+ state.acked = false;
2266
+ }
2267
+ }
2268
+ }
2269
+ sendSubscribeIfOpen(state) {
2270
+ const conn = this.getConnection(state.shardKey);
2271
+ if (conn?.wsState !== "open" || state.acked) {
2272
+ return;
2273
+ }
2274
+ const table = state.fn.__lunoraTable ?? state.fn.__lunoraRef;
2275
+ sendOn(conn, {
2276
+ id: state.id,
2277
+ // `sinceSeq` rides along when we hold a persisted cursor for this
2278
+ // sub (a hydrated read or an earlier frame), so the server can
2279
+ // resume instead of re-snapshotting. Omitted on a cold sub.
2280
+ query: {
2281
+ args: state.args,
2282
+ functionPath: state.fn.__lunoraRef,
2283
+ table,
2284
+ ...state.serverCursor === void 0 ? {} : { sinceSeq: state.serverCursor },
2285
+ ...state.serverEpoch === void 0 ? {} : { sinceEpoch: state.serverEpoch }
2286
+ },
2287
+ type: "subscribe"
2288
+ });
2289
+ }
2290
+ sendShapeSubscribeIfOpen(state) {
2291
+ const conn = this.getConnection(state.shardKey);
2292
+ if (conn?.wsState !== "open") {
2293
+ return;
2294
+ }
2295
+ sendOn(conn, {
2296
+ id: state.id,
2297
+ shape: { name: state.name, ...state.args === void 0 ? {} : { args: state.args } },
2298
+ type: "shape_subscribe",
2299
+ // Resume from the last applied checkpoint when we hold one; a cold
2300
+ // subscribe omits it and the server seeds the full membership.
2301
+ ...state.serverCursor === void 0 ? {} : { sinceCheckpoint: state.serverCursor },
2302
+ ...state.serverEpoch === void 0 ? {} : { sinceEpoch: state.serverEpoch }
2303
+ });
2304
+ }
2305
+ handleServerMessage(raw, shardKey) {
2306
+ const text = decodeServerFrame(raw);
2307
+ if (text === void 0) {
2308
+ return;
2309
+ }
2310
+ let message;
2311
+ try {
2312
+ message = JSON.parse(text);
2313
+ } catch {
2314
+ return;
2315
+ }
2316
+ switch (message.type) {
2317
+ case "ack": {
2318
+ const state = this.subscriptions.getById(message.id);
2319
+ if (state) {
2320
+ state.acked = true;
2321
+ }
2322
+ return;
2323
+ }
2324
+ case "chunk": {
2325
+ const { data, id } = message;
2326
+ const stream = this.streams.get(id);
2327
+ stream?.handle.push(data);
2328
+ return;
2329
+ }
2330
+ case "complete": {
2331
+ this.handleCompleteMessage(message.id);
2332
+ return;
2333
+ }
2334
+ case "data":
2335
+ case "delta": {
2336
+ this.handleDataMessage(message);
2337
+ return;
2338
+ }
2339
+ case "error": {
2340
+ this.handleErrorMessage(message);
2341
+ break;
2342
+ }
2343
+ case "pokeEnd": {
2344
+ this.handlePokeEnd(message);
2345
+ break;
2346
+ }
2347
+ case "pokePart": {
2348
+ this.handlePokePart(message);
2349
+ break;
2350
+ }
2351
+ case "pokeStart": {
2352
+ this.handlePokeStart(message);
2353
+ break;
2354
+ }
2355
+ case "resume": {
2356
+ this.handleResumeMessage(message);
2357
+ break;
2358
+ }
2359
+ case "settled": {
2360
+ this.handleSettledMessage(message);
2361
+ break;
2362
+ }
2363
+ case "whisper": {
2364
+ this.dispatchWhisper(message, shardKey);
2365
+ break;
2366
+ }
2367
+ }
2368
+ }
2369
+ handleErrorMessage(message) {
2370
+ const errorCode = message.error?.code;
2371
+ if (errorCode === "TOKEN_EXPIRED") {
2372
+ this.notifyTokenExpired();
2373
+ return;
2374
+ }
2375
+ const { id } = message;
2376
+ const stream = id === void 0 ? void 0 : this.streams.get(id);
2377
+ if (stream && id !== void 0) {
2378
+ stream.handle.fail(buildStreamError(message));
2379
+ this.streams.delete(id);
2380
+ return;
2381
+ }
2382
+ const state = id === void 0 ? void 0 : this.subscriptions.getById(id);
2383
+ if (state) {
2384
+ fanSubscriptionError(state.errorCallbacks, buildSubscriptionError(message));
2385
+ return;
2386
+ }
2387
+ const shapeState = id === void 0 ? void 0 : this.shapeSubscriptions.get(id);
2388
+ if (shapeState) {
2389
+ fanSubscriptionError(shapeState.errorCallbacks, buildSubscriptionError(message));
2390
+ }
2391
+ }
2392
+ handlePokeStart(message) {
2393
+ if (this.pokeBuffers.size >= LunoraClient.MAX_POKE_BUFFERS) {
2394
+ const oldest = this.pokeBuffers.keys().next().value;
2395
+ if (oldest !== void 0) {
2396
+ this.pokeBuffers.delete(oldest);
2397
+ }
2398
+ }
2399
+ this.pokeBuffers.set(message.pokeId, { baseCheckpoint: message.baseCheckpoint, epoch: message.epoch, lastMutationId: /* @__PURE__ */ new Map(), parts: /* @__PURE__ */ new Map() });
2400
+ }
2401
+ handlePokePart(message) {
2402
+ const buffer = this.pokeBuffers.get(message.pokeId);
2403
+ if (!buffer) {
2404
+ return;
2405
+ }
2406
+ const existing = buffer.parts.get(message.shapeId) ?? [];
2407
+ existing.push(...message.rowsPatch);
2408
+ buffer.parts.set(message.shapeId, existing);
2409
+ if (message.lastMutationId !== void 0) {
2410
+ buffer.lastMutationId.set(message.shapeId, message.lastMutationId);
2411
+ }
2412
+ }
2413
+ handlePokeEnd(message) {
2414
+ const buffer = this.pokeBuffers.get(message.pokeId);
2415
+ if (!buffer) {
2416
+ return;
2417
+ }
2418
+ this.pokeBuffers.delete(message.pokeId);
2419
+ for (const [shapeId, ops] of buffer.parts) {
2420
+ const state = this.shapeSubscriptions.get(shapeId);
2421
+ if (!state) {
2422
+ continue;
2423
+ }
2424
+ const epochForked = buffer.epoch !== void 0 && state.serverEpoch !== void 0 && buffer.epoch !== state.serverEpoch;
2425
+ const baseDiverged = buffer.baseCheckpoint !== void 0 && state.serverCursor !== void 0 && state.serverCursor !== buffer.baseCheckpoint;
2426
+ if (epochForked || baseDiverged) {
2427
+ state.rows.clear();
2428
+ state.serverCursor = void 0;
2429
+ state.serverEpoch = void 0;
2430
+ this.emitShapeRows(state);
2431
+ this.sendShapeSubscribeIfOpen(state);
2432
+ continue;
2433
+ }
2434
+ applyRowOpsToView(state.rows, ops);
2435
+ if (message.checkpoint !== void 0) {
2436
+ state.serverCursor = message.checkpoint;
2437
+ }
2438
+ if (message.epoch !== void 0) {
2439
+ state.serverEpoch = message.epoch;
2440
+ }
2441
+ const watermark = buffer.lastMutationId.get(shapeId);
2442
+ if (watermark !== void 0) {
2443
+ state.lastMutationId = watermark;
2444
+ }
2445
+ this.emitShapeRows(state);
2446
+ state.onCheckpoint?.({ checkpoint: state.serverCursor, mutationId: state.lastMutationId });
2447
+ }
2448
+ }
2449
+ /** Materialize a shape's keyed view to an array and invoke its callbacks. */
2450
+ // eslint-disable-next-line class-methods-use-this -- a pure state→callback fan-out kept beside the shape-subscription pipeline it serves.
2451
+ emitShapeRows(state) {
2452
+ const rows = [...state.rows.values()];
2453
+ for (const shapeCallback of state.callbacks) {
2454
+ try {
2455
+ shapeCallback(rows);
2456
+ } catch {
2457
+ }
2458
+ }
2459
+ }
2460
+ handleDataMessage(message) {
2461
+ const { id } = message;
2462
+ const state = id ? this.subscriptions.getById(id) : void 0;
2463
+ if (!state) {
2464
+ return;
2465
+ }
2466
+ const payload = this.resolveDataPayload(message, state);
2467
+ state.serverBase = payload;
2468
+ if (message.cursor !== void 0) {
2469
+ state.serverCursor = message.cursor;
2470
+ }
2471
+ if (message.epoch !== void 0) {
2472
+ state.serverEpoch = message.epoch;
2473
+ }
2474
+ this.persistQueryValue(state);
2475
+ dropConfirmedLayers(state, state.serverCursor);
2476
+ notifySubscription(state, state.optimisticLayers.length === 0 ? payload : foldOptimistic(payload, state.optimisticLayers));
2477
+ }
2478
+ /**
2479
+ * Handle a `resume` frame (Pillar 1b): the server proved nothing the
2480
+ * subscription reads changed since our `sinceSeq`, so the cached value is
2481
+ * still current. We keep `lastValue` as-is, mark the sub acked, and advance
2482
+ * the cursor (re-persisting so the next reconnect resumes from the newer
2483
+ * watermark). No callback fires — the value didn't change, and `subscribe()`
2484
+ * already replayed the cached value to every consumer synchronously.
2485
+ */
2486
+ handleResumeMessage(message) {
2487
+ const state = this.subscriptions.getById(message.id);
2488
+ if (!state) {
2489
+ return;
2490
+ }
2491
+ this.ackAndAdvanceCursor(state, message.cursor, message.epoch);
2492
+ }
2493
+ /**
2494
+ * Handle a `settled` frame: a write touched one of this subscription's read
2495
+ * tables but produced a byte-identical result, so the server suppressed the
2496
+ * data frame. Like {@link handleResumeMessage} the value didn't change — we
2497
+ * advance the resume position and re-persist — but we ALSO surface the echoed
2498
+ * custom-mutator watermark via `onCheckpoint` so a `@lunora/db` list
2499
+ * collection drops the optimistic overlay for the confirmed write (otherwise
2500
+ * its checkpoint gate, fed only by data frames, would hang forever). Sent
2501
+ * only to custom-mutator clients; plain `useQuery` subscribers leave
2502
+ * `onCheckpoint` unset and this is a near no-op.
2503
+ */
2504
+ handleSettledMessage(message) {
2505
+ const state = this.subscriptions.getById(message.id);
2506
+ if (!state) {
2507
+ return;
2508
+ }
2509
+ this.ackAndAdvanceCursor(state, message.cursor, message.epoch);
2510
+ if (message.lastMutationId !== void 0) {
2511
+ state.lastMutationId = message.lastMutationId;
2512
+ }
2513
+ for (const onCheckpoint of state.checkpointCallbacks) {
2514
+ onCheckpoint({ checkpoint: state.serverCursor, mutationId: state.lastMutationId });
2515
+ }
2516
+ }
2517
+ /**
2518
+ * Mark `state` acked and, when the frame carries a newer cursor/epoch than
2519
+ * the cached position, advance the resume watermark and re-persist. Shared by
2520
+ * the `resume` and `settled` frame handlers — both acknowledge "nothing the
2521
+ * client must re-render changed, but the resume position may have moved".
2522
+ */
2523
+ ackAndAdvanceCursor(state, cursor, epoch) {
2524
+ state.acked = true;
2525
+ if (cursor !== void 0 && cursor !== state.serverCursor || epoch !== void 0 && epoch !== state.serverEpoch) {
2526
+ if (cursor !== void 0) {
2527
+ state.serverCursor = cursor;
2528
+ }
2529
+ if (epoch !== void 0) {
2530
+ state.serverEpoch = epoch;
2531
+ }
2532
+ this.persistQueryValue(state);
2533
+ if (dropConfirmedLayers(state, state.serverCursor)) {
2534
+ notifySubscription(state, foldOptimistic(state.serverBase, state.optimisticLayers));
2535
+ }
2536
+ }
2537
+ }
2538
+ /**
2539
+ * Resolve the value to publish for a `data`/`delta` frame.
2540
+ *
2541
+ * A `data` frame is an authoritative snapshot (the server re-execution path)
2542
+ * and always replaces the cached value wholesale. A `delta` frame carrying a
2543
+ * structured `MutationDelta` (the `broadcastDelta` row-change path) is
2544
+ * merged incrementally into the cached list — preserving order, no dup/loss —
2545
+ * so each subscription (including every paginated page) updates by delta
2546
+ * rather than a full re-send. We fall back to full replacement when the
2547
+ * delta isn't a recognisable row change, when there's no cached value yet,
2548
+ * or when it can't be applied cleanly against the current cached shape.
2549
+ */
2550
+ // eslint-disable-next-line class-methods-use-this -- instance method for symmetry with the other message handlers; reads no shared client state
2551
+ resolveDataPayload(message, state) {
2552
+ if ("data" in message && message.data !== void 0) {
2553
+ return message.data;
2554
+ }
2555
+ const { delta } = message;
2556
+ if (isMutationDelta(delta) && state.serverBase !== void 0) {
2557
+ const merged = applyDelta(state.serverBase, delta);
2558
+ if (merged !== void 0) {
2559
+ return merged;
2560
+ }
2561
+ }
2562
+ return delta;
2563
+ }
2564
+ /** Route an inbound whisper to the topic's handlers on the originating shard. */
2565
+ dispatchWhisper(message, shardKey) {
2566
+ const handlers = this.whisperHandlers.get(connectionKey(shardKey))?.get(message.topic);
2567
+ if (!handlers) {
2568
+ return;
2569
+ }
2570
+ for (const handler of handlers) {
2571
+ try {
2572
+ handler(message.data, message.from);
2573
+ } catch {
2574
+ }
2575
+ }
2576
+ }
2577
+ /** Notify every {@link onTokenExpired} listener (best-effort, listener throws swallowed). */
2578
+ notifyTokenExpired() {
2579
+ this.tokenExpiredListeners.emit();
2580
+ }
2581
+ handleCompleteMessage(id) {
2582
+ const stream = this.streams.get(id);
2583
+ if (stream) {
2584
+ stream.handle.complete();
2585
+ this.streams.delete(id);
2586
+ return;
2587
+ }
2588
+ const state = this.subscriptions.getById(id);
2589
+ if (state) {
2590
+ this.subscriptions.remove(state);
2591
+ }
2592
+ }
2593
+ unpersist(id) {
2594
+ if (id) {
2595
+ this.persistence?.remove(id).catch((error) => {
2596
+ reportPersistenceError(this.onPersistenceError, "remove", error, id);
2597
+ });
2598
+ }
2599
+ }
2600
+ /**
2601
+ * Stable, non-reversible fingerprint of the current auth identity used to
2602
+ * stamp queued offline writes. `null` (signed out) is its own identity and
2603
+ * never matches a bearer-token fingerprint. The raw token is never stored;
2604
+ * a length-prefixed FNV-1a hash is enough to detect an identity *change*
2605
+ * without keeping the credential around in the queue map.
2606
+ */
2607
+ // `null` is the distinct "signed out" identity (separate from `undefined`,
2608
+ // which means "not stamped / hydrated"); the two must not be conflated.
2609
+ identityFingerprint() {
2610
+ if (this.authSubject !== void 0) {
2611
+ return this.authSubject === null ? null : `subj:${this.authSubject}`;
2612
+ }
2613
+ const token = this.authToken;
2614
+ if (token === null) {
2615
+ return null;
2616
+ }
2617
+ let hash = 2166136261;
2618
+ for (let index = 0; index < token.length; index += 1) {
2619
+ hash ^= token.charCodeAt(index);
2620
+ hash = Math.imul(hash, 16777619);
2621
+ }
2622
+ return `${token.length.toString(36)}:${(hash >>> 0).toString(36)}`;
2623
+ }
2624
+ /**
2625
+ * Drain every in-memory offline write and reject it because the auth
2626
+ * identity changed. Durable entries are also dropped from persistence so a
2627
+ * later `hydrate` can't resurrect another user's writes. Stamps are cleared
2628
+ * alongside. Persisted entries restored without a live awaiter still get
2629
+ * unpersisted here.
2630
+ */
2631
+ rejectQueuedForIdentityChange() {
2632
+ const drained = this.offlineQueue.drain();
2633
+ for (const item of drained) {
2634
+ this.queuedIdentities.delete(item.id ?? "");
2635
+ this.unpersist(item.id);
2636
+ const error = new Error("offline mutation discarded: auth identity changed before replay");
2637
+ error.code = "OFFLINE_IDENTITY_CHANGED";
2638
+ item.reject(error);
2639
+ this.emitItemSettled(item, "rejected", error);
2640
+ }
2641
+ this.clearQueryCacheForIdentityChange();
2642
+ }
2643
+ /**
2644
+ * Migrate every live identity stamp from `from` to `to` — used when the auth
2645
+ * identity label changes but the underlying credential (token) does NOT, e.g.
2646
+ * the user id resolves a tick after the token was set. The in-memory
2647
+ * `queuedIdentities` map is the flush-time source of truth, so re-stamping it
2648
+ * keeps the in-flight writes replayable under the new (more stable) identity
2649
+ * instead of the flush guard discarding them as a mismatch.
2650
+ */
2651
+ restampQueuedIdentity(from, to) {
2652
+ for (const [id, stamp] of this.queuedIdentities) {
2653
+ if (stamp === from) {
2654
+ this.queuedIdentities.set(id, to);
2655
+ }
2656
+ }
2657
+ }
2658
+ /**
2659
+ * Drop the durable read cache on an identity change so a cached value stamped
2660
+ * under the previous identity can never hydrate into a new session. Clears
2661
+ * the in-flight write batch and the not-yet-consumed hydrated entries too;
2662
+ * the durable `clear()` is best-effort.
2663
+ */
2664
+ clearQueryCacheForIdentityChange() {
2665
+ if (this.cacheFlushTimer !== void 0) {
2666
+ clearTimeout(this.cacheFlushTimer);
2667
+ this.cacheFlushTimer = void 0;
2668
+ }
2669
+ this.pendingCacheWrites.clear();
2670
+ this.hydratedQueryCache.clear();
2671
+ this.queryCache?.clear().catch(() => void 0);
2672
+ }
2673
+ async flushOfflineQueue(shardKey) {
2674
+ const key = connectionKey(shardKey);
2675
+ const drained = this.offlineQueue.drain((item) => connectionKey(item.shardKey) === key);
2676
+ for (let index = 0; index < drained.length; index += 1) {
2677
+ const item = drained[index];
2678
+ if (!item) {
2679
+ continue;
2680
+ }
2681
+ const currentIdentity = this.identityFingerprint();
2682
+ const liveStamp = item.id === void 0 ? void 0 : this.queuedIdentities.get(item.id);
2683
+ const stamped = liveStamp === void 0 ? item.identity : liveStamp;
2684
+ if (stamped !== void 0 && stamped !== currentIdentity) {
2685
+ this.queuedIdentities.delete(item.id ?? "");
2686
+ this.unpersist(item.id);
2687
+ const error = new Error("offline mutation skipped: auth identity changed before replay");
2688
+ error.code = "OFFLINE_IDENTITY_CHANGED";
2689
+ item.reject(error);
2690
+ this.emitItemSettled(item, "rejected", error);
2691
+ continue;
2692
+ }
2693
+ this.queuedIdentities.delete(item.id ?? "");
2694
+ try {
2695
+ let commitCursor;
2696
+ const value = await this.rpc(item.functionPath, item.args, item.shardKey, {
2697
+ captureBookmark: true,
2698
+ mutationId: item.id,
2699
+ onCommitCursor: (cursor) => {
2700
+ commitCursor = cursor;
2701
+ }
2702
+ });
2703
+ this.unpersist(item.id);
2704
+ item.onCommit?.(commitCursor);
2705
+ item.resolve(value);
2706
+ this.emitItemSettled(item, "committed");
2707
+ } catch (error) {
2708
+ if (error.code !== void 0) {
2709
+ this.unpersist(item.id);
2710
+ item.reject(error);
2711
+ this.emitItemSettled(item, "rejected", error);
2712
+ continue;
2713
+ }
2714
+ this.offlineQueue.requeue(drained.slice(index));
2715
+ return;
2716
+ }
2717
+ }
2718
+ }
2719
+ }
2720
+
2721
+ export { LunoraClient };