@lunora/client 1.0.0-alpha.23 → 1.0.0-alpha.231

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 (97) hide show
  1. package/README.md +16 -3
  2. package/dist/auth/index.d.mts +43 -12
  3. package/dist/auth/index.d.ts +43 -12
  4. package/dist/auth/index.mjs +1 -60
  5. package/dist/index.d.mts +869 -438
  6. package/dist/index.d.ts +869 -438
  7. package/dist/index.mjs +1 -21
  8. package/dist/packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs +1 -0
  9. package/dist/packem_shared/DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs +1 -0
  10. package/dist/packem_shared/LunoraClient-D6MyuSWy.mjs +1 -0
  11. package/dist/packem_shared/OfflineQueue-BWamzR6p.mjs +1 -0
  12. package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs +1 -0
  13. package/dist/packem_shared/SKIP-d7LeP-sY.mjs +1 -0
  14. package/dist/packem_shared/SubscriptionRegistry-DKIXE7M7.mjs +1 -0
  15. package/dist/packem_shared/TabCoordinator-CXD7vulJ.mjs +1 -0
  16. package/dist/packem_shared/applyDelta-CWpwS3Bb.mjs +1 -0
  17. package/dist/packem_shared/client-urls-BHLUjjcG.mjs +1 -0
  18. package/dist/packem_shared/connectLiveStream-DCgklEjI.mjs +1 -0
  19. package/dist/packem_shared/createAsyncStoragePersistence-6FCvqc6C.mjs +1 -0
  20. package/dist/packem_shared/createAsyncStorageQueryCache-f5023fdB.mjs +1 -0
  21. package/dist/packem_shared/createCallRunner-Bwcrfh76.mjs +1 -0
  22. package/dist/packem_shared/createClientQuery-B8Nfj-7o.mjs +1 -0
  23. package/dist/packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs +1 -0
  24. package/dist/packem_shared/createInMemoryPersistence-Cz2W6XVj.mjs +1 -0
  25. package/dist/packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs +1 -0
  26. package/dist/packem_shared/createLocalStore-BT0QPKdf.mjs +1 -0
  27. package/dist/packem_shared/createMutatorRunner-CuMRJpUx.mjs +1 -0
  28. package/dist/packem_shared/createReconnect-CjTmjJDH.mjs +1 -0
  29. package/dist/packem_shared/createServerClient-BqCdfoE1.mjs +1 -0
  30. package/dist/packem_shared/createSnapshotPrecondition-CLkxVeN1.mjs +1 -0
  31. package/dist/packem_shared/delta-merge-Ls3DED4g.mjs +1 -0
  32. package/dist/packem_shared/deserializePreloaded-CyFK_cv6.mjs +1 -0
  33. package/dist/packem_shared/function-reference.d-Br_hsKje.d.mts +45 -0
  34. package/dist/packem_shared/function-reference.d-Br_hsKje.d.ts +45 -0
  35. package/dist/packem_shared/getServerSession-BaOoo1p6.mjs +1 -0
  36. package/dist/packem_shared/httpStream-DaqP70Ne.mjs +9 -0
  37. package/dist/packem_shared/idb-utility-C8WS390w.mjs +1 -0
  38. package/dist/packem_shared/live-stream-ct8j7T75.mjs +10 -0
  39. package/dist/packem_shared/liveTopicSubscription-Bs-ULKfs.mjs +1 -0
  40. package/dist/packem_shared/local-store-fqWV2n_Z.mjs +1 -0
  41. package/dist/packem_shared/lunora-client.d-DpmxnYmL.d.ts +4916 -0
  42. package/dist/packem_shared/lunora-client.d-dOEEoF4x.d.mts +4916 -0
  43. package/dist/packem_shared/offline-queue-D_fr-uQ3.mjs +1 -0
  44. package/dist/packem_shared/preload.d-BkXsKMmU.d.ts +21 -0
  45. package/dist/packem_shared/preload.d-XVLTUaah.d.mts +21 -0
  46. package/dist/packem_shared/preloadQuery-uFy24PCR.mjs +1 -0
  47. package/dist/packem_shared/single-blob-store-DpqSxsgi.mjs +1 -0
  48. package/dist/packem_shared/wire-errors-Bw04a4ZQ.mjs +1 -0
  49. package/dist/pagination/index.d.mts +42 -42
  50. package/dist/pagination/index.d.ts +42 -42
  51. package/dist/pagination/index.mjs +1 -61
  52. package/dist/query/index.d.mts +111 -43
  53. package/dist/query/index.d.ts +111 -43
  54. package/dist/query/index.mjs +1 -1
  55. package/dist/service.d.mts +49 -0
  56. package/dist/service.d.ts +49 -0
  57. package/dist/service.mjs +1 -0
  58. package/dist/ssr/index.d.mts +109 -79
  59. package/dist/ssr/index.d.ts +109 -79
  60. package/dist/ssr/index.mjs +1 -4
  61. package/dist/upload.d.mts +35 -0
  62. package/dist/upload.d.ts +35 -0
  63. package/dist/upload.mjs +1 -0
  64. package/package.json +15 -2
  65. package/dist/packem_shared/CONFLICT_ERROR_CODE-B8gQ8tyU.mjs +0 -33
  66. package/dist/packem_shared/ClientServiceWorker-C3PAFwy0.mjs +0 -100
  67. package/dist/packem_shared/DEFAULT_MAX_BUFFER-7hFnzNk9.mjs +0 -110
  68. package/dist/packem_shared/LunoraClient-BBCQjjbl.mjs +0 -3599
  69. package/dist/packem_shared/OfflineQueue-B4HUF7rt.mjs +0 -1
  70. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  71. package/dist/packem_shared/SubscriptionRegistry-CxS_Inha.mjs +0 -31
  72. package/dist/packem_shared/TabCoordinator-BwRR8H06.mjs +0 -222
  73. package/dist/packem_shared/applyDelta-CRKZ1PBt.mjs +0 -81
  74. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  75. package/dist/packem_shared/createClientQuery-CQ51bWAE.mjs +0 -71
  76. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  77. package/dist/packem_shared/createInMemoryPersistence-DZ2VHWgm.mjs +0 -79
  78. package/dist/packem_shared/createInMemoryQueryCache-DiaGZkA2.mjs +0 -112
  79. package/dist/packem_shared/createLocalStore-BtqUmOQA.mjs +0 -2
  80. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  81. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +0 -31
  82. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  83. package/dist/packem_shared/createReply-lI4tVS2w.mjs +0 -36
  84. package/dist/packem_shared/createServerClient-CTTAmvMx.mjs +0 -11
  85. package/dist/packem_shared/createSnapshotPrecondition-CxQ1T4ZP.mjs +0 -18
  86. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  87. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  88. package/dist/packem_shared/httpStream-BJU-aflc.mjs +0 -159
  89. package/dist/packem_shared/idb-utility-DrSVX43Q.mjs +0 -48
  90. package/dist/packem_shared/local-store-DIq-UWfD.mjs +0 -106
  91. package/dist/packem_shared/lunora-client.d-JvtVpf8A.d.mts +0 -2824
  92. package/dist/packem_shared/lunora-client.d-JvtVpf8A.d.ts +0 -2824
  93. package/dist/packem_shared/offline-queue-CF4_Co5k.mjs +0 -199
  94. package/dist/packem_shared/preload.d-C4_d_l5v.d.ts +0 -20
  95. package/dist/packem_shared/preload.d-DKbjGN5O.d.mts +0 -20
  96. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  97. package/dist/packem_shared/wire-key-Djie6aaR.mjs +0 -266
@@ -1,3599 +0,0 @@
1
- import { LunoraError } from '@lunora/errors';
2
- import { s as stableWireKey, d as decodeWire, e as encodeWire } from './wire-key-Djie6aaR.mjs';
3
- import createInMemoryBookmarkStorage from './createInMemoryBookmarkStorage-BoN7a7TH.mjs';
4
- import { ClientQueryStore } from './createClientQuery-CQ51bWAE.mjs';
5
- import { TabCoordinator } from './TabCoordinator-BwRR8H06.mjs';
6
- import { isMutationDelta, applyDelta } from './applyDelta-CRKZ1PBt.mjs';
7
- import { httpStream } from './httpStream-BJU-aflc.mjs';
8
- import { f as foldOptimistic, a as applyOptimisticLayer, d as dropConfirmedLayers, n as notifySubscription, c as createLocalStore } from './local-store-DIq-UWfD.mjs';
9
- import { O as OfflineQueue, n as nextId, i as isStaleVersion, r as reportPersistenceError } from './offline-queue-CF4_Co5k.mjs';
10
- import { resolvePersistenceAdapter } from './createInMemoryPersistence-DZ2VHWgm.mjs';
11
- import { resolveQueryCacheAdapter, queryCacheKey } from './createInMemoryQueryCache-DiaGZkA2.mjs';
12
- import { createReconnect } from './createReconnect-Di_-oHH7.mjs';
13
- import { createStream } from './DEFAULT_MAX_BUFFER-7hFnzNk9.mjs';
14
- import { SubscriptionRegistry } from './SubscriptionRegistry-CxS_Inha.mjs';
15
-
16
- const MAX_BATCH_ENTRIES = 500;
17
-
18
- const evictOldestEntry = (map, capacity) => {
19
- if (map.size < capacity) {
20
- return;
21
- }
22
- const oldest = map.keys().next().value;
23
- if (oldest !== void 0) {
24
- map.delete(oldest);
25
- }
26
- };
27
-
28
- class Listeners {
29
- listeners = /* @__PURE__ */ new Set();
30
- add(listener) {
31
- this.listeners.add(listener);
32
- return () => {
33
- this.listeners.delete(listener);
34
- };
35
- }
36
- // The conditional rest tuple makes `emit()` argument-free for a
37
- // `Listeners<void>` and one-argument for every other payload.
38
- // 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
39
- emit(...args) {
40
- const [value] = args;
41
- for (const listener of this.listeners) {
42
- try {
43
- listener(value);
44
- } catch {
45
- }
46
- }
47
- }
48
- clear() {
49
- this.listeners.clear();
50
- }
51
- }
52
-
53
- const RPC_PATH = "/_lunora/rpc";
54
- const RPC_BATCH_PATH = "/_lunora/rpc-batch";
55
- const WS_PATH = "/_lunora/ws";
56
- const bucketQuery = (bucket) => bucket === void 0 || bucket === "" ? "" : `&bucket=${encodeURIComponent(bucket)}`;
57
- const rollbackOptimistic = (optimisticRollbacks) => {
58
- for (let index = optimisticRollbacks.length - 1; index >= 0; index -= 1) {
59
- optimisticRollbacks[index]?.();
60
- }
61
- };
62
- const applyRowOpsToView = (rows, ops) => {
63
- for (const op of ops) {
64
- if (op.op === "delete") {
65
- rows.delete(op.key);
66
- } else if (op.value !== void 0) {
67
- rows.set(op.key, op.value);
68
- }
69
- }
70
- };
71
- const WS_KEEPALIVE_PING = "lunora-ping";
72
- const DEFAULT_HEARTBEAT_INTERVAL_MS = 3e4;
73
- const DEFAULT_CONNECT_TIMEOUT_MS = 1e4;
74
- const QUERY_CACHE_DEBOUNCE_MS = 250;
75
- const MAX_PENDING_STREAMS = 64;
76
- const SHARD_TRAFFIC_PATH = "/_lunora/admin/shard-traffic";
77
- const SCHEDULED_PATH = "/_lunora/admin/scheduled";
78
- const SCHEDULED_STATUS_PATH = "/_lunora/admin/scheduled/status";
79
- const SCHEDULED_WS_PATH = "/_lunora/admin/scheduled/ws";
80
- const SCHEDULED_CANCEL_PATH = "/_lunora/admin/scheduled/cancel";
81
- const SCHEDULED_DEAD_PATH = "/_lunora/admin/scheduled/dead";
82
- const SCHEDULED_DEAD_RETRY_PATH = "/_lunora/admin/scheduled/dead/retry";
83
- const SCHEDULED_DEAD_CANCEL_PATH = "/_lunora/admin/scheduled/dead/cancel";
84
- const WORKFLOWS_INSTANCES_PATH = "/_lunora/admin/workflows/instances";
85
- const WORKFLOWS_INSTANCE_PATH = "/_lunora/admin/workflows/instance";
86
- const WORKFLOWS_STATUS_PATH = "/_lunora/admin/workflows/status";
87
- const STORAGE_PATH = "/_lunora/admin/storage";
88
- const STORAGE_URL_PATH = "/_lunora/admin/storage/url";
89
- const STORAGE_BUCKETS_PATH = "/_lunora/admin/storage/buckets";
90
- const FUNCTIONS_PATH = "/_lunora/admin/functions";
91
- const CRON_JOBS_PATH = "/_lunora/admin/cron-jobs";
92
- const CRON_JOBS_RUN_PATH = "/_lunora/admin/cron-jobs/run";
93
- const OPENAPI_PATH = "/_lunora/admin/openapi";
94
- const OPENRPC_PATH = "/_lunora/admin/openrpc";
95
- const GLOBAL_TABLES_PATH = "/_lunora/admin/global/tables";
96
- const GLOBAL_TABLE_PATH = "/_lunora/admin/global/table";
97
- const GLOBAL_FACET_PATH = "/_lunora/admin/global/facet";
98
- const VECTOR_INDEXES_PATH = "/_lunora/admin/vector/indexes";
99
- const VECTOR_QUERY_PATH = "/_lunora/admin/vector/query";
100
- const KV_NAMESPACES_PATH = "/_lunora/admin/kv/namespaces";
101
- const KV_KEYS_PATH = "/_lunora/admin/kv/keys";
102
- const KV_VALUE_PATH = "/_lunora/admin/kv/value";
103
- const AUTH_USERS_PATH = "/_lunora/admin/auth/users";
104
- const AUTH_SESSIONS_PATH = "/_lunora/admin/auth/sessions";
105
- const AUTH_CREATE_USER_PATH = "/_lunora/admin/auth/users/create";
106
- const AUTH_SET_ROLE_PATH = "/_lunora/admin/auth/users/role";
107
- const AUTH_BAN_PATH = "/_lunora/admin/auth/users/ban";
108
- const AUTH_UNBAN_PATH = "/_lunora/admin/auth/users/unban";
109
- const AUTH_SET_PASSWORD_PATH = "/_lunora/admin/auth/users/password";
110
- const AUTH_REMOVE_USER_PATH = "/_lunora/admin/auth/users/remove";
111
- const AUTH_IMPERSONATE_PATH = "/_lunora/admin/auth/users/impersonate";
112
- const AUTH_REVOKE_SESSION_PATH = "/_lunora/admin/auth/sessions/revoke";
113
- const AUTH_REVOKE_SESSIONS_PATH = "/_lunora/admin/auth/sessions/revoke-all";
114
- const AUTH_CAPABILITIES_PATH = "/_lunora/admin/auth/capabilities";
115
- const AUTH_UPDATE_USER_PATH = "/_lunora/admin/auth/users/update";
116
- const AUTH_ACCOUNTS_PATH = "/_lunora/admin/auth/accounts";
117
- const AUTH_UNLINK_ACCOUNT_PATH = "/_lunora/admin/auth/accounts/unlink";
118
- const AUTH_PASSKEYS_PATH = "/_lunora/admin/auth/passkeys";
119
- const AUTH_DELETE_PASSKEY_PATH = "/_lunora/admin/auth/passkeys/delete";
120
- const AUTH_DISABLE_2FA_PATH = "/_lunora/admin/auth/two-factor/disable";
121
- const AUTH_ORGS_PATH = "/_lunora/admin/auth/organizations";
122
- const AUTH_ORG_MEMBERS_PATH = "/_lunora/admin/auth/organizations/members";
123
- const AUTH_ORG_INVITATIONS_PATH = "/_lunora/admin/auth/organizations/invitations";
124
- const AUTH_REMOVE_MEMBER_PATH = "/_lunora/admin/auth/organizations/members/remove";
125
- const AUTH_CANCEL_INVITATION_PATH = "/_lunora/admin/auth/organizations/invitations/cancel";
126
- const AUTH_CONFIG_PATH = "/_lunora/admin/auth/config";
127
- const AUTH_CREATE_ORG_PATH = "/_lunora/admin/auth/organizations/create";
128
- const AUTH_UPDATE_ORG_PATH = "/_lunora/admin/auth/organizations/update";
129
- const AUTH_REMOVE_ORG_PATH = "/_lunora/admin/auth/organizations/remove";
130
- const AUTH_ADD_MEMBER_PATH = "/_lunora/admin/auth/organizations/members/add";
131
- const AUTH_INVITE_MEMBER_PATH = "/_lunora/admin/auth/organizations/members/invite";
132
- const AUTH_MEMBER_ROLE_PATH = "/_lunora/admin/auth/organizations/members/role";
133
- const AUTH_ORG_TEAMS_PATH = "/_lunora/admin/auth/organizations/teams";
134
- const AUTH_CREATE_TEAM_PATH = "/_lunora/admin/auth/organizations/teams/create";
135
- const AUTH_UPDATE_TEAM_PATH = "/_lunora/admin/auth/organizations/teams/update";
136
- const AUTH_REMOVE_TEAM_PATH = "/_lunora/admin/auth/organizations/teams/remove";
137
- const AUTH_ORG_TEAM_MEMBERS_PATH = "/_lunora/admin/auth/organizations/teams/members";
138
- const AUTH_ADD_TEAM_MEMBER_PATH = "/_lunora/admin/auth/organizations/teams/members/add";
139
- const AUTH_REMOVE_TEAM_MEMBER_PATH = "/_lunora/admin/auth/organizations/teams/members/remove";
140
- const AUTH_ORG_ROLES_PATH = "/_lunora/admin/auth/organizations/roles";
141
- const AUTH_CREATE_ROLE_PATH = "/_lunora/admin/auth/organizations/roles/create";
142
- const AUTH_UPDATE_ROLE_PATH = "/_lunora/admin/auth/organizations/roles/update";
143
- const AUTH_REMOVE_ROLE_PATH = "/_lunora/admin/auth/organizations/roles/remove";
144
- const DEFAULT_AUTH_BASE_PATH = "/api/auth";
145
- const GET_SESSION_PATH = "/get-session";
146
- const deriveWsUrl = (url) => {
147
- if (url.startsWith("https://")) {
148
- return `wss://${url.slice("https://".length)}`;
149
- }
150
- if (url.startsWith("http://")) {
151
- return `ws://${url.slice("http://".length)}`;
152
- }
153
- return url;
154
- };
155
- const joinUrl = (base, path) => {
156
- const trimmed = base.endsWith("/") ? base.slice(0, -1) : base;
157
- return `${trimmed}${path}`;
158
- };
159
- const withQuery = (path, params) => {
160
- const search = new URLSearchParams();
161
- for (const [key, value] of Object.entries(params)) {
162
- if (value !== void 0 && value !== "") {
163
- search.set(key, String(value));
164
- }
165
- }
166
- const query = search.toString();
167
- return query === "" ? path : `${path}?${query}`;
168
- };
169
- const connectionKey = (shardKey) => shardKey ?? "";
170
- const buildStreamError = (message) => {
171
- const errorEnvelope = message.error;
172
- const code = typeof errorEnvelope?.code === "string" ? errorEnvelope.code : void 0;
173
- const nestedMessage = typeof errorEnvelope?.message === "string" ? errorEnvelope.message : void 0;
174
- const messageText = (typeof message.message === "string" ? message.message : void 0) ?? nestedMessage ?? "stream error";
175
- return code === void 0 ? new Error(messageText) : new LunoraError(code, messageText);
176
- };
177
- const buildSubscriptionError = (message) => {
178
- const errorEnvelope = message.error;
179
- const code = typeof errorEnvelope?.code === "string" ? errorEnvelope.code : void 0;
180
- const nestedMessage = typeof errorEnvelope?.message === "string" ? errorEnvelope.message : void 0;
181
- const messageText = (typeof message.message === "string" ? message.message : void 0) ?? nestedMessage ?? "subscription error";
182
- return { message: messageText, ...code === void 0 ? {} : { code } };
183
- };
184
- const fanSubscriptionError = (callbacks, error) => {
185
- for (const errorCallback of callbacks) {
186
- try {
187
- errorCallback(error);
188
- } catch {
189
- }
190
- }
191
- };
192
- const sharedDecoder = new TextDecoder();
193
- const decodeServerFrame = (raw) => {
194
- if (typeof raw === "string") {
195
- return raw;
196
- }
197
- if (raw instanceof ArrayBuffer) {
198
- return sharedDecoder.decode(raw);
199
- }
200
- return void 0;
201
- };
202
- const sendOn = (conn, message) => {
203
- if (!conn.socket || conn.wsState !== "open") {
204
- return false;
205
- }
206
- try {
207
- conn.socket.send(JSON.stringify(message));
208
- return true;
209
- } catch {
210
- return false;
211
- }
212
- };
213
- const reconstructError = (errorBody) => {
214
- const error = new Error(errorBody.message ?? "request failed");
215
- error.code = errorBody.code;
216
- if (errorBody.data !== void 0) {
217
- error.data = decodeWire(errorBody.data);
218
- }
219
- if (errorBody.hint !== void 0) {
220
- error.hint = errorBody.hint;
221
- }
222
- if (errorBody.docsUrl !== void 0) {
223
- error.docsUrl = errorBody.docsUrl;
224
- }
225
- return error;
226
- };
227
- const encodeCallArgs = (payload, label) => {
228
- try {
229
- return encodeWire(payload);
230
- } catch (error) {
231
- const reason = error instanceof Error ? error.message : String(error);
232
- throw new TypeError(`LunoraClient: cannot encode ${label} — ${reason}`, error instanceof Error ? { cause: error } : void 0);
233
- }
234
- };
235
- const demuxBatchResults = (rawResults, count) => {
236
- const slots = Array.from({ length: count });
237
- for (const entry of rawResults) {
238
- if (typeof entry.id !== "number" || entry.id < 0 || entry.id >= count) {
239
- continue;
240
- }
241
- const inner = entry.body;
242
- slots[entry.id] = inner && "error" in inner && inner.error ? { error: reconstructError(inner.error), ok: false } : { ok: true, value: decodeWire(inner?.result) };
243
- }
244
- return slots.map((slot) => slot ?? { error: new Error("batch call returned no result"), ok: false });
245
- };
246
- const TRANSIENT_BATCH_ERROR_CODES = /* @__PURE__ */ new Set(["SHARD_ERROR", "SHARD_UNAVAILABLE"]);
247
- const RESOLVED_PROMISE = Promise.resolve();
248
- class LunoraClient {
249
- /** 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. */
250
- static MAX_POKE_BUFFERS = 256;
251
- /**
252
- * Create a typed {@link ClientQueryRef}. Convenience wrapper around
253
- * {@link createClientQuery} so you don't need a separate import.
254
- * @example
255
- * ```ts
256
- * const sidebarOpen = LunoraClient.createClientQuery("sidebarOpen", true);
257
- * ```
258
- */
259
- static createClientQuery(key, defaultValue) {
260
- return { defaultValue, key };
261
- }
262
- url;
263
- wsUrl;
264
- /** Local reactive store for {@link ClientQueryRef} values — no server round-trip. Private; reach it via `getClientQuery` / `setClientQuery` / `subscribeClientQuery`. */
265
- clientQueryStore;
266
- wsToken;
267
- /** Better-auth base path (trailing slash stripped) for the `get-session` lookup. */
268
- authBasePath;
269
- fetchImpl;
270
- WebSocketImpl;
271
- bookmark;
272
- reconnectOptions;
273
- /** WS connect timeout (ms); `0` disables it. See {@link LunoraClientOptions.connectTimeoutMs}. */
274
- connectTimeoutMs;
275
- /** Keepalive cadence (ms); `0` disables the heartbeat. See {@link LunoraClientOptions.heartbeatIntervalMs}. */
276
- heartbeatIntervalMs;
277
- offlineQueue;
278
- /**
279
- * Durable outbox seam (the `@lunora/db` `createExecutorOutboxSink`). When
280
- * set, offline writes are delegated here and the built-in {@link OfflineQueue}
281
- * is bypassed, so a db app has exactly one durable write path.
282
- */
283
- outbox;
284
- /** Stable per-client id stamped onto every `OutboxMutation` (custom-mutator watermark). */
285
- clientId;
286
- /**
287
- * `true` when the constructor's hydration microtask has finished loading the
288
- * durable read cache (Pillar 2) into `hydratedQueryCache`. Signals that
289
- * the cache is ready for synchronous `peekHydratedQuery` reads.
290
- */
291
- readyResolved = false;
292
- /** Resolvers for `whenReady()` — called once hydration completes. */
293
- readyResolve;
294
- /**
295
- * Promise that resolves once the durable read cache has been loaded. When
296
- * `hydrateOnStart` is not set or no query cache is configured, resolves
297
- * immediately (the constructor creates an already-resolved promise).
298
- */
299
- readyPromise;
300
- /**
301
- * Highest custom-mutator watermark the server has echoed for this client,
302
- * keyed by shard bucket (`shardKey ?? ""`) since the DO tracks one
303
- * `__client_watermark` per shard. `callMutator` bumps it from every
304
- * ack; the `@lunora/db` mutator runtime seeds its `clientSeq` generator from
305
- * it so a reload (which resets the in-memory counter) never reissues a stale
306
- * sequence the server would silently swallow as a replay.
307
- */
308
- clientWatermarks = /* @__PURE__ */ new Map();
309
- /** Monotonic per-client mutation counter backing the server `__client_watermark`. */
310
- outboxMutationCounter = 0;
311
- onPersistenceError;
312
- persistence;
313
- /** App/schema version stamped on persisted writes + cached reads; mismatches are purged. */
314
- persistenceVersion;
315
- /** Releases the multi-tab outbox-leader Web Lock on close (see `hydrateAsOutboxLeader`). */
316
- outboxLeaderRelease;
317
- /** Durable read cache (Pillar 2); `undefined` when `queryCache` is omitted or `false`. */
318
- queryCache;
319
- /**
320
- * Values restored from the `queryCache` at construction, keyed by the
321
- * read-cache key, awaiting the `subscribe()` that will consume them. A
322
- * key is consumed (deleted) the first time its subscription is created, so
323
- * the cache only ever seeds the initial value — live frames take over after.
324
- */
325
- hydratedQueryCache = /* @__PURE__ */ new Map();
326
- /**
327
- * Coalesced read-cache writes: the latest value per key, flushed to
328
- * the `queryCache` on a short debounce so a burst of deltas persists once.
329
- */
330
- pendingCacheWrites = /* @__PURE__ */ new Map();
331
- cacheFlushTimer;
332
- subscriptions = new SubscriptionRegistry();
333
- /**
334
- * Cross-tab coordinator; created only when `crossTabSync: true`. When the
335
- * client is not the elected leader, all WebSocket operations are skipped.
336
- * Not `readonly` — `close()` clears it (mirrors `outboxLeaderRelease`).
337
- */
338
- tabCoordinator;
339
- /** One {@link ShardConnection} per shard key (keyed by `shardKey ?? ""`). */
340
- connections = /* @__PURE__ */ new Map();
341
- /** Default `connect`-envelope context applied to a shard with no explicit override. */
342
- defaultConnectionContext;
343
- /**
344
- * Per-shard `connect`-envelope context registered via `setConnectionContext`
345
- * (keyed by `shardKey ?? ""`), overriding `defaultConnectionContext`. Sent
346
- * on every socket open so it replays across reconnects, and forwarded to the
347
- * server's `onConnect`/`onDisconnect` lifecycle hooks. This holds only the
348
- * imperative (last-writer-wins) override; refcounted holders registered via
349
- * `acquireConnectionContext` live in `connectionContextHolders` and take
350
- * precedence — see `effectiveConnectionContext`.
351
- */
352
- connectionContexts = /* @__PURE__ */ new Map();
353
- /**
354
- * Per-shard stack of refcounted connection-context holders (keyed by
355
- * `shardKey ?? ""`), registered via `acquireConnectionContext`. Each holder
356
- * is an opaque token carrying its `context`; the most-recently acquired
357
- * holder wins (last-writer-wins among live holders), and the context is only
358
- * cleared for a shard once its last holder releases — so two concurrently
359
- * mounted presence hooks on the same shard can't stomp each other's context
360
- * on cleanup. A holder is identified by reference identity so a release
361
- * removes exactly the right one regardless of stack position.
362
- */
363
- connectionContextHolders = /* @__PURE__ */ new Map();
364
- // `null` is the public sentinel for "signed out" across getAuthToken /
365
- // setAuthToken / onAuthTokenChange — part of the exported API contract.
366
- // eslint-disable-next-line unicorn/no-null -- public auth-token contract sentinel
367
- authToken = null;
368
- /**
369
- * Optional STABLE identity subject (a user id), the basis of the offline-queue
370
- * identity stamp when supplied. Keeps a same-user token *refresh* from looking
371
- * like an identity change (which would discard queued writes). `undefined` =
372
- * not supplied, so identity falls back to a hash of the raw token. See
373
- * `setAuthToken` / `identityFingerprint`.
374
- */
375
- authSubject = void 0;
376
- /**
377
- * Identity stamp recorded against each queued offline mutation, keyed by
378
- * the queue-assigned mutation id. Captured at enqueue from the auth token
379
- * in effect at the time, and re-checked at flush so a queued write can
380
- * never replay under a different identity than the one that issued it.
381
- * See `identityFingerprint` for the fingerprint shape.
382
- */
383
- queuedIdentities = /* @__PURE__ */ new Map();
384
- closed = false;
385
- /** Subscribers to auth-token changes (see `onAuthTokenChange`). */
386
- authTokenListeners = new Listeners();
387
- /** Subscribers to aggregate connection-status changes (see `onConnectionStatus`). */
388
- statusListeners = new Listeners();
389
- /** Subscribers notified when the server drops a socket for an expired token (see `onTokenExpired`). */
390
- tokenExpiredListeners = new Listeners();
391
- /** Subscribers to offline-queued mutation verdicts (see `onMutationSettled`). */
392
- mutationSettledListeners = new Listeners();
393
- /** Subscribers to the offline-queue pending-count (see `onPendingChange`). */
394
- pendingChangeListeners = new Listeners();
395
- /**
396
- * Whisper-topic handlers, keyed by `connectionKey(shardKey)` → topic → set
397
- * of callbacks. Membership doubles as the resubscribe set replayed on every
398
- * (re)connect so a topic survives a socket bounce.
399
- */
400
- whisperHandlers = /* @__PURE__ */ new Map();
401
- /** Last status broadcast, so we only notify listeners on an actual change. */
402
- lastStatus = "idle";
403
- nextSubId = 0;
404
- nextStreamId = 0;
405
- /**
406
- * In-flight client-side stream readers, keyed by the stream id sent on the
407
- * wire. The handle drives the underlying iterator queue and `shardKey`
408
- * tells us which socket to push the cancel frame onto when the consumer
409
- * calls `.cancel()` or the iterator is garbage-collected.
410
- */
411
- streams = /* @__PURE__ */ new Map();
412
- /** Live shape subscriptions (partial replication), keyed by their wire id. */
413
- shapeSubscriptions = /* @__PURE__ */ new Map();
414
- /** In-flight pokes being assembled between `pokeStart` and `pokeEnd`, keyed by `pokeId`. */
415
- pokeBuffers = /* @__PURE__ */ new Map();
416
- nextShapeId = 0;
417
- constructor(options) {
418
- this.url = options.url;
419
- this.wsUrl = options.wsUrl ?? joinUrl(deriveWsUrl(options.url), WS_PATH);
420
- this.wsToken = options.wsToken;
421
- const authBase = options.authBasePath ?? DEFAULT_AUTH_BASE_PATH;
422
- this.authBasePath = authBase.endsWith("/") ? authBase.slice(0, -1) : authBase;
423
- this.fetchImpl = options.fetch ?? (typeof fetch === "function" ? fetch.bind(globalThis) : void 0);
424
- this.WebSocketImpl = options.WebSocket ?? (typeof WebSocket === "function" ? WebSocket : void 0);
425
- this.bookmark = options.bookmarkStorage ?? createInMemoryBookmarkStorage();
426
- this.reconnectOptions = options.reconnect;
427
- this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
428
- this.connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
429
- this.defaultConnectionContext = options.connectionContext;
430
- this.persistence = resolvePersistenceAdapter(options.persistence, options.outbox === void 0);
431
- this.persistenceVersion = options.persistenceVersion;
432
- this.queryCache = resolveQueryCacheAdapter(options.queryCache);
433
- this.onPersistenceError = options.offlineQueue?.onPersistenceError;
434
- this.clientQueryStore = new ClientQueryStore();
435
- if (options.crossTabSync) {
436
- this.tabCoordinator = new TabCoordinator({
437
- onBecomeLeader: () => {
438
- for (const state of this.subscriptions.all()) {
439
- this.ensureSocket(state.shardKey);
440
- this.sendSubscribeIfOpen(state);
441
- }
442
- },
443
- onStopBeingLeader: () => {
444
- for (const [key, conn] of this.connections) {
445
- conn.socket?.close();
446
- this.connections.delete(key);
447
- }
448
- },
449
- onSubscriptionData: (key, data) => {
450
- const state = this.subscriptions.get(key);
451
- if (state) {
452
- state.serverBase = data;
453
- const folded = state.optimisticLayers.length === 0 ? data : foldOptimistic(data, state.optimisticLayers);
454
- state.lastValue = folded;
455
- for (const callback of state.callbacks) {
456
- try {
457
- callback(folded);
458
- } catch {
459
- }
460
- }
461
- }
462
- },
463
- onSubscriptionError: (key, error) => {
464
- const state = this.subscriptions.get(key);
465
- if (state) {
466
- for (const callback of state.errorCallbacks) {
467
- try {
468
- callback(error);
469
- } catch {
470
- }
471
- }
472
- }
473
- }
474
- });
475
- this.tabCoordinator.start();
476
- } else {
477
- this.tabCoordinator = void 0;
478
- }
479
- if (options.hydrateOnStart && this.queryCache) {
480
- this.readyPromise = new Promise((resolve) => {
481
- this.readyResolve = resolve;
482
- });
483
- } else {
484
- this.readyResolved = true;
485
- this.readyPromise = RESOLVED_PROMISE;
486
- }
487
- this.offlineQueue = new OfflineQueue(options.offlineQueue, {
488
- onEvict: (entry, error) => {
489
- this.emitItemSettled(entry, "rejected", error);
490
- },
491
- onSizeChange: (size) => {
492
- this.pendingChangeListeners.emit(size);
493
- },
494
- persistence: this.persistence,
495
- version: options.persistenceVersion
496
- });
497
- this.outbox = options.outbox;
498
- this.clientId = options.clientId ?? `client-${nextId()}`;
499
- if (this.persistence) {
500
- queueMicrotask(() => {
501
- this.hydrateAsOutboxLeader();
502
- });
503
- }
504
- if (this.queryCache) {
505
- queueMicrotask(() => {
506
- const hydration = async () => {
507
- try {
508
- await this.hydrateQueryCache();
509
- } catch {
510
- } finally {
511
- this.readyResolved = true;
512
- this.readyResolve?.();
513
- }
514
- };
515
- hydration().catch(() => {
516
- });
517
- });
518
- }
519
- }
520
- // --- Auth helpers -------------------------------------------------------
521
- /**
522
- * Set (or clear) the bearer token sent on every HTTP RPC. Notifies any
523
- * {@link onAuthTokenChange} listeners so React hooks like `useAuth` stay in
524
- * sync across all mounted instances.
525
- *
526
- * Pass a STABLE `subject` (the user id) to key the offline-queue identity on
527
- * it instead of the token bytes, so a token *refresh* (same user, new JWT)
528
- * doesn't read as an identity change and discard queued writes. The subject is
529
- * **sticky**: a later call that omits it (or passes `undefined`) keeps the
530
- * established subject — so `setAuthToken(refreshedToken)` after a prior
531
- * `setAuthToken(token, user.id)` retains the identity. Pass `null` to clear it
532
- * (an explicit sign-out). Establishing the subject for the first time on an
533
- * UNCHANGED token (e.g. the user id resolves a tick after the token was set)
534
- * re-stamps any in-flight queued writes rather than dropping them — same
535
- * credential, just a more stable label. A real user switch (the token AND
536
- * subject both change) still drops the previous user's writes.
537
- *
538
- * Does NOT update the WebSocket auth — the WS token is fixed at upgrade
539
- * time and lives in the URL. To refresh live WS auth, call
540
- * {@link setWsToken} explicitly, which closes existing shard sockets to
541
- * force a reconnect with the new credential.
542
- */
543
- setAuthToken(token, subject) {
544
- const tokenChanged = this.authToken !== token;
545
- const previousIdentity = this.identityFingerprint();
546
- this.authToken = token;
547
- if (subject !== void 0) {
548
- this.authSubject = subject;
549
- }
550
- const newIdentity = this.identityFingerprint();
551
- if (newIdentity !== previousIdentity) {
552
- if (tokenChanged) {
553
- this.rejectQueuedForIdentityChange();
554
- } else {
555
- this.restampQueuedIdentity(previousIdentity, newIdentity);
556
- }
557
- }
558
- if (tokenChanged) {
559
- this.authTokenListeners.emit(token);
560
- }
561
- }
562
- getAuthToken() {
563
- return this.authToken;
564
- }
565
- /**
566
- * The current identity fingerprint (the same stamp queued offline writes
567
- * carry). Exposed so a durable {@link OutboxSink}'s replay handler — which
568
- * owns its own at-least-once replay outside the built-in `OfflineQueue` —
569
- * can drop a persisted write whose captured `identity` no longer matches the
570
- * signed-in user, the guard the queue path applies in `flushOfflineQueue`.
571
- */
572
- currentIdentity() {
573
- return this.identityFingerprint();
574
- }
575
- /** This client's stable identifier — the watermark key the server's custom-mutator protocol advances per `clientSeq`. */
576
- clientIdentifier() {
577
- return this.clientId;
578
- }
579
- /**
580
- * The highest custom-mutator watermark the server has echoed for this client
581
- * on the given shard (0 if none yet). The `@lunora/db` mutator runtime seeds
582
- * its `clientSeq` generator from this so a reload never reissues a sequence
583
- * the server has already applied (which it would swallow as a replay, silently
584
- * dropping the write).
585
- */
586
- confirmedMutationWatermark(shardKey) {
587
- return this.clientWatermarks.get(shardKey ?? "") ?? 0;
588
- }
589
- /**
590
- * Push a custom mutator to its authoritative server impl over the watermark
591
- * protocol (Phase 4): the request carries `x-lunora-client-id` + a monotonic
592
- * `x-lunora-client-seq`, so the DO runs it exactly once and advances this
593
- * client's `__client_watermark`.
594
- *
595
- * Returns the server `result` plus `applied`: `true` when the DO ran this push
596
- * as the next-in-order mutation, `false` when it was a replay ack (`clientSeq`
597
- * was at or below the stored watermark — e.g. a stale sequence after a reload).
598
- * A `false` verdict tells the caller to reissue above the now-known watermark
599
- * (echoed into {@link confirmedMutationWatermark}) rather than treat the benign
600
- * ack as a confirmed write. Every ack — applied or not — bumps the watermark.
601
- *
602
- * This is the online transport for `@lunora/db`'s client-mutator runtime; the
603
- * optimistic overlay + durable-outbox concerns live in that runtime, not here.
604
- */
605
- async callMutator(functionPath, args, options) {
606
- const clientSeq = options?.clientSeq;
607
- if (clientSeq !== void 0 && (!Number.isInteger(clientSeq) || clientSeq <= 0)) {
608
- throw new LunoraError("INTERNAL", `callMutator: clientSeq must be a positive integer, got ${String(clientSeq)}`);
609
- }
610
- const bucket = options?.shardKey ?? "";
611
- let ackWatermark;
612
- const result = await this.rpc(functionPath, args, options?.shardKey, {
613
- captureBookmark: true,
614
- clientId: this.clientId,
615
- clientSeq,
616
- onMutationAck: (lastMutationId) => {
617
- ackWatermark = lastMutationId;
618
- }
619
- });
620
- if (ackWatermark !== void 0 && ackWatermark > (this.clientWatermarks.get(bucket) ?? 0)) {
621
- this.clientWatermarks.set(bucket, ackWatermark);
622
- }
623
- const applied = ackWatermark === void 0 || ackWatermark === clientSeq;
624
- return { applied, result };
625
- }
626
- /**
627
- * Subscribe to auth-token changes. Returns an unsubscribe function. The
628
- * listener is NOT invoked on registration — use {@link getAuthToken} for
629
- * the current value.
630
- */
631
- onAuthTokenChange(listener) {
632
- return this.authTokenListeners.add(listener);
633
- }
634
- /**
635
- * Fetch the currently authenticated user from better-auth's `get-session`
636
- * endpoint, returning the `user` record or `null` when signed out. Sends
637
- * the stored bearer token (if any) and `credentials: "include"` so a
638
- * cookie-session is also honoured. A network/parse failure or a non-OK
639
- * response resolves to `null` rather than throwing — callers treat "couldn't
640
- * resolve identity" as "signed out".
641
- *
642
- * Framework-agnostic: pair it with {@link onAuthTokenChange} to refetch when
643
- * the token changes (that's what `@lunora/react`'s `useAuth` does).
644
- */
645
- async getCurrentUser() {
646
- if (this.closed || !this.fetchImpl) {
647
- return null;
648
- }
649
- const headers = {};
650
- if (this.authToken) {
651
- headers["authorization"] = `Bearer ${this.authToken}`;
652
- }
653
- try {
654
- const response = await this.fetchImpl(joinUrl(this.url, `${this.authBasePath}${GET_SESSION_PATH}`), {
655
- credentials: "include",
656
- headers,
657
- method: "GET"
658
- });
659
- if (!response.ok) {
660
- return null;
661
- }
662
- const body = await response.json();
663
- return body?.user ?? null;
664
- } catch {
665
- return null;
666
- }
667
- }
668
- /**
669
- * Replace the token appended to WS upgrade URLs as `?token=…` and close
670
- * every open shard socket so the reconnect picks up the new value. Call
671
- * this whenever the user's WS credential changes (rotating the admin token
672
- * in the studio, switching workspaces, etc.). Accepts a static string or a
673
- * {@link WsTokenProvider} resolved fresh at every (re)connect — the channel
674
- * for short-lived credentials like the minted ephemeral admin sub-token.
675
- * Bearer tokens for HTTP RPC are independent — see {@link setAuthToken}.
676
- */
677
- setWsToken(token) {
678
- if (this.wsToken === token) {
679
- return;
680
- }
681
- this.wsToken = token;
682
- for (const conn of this.connections.values()) {
683
- if (conn.socket) {
684
- try {
685
- conn.socket.close();
686
- } catch {
687
- }
688
- }
689
- }
690
- }
691
- /**
692
- * Register (or clear, with `undefined`) the app context sent in the `connect`
693
- * envelope for a shard's socket, overriding the client-wide
694
- * {@link LunoraClientOptions.connectionContext}. The server forwards it to the
695
- * `onConnect`/`onDisconnect` lifecycle hooks as `event.context` — e.g.
696
- * `@lunora/react`'s `usePresence` registers `{ roomId, sessionId }` so the
697
- * presence row is removed the instant the socket drops, with no TTL lag.
698
- *
699
- * Stored per shard and replayed on every (re)connect. When a socket for the
700
- * shard is already open, a fresh `connect` envelope is sent immediately so the
701
- * server sees the new context without waiting for a reconnect.
702
- */
703
- setConnectionContext(context, options = {}) {
704
- const key = connectionKey(options.shardKey);
705
- if (context === void 0) {
706
- this.connectionContexts.delete(key);
707
- } else {
708
- this.connectionContexts.set(key, context);
709
- }
710
- this.refreshConnectionContext(key);
711
- }
712
- /**
713
- * Refcounted variant of {@link setConnectionContext}: register a connection
714
- * `context` for a shard and get back a release function. Unlike the imperative
715
- * setter, the context is only cleared once the *last* acquired holder releases
716
- * it — so two components (e.g. two mounted `usePresence` hooks) on the same
717
- * shard no longer clobber each other's context when one of them unmounts. The
718
- * most-recently acquired live holder wins (last-writer-wins), and releasing
719
- * the top holder falls back to the previous one rather than clearing.
720
- *
721
- * With a single holder the behaviour is identical to a
722
- * `setConnectionContext(context)` / `setConnectionContext(undefined)` pair.
723
- * Releasing more than once is a no-op (the holder is matched by reference, so
724
- * a double release can't drop a different holder).
725
- */
726
- acquireConnectionContext(context, options = {}) {
727
- const key = connectionKey(options.shardKey);
728
- const holder = { context };
729
- const holders = this.connectionContextHolders.get(key);
730
- if (holders) {
731
- holders.push(holder);
732
- } else {
733
- this.connectionContextHolders.set(key, [holder]);
734
- }
735
- this.refreshConnectionContext(key);
736
- let released = false;
737
- return () => {
738
- if (released) {
739
- return;
740
- }
741
- released = true;
742
- const live = this.connectionContextHolders.get(key);
743
- if (!live) {
744
- return;
745
- }
746
- const index = live.indexOf(holder);
747
- if (index !== -1) {
748
- live.splice(index, 1);
749
- }
750
- if (live.length === 0) {
751
- this.connectionContextHolders.delete(key);
752
- }
753
- this.refreshConnectionContext(key);
754
- };
755
- }
756
- // --- Whispering ---------------------------------------------------------
757
- /**
758
- * Join a whisper `topic` and receive every ephemeral message other members
759
- * broadcast to it on the same shard (typing indicators, live cursors,
760
- * presence pings). Whispers never touch the server's durable state — there's
761
- * no query, no row, no CDC entry. Returns an unsubscribe function; the topic
762
- * is left on the server once its last local handler unsubscribes.
763
- *
764
- * `handler` receives the raw `data` and the sender's verified `from` user id
765
- * (omitted for an anonymous sender). The topic is scoped to `options.shardKey`
766
- * (the default shard when omitted) — use the same shard you target with the
767
- * matching queries/mutations so members land on the same Durable Object.
768
- *
769
- * Security: whisper topics are NOT access-controlled beyond the shard
770
- * boundary — any client that can open a socket to the shard can join, read,
771
- * and inject on any topic name. `from` is server-stamped and unforgeable, but
772
- * do not put data on a whisper topic that some shard members shouldn't see,
773
- * and don't trust a whisper's `data` as authorization. Use a query/mutation
774
- * (with RLS) for anything privileged; whispers are for transient awareness.
775
- */
776
- whisperSubscribe(topic, handler, options = {}) {
777
- const key = connectionKey(options.shardKey);
778
- let byTopic = this.whisperHandlers.get(key);
779
- if (!byTopic) {
780
- byTopic = /* @__PURE__ */ new Map();
781
- this.whisperHandlers.set(key, byTopic);
782
- }
783
- let handlers = byTopic.get(topic);
784
- const first = handlers === void 0;
785
- if (!handlers) {
786
- handlers = /* @__PURE__ */ new Set();
787
- byTopic.set(topic, handlers);
788
- }
789
- handlers.add(handler);
790
- this.ensureSocket(options.shardKey);
791
- if (first) {
792
- const conn = this.getConnection(options.shardKey);
793
- if (conn) {
794
- sendOn(conn, { topic, type: "whisper_subscribe" });
795
- }
796
- }
797
- return () => {
798
- const stillByTopic = this.whisperHandlers.get(key);
799
- const stillHandlers = stillByTopic?.get(topic);
800
- if (!stillHandlers?.delete(handler) || stillHandlers.size > 0) {
801
- return;
802
- }
803
- stillByTopic?.delete(topic);
804
- if (stillByTopic?.size === 0) {
805
- this.whisperHandlers.delete(key);
806
- }
807
- const conn = this.getConnection(options.shardKey);
808
- if (conn) {
809
- sendOn(conn, { topic, type: "whisper_unsubscribe" });
810
- }
811
- };
812
- }
813
- /**
814
- * Broadcast an ephemeral `data` payload to the other members of a whisper
815
- * `topic` on `options.shardKey`'s shard. Fire-and-forget: the frame is
816
- * dropped when the shard socket isn't open (whispers are transient, never
817
- * queued), and the server silently drops it if the sender exceeds its
818
- * whisper rate budget. The sender never receives its own whisper. Omitting
819
- * `data` delivers JSON `null` to receivers (not `undefined`).
820
- */
821
- whisper(topic, data, options = {}) {
822
- this.ensureSocket(options.shardKey);
823
- const conn = this.getConnection(options.shardKey);
824
- if (conn) {
825
- sendOn(conn, { data: encodeCallArgs(data ?? null, `whisper data for topic '${topic}'`), topic, type: "whisper" });
826
- }
827
- }
828
- /**
829
- * Subscribe to token-expiry events: invoked whenever the server drops a
830
- * shard socket because the connection's credential lapsed (close code
831
- * `4001`). The client already reconnects automatically (re-resolving
832
- * identity from the cookie/token in effect); use this to refresh a
833
- * short-lived token first — e.g. call {@link setWsToken} / {@link setAuthToken}
834
- * with a freshly minted one. Returns an unsubscribe function.
835
- */
836
- onTokenExpired(listener) {
837
- return this.tokenExpiredListeners.add(listener);
838
- }
839
- // --- Connection status --------------------------------------------------
840
- /**
841
- * Current aggregate live-socket status across all shard connections. See
842
- * {@link ConnectionStatus}.
843
- */
844
- connectionStatus() {
845
- return this.computeStatus();
846
- }
847
- /**
848
- * Subscribe to aggregate connection-status changes. Invokes `listener`
849
- * immediately with the current status, then on every transition. Returns an
850
- * unsubscribe function.
851
- */
852
- onConnectionStatus(listener) {
853
- const unsubscribe = this.statusListeners.add(listener);
854
- listener(this.computeStatus());
855
- return unsubscribe;
856
- }
857
- /**
858
- * Number of offline writes waiting in the built-in queue to be sent — the
859
- * depth for a "N changes waiting to sync" indicator. Counts writes that are
860
- * queued (offline / mid-reconnect), not ones already in flight on the wire.
861
- * A `@lunora/db` app whose writes ride the unified outbox should read
862
- * `LunoraDb.pendingCount()` instead (this counts only the built-in queue).
863
- */
864
- pendingCount() {
865
- return this.offlineQueue.size;
866
- }
867
- /**
868
- * Subscribe to changes in {@link pendingCount}. Invokes `listener` immediately
869
- * with the current count, then whenever the queue depth changes (a write is
870
- * enqueued, flushed, or discarded). Returns an unsubscribe function.
871
- */
872
- onPendingChange(listener) {
873
- const unsubscribe = this.pendingChangeListeners.add(listener);
874
- listener(this.offlineQueue.size);
875
- return unsubscribe;
876
- }
877
- /**
878
- * Subscribe to terminal verdicts for offline-queued mutations. The listener
879
- * fires once per queued write that commits or is rejected — including a write
880
- * restored from durable storage after a reload, whose original `mutation()`
881
- * Promise no longer exists (`hadAwaiter: false`), and a write the queue
882
- * evicts on overflow or discards on an identity change. This is the durable
883
- * channel for surfacing a rolled-back optimistic write to the UI; an online
884
- * mutation that never queued still surfaces through the Promise `mutation()`
885
- * returns. The listener is NOT invoked on registration. Returns an
886
- * unsubscribe function. See {@link MutationSettledEvent}.
887
- */
888
- onMutationSettled(listener) {
889
- return this.mutationSettledListeners.add(listener);
890
- }
891
- // --- Client Query (local state) ----------------------------------------
892
- /**
893
- * Read the current value for a {@link ClientQueryRef}. Returns
894
- * `ref.defaultValue` when no value has been explicitly set.
895
- */
896
- getClientQuery(ref) {
897
- return this.clientQueryStore.get(ref);
898
- }
899
- /**
900
- * Set a new value for `ref` and notify every subscriber. Pass `undefined`
901
- * to reset the slot to `ref.defaultValue`.
902
- */
903
- setClientQuery(ref, value) {
904
- this.clientQueryStore.set(ref, value);
905
- }
906
- /**
907
- * Subscribe to changes for `ref`. The callback is NOT invoked on
908
- * registration — call {@link getClientQuery} for the current value.
909
- * Returns an unsubscribe function.
910
- */
911
- subscribeClientQuery(ref, callback) {
912
- return this.clientQueryStore.subscribe(ref, callback);
913
- }
914
- /**
915
- * Reset a {@link ClientQueryRef} to its default value, notifying every
916
- * subscriber. Equivalent to `setClientQuery(ref, ref.defaultValue)` but
917
- * removes the stored entry so a future {@link getClientQuery} returns
918
- * the default rather than an explicitly-set value.
919
- */
920
- resetClientQuery(ref) {
921
- this.clientQueryStore.reset(ref);
922
- }
923
- /**
924
- * Capture a snapshot of the current live query value at call time and
925
- * produce a `() => boolean` precondition that compares it against the
926
- * value at replay time (on queue drain / reconnect).
927
- *
928
- * When the precondition is checked it re-reads the query's current value
929
- * via `peekActiveQueryValue`. If the value differs from what was
930
- * captured at call time the precondition returns `false` and the offline
931
- * mutation is dropped as stale.
932
- *
933
- * This is a method wrapper around `createSnapshotPrecondition` that
934
- * binds the client instance for you — no need to pass `client` explicitly.
935
- * @example
936
- * ```ts
937
- * client.mutation(api.todos.update, { id, text }, {
938
- * precondition: client.snapshotPrecondition(api.todos.list, { userId }),
939
- * });
940
- * ```
941
- */
942
- snapshotPrecondition(functionRef, args, shardKey) {
943
- const snapshot = this.peekActiveQueryValue(functionRef.__lunoraRef, args, shardKey);
944
- const snapshotKey = snapshot === void 0 ? void 0 : stableWireKey(snapshot);
945
- return () => {
946
- const current = this.peekActiveQueryValue(functionRef.__lunoraRef, args, shardKey);
947
- if (snapshotKey === void 0 && current === void 0) {
948
- return true;
949
- }
950
- if (snapshotKey === void 0 || current === void 0) {
951
- return false;
952
- }
953
- return stableWireKey(current) === snapshotKey;
954
- };
955
- }
956
- // --- Hydration helpers --------------------------------------------------
957
- /**
958
- * Resolves once the durable read cache has been loaded into memory. When
959
- * `hydrateOnStart` is not configured or no query cache adapter is active,
960
- * returns an already-resolved promise so callers can always await it
961
- * unconditionally.
962
- *
963
- * Framework adapters (React, Vue, etc.) use this to gate the first
964
- * (enabled) render of a live query behind hydration, so the user sees
965
- * cached data instead of an undefined flash before the socket round-trip.
966
- */
967
- whenReady() {
968
- return this.readyPromise;
969
- }
970
- /**
971
- * Synchronously reports whether {@link whenReady} has already resolved (the
972
- * durable read cache is loaded, or none is configured). Framework adapters
973
- * read this to seed the hydration-gate state on the first render without
974
- * awaiting, then subscribe via {@link whenReady} for the pending case.
975
- */
976
- get isReady() {
977
- return this.readyResolved;
978
- }
979
- /**
980
- * Synchronously peek at a value the durable read cache loaded for the given
981
- * function path + args + shard key. Returns `undefined` when:
982
- *
983
- * - No query cache adapter is configured.
984
- * - Hydration hasn't completed yet (race — await {@link whenReady} first).
985
- * - The cached value's identity fingerprint doesn't match the current auth.
986
- *
987
- * Unlike the internal {@link takeHydratedCache}, this is a READ-ONLY peek:
988
- * the cached entry stays in `hydratedQueryCache` so the subscription created
989
- * later by {@link subscribe} consumes it normally.
990
- */
991
- peekHydratedQuery(functionPath, args, shardKey) {
992
- if (!this.readyResolved) {
993
- return void 0;
994
- }
995
- const argsKey = stableWireKey(args);
996
- const key = queryCacheKey(functionPath, argsKey, shardKey);
997
- const entry = this.hydratedQueryCache.get(key);
998
- if (entry === void 0) {
999
- return void 0;
1000
- }
1001
- return entry.identity === this.identityFingerprint() ? entry.value : void 0;
1002
- }
1003
- /**
1004
- * Peek at the **current live value** of an active subscription, if one
1005
- * exists. Returns the subscription's `lastValue` (which includes any
1006
- * optimistic overlay) or `undefined` if no subscription is active for the
1007
- * given `(functionPath, args, shardKey)`.
1008
- *
1009
- * Unlike {@link peekHydratedQuery} (which reads from the durable read cache
1010
- * and is independent of active subscriptions), this method reflects the
1011
- * current in-memory state of an already-opened subscription — useful for
1012
- * offline mutation preconditions that need to snapshot the value at call time
1013
- * and compare it at replay time.
1014
- */
1015
- peekActiveQueryValue(functionPath, args, shardKey) {
1016
- const key = SubscriptionRegistry.key(functionPath, args, shardKey);
1017
- const state = this.subscriptions.get(key);
1018
- return state?.lastValue;
1019
- }
1020
- // --- RPC ---------------------------------------------------------------
1021
- async query(function_, args, options = {}) {
1022
- if (this.closed) {
1023
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1024
- }
1025
- return await this.rpc(function_.__lunoraRef, args, options.shardKey, { attachBookmark: true });
1026
- }
1027
- /**
1028
- * Batch several independent calls into ONE round trip (plan 088). Each call is
1029
- * dispatched server-side exactly as an individual RPC — per-shard
1030
- * authorization, `(identity, mutationId)` idempotency, and custom-mutator
1031
- * watermark ordering are all preserved — and the worker splits the batch by
1032
- * shard so calls to different shards fan out to their own DOs. Results are
1033
- * demuxed back in input order; a failing call does NOT fail the batch (its
1034
- * slot carries `{ ok: false, error }`, with `.code`/`.data` reconstructed like
1035
- * a single call). Args/results ride the value codec (bytes/bigint survive).
1036
- *
1037
- * No promise pipelining and no capability passing — a call's args cannot
1038
- * reference another call's result (see plan 088 §fence; capabilities are
1039
- * incompatible with DO hibernation).
1040
- */
1041
- async batch(calls) {
1042
- if (this.closed) {
1043
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1044
- }
1045
- if (!this.fetchImpl) {
1046
- throw new LunoraError("INTERNAL", "LunoraClient: no `fetch` implementation available");
1047
- }
1048
- if (calls.length === 0) {
1049
- return [];
1050
- }
1051
- const response = await this.fetchImpl(joinUrl(this.url, RPC_BATCH_PATH), {
1052
- body: JSON.stringify({
1053
- calls: calls.map((call, index) => {
1054
- return {
1055
- args: encodeCallArgs(call.args ?? {}, `args for batch call '${call.fn.__lunoraRef}'`),
1056
- functionPath: call.fn.__lunoraRef,
1057
- id: index,
1058
- shardKey: call.shardKey
1059
- };
1060
- })
1061
- }),
1062
- headers: this.rpcRequestHeaders({ attachBookmark: true }),
1063
- method: "POST"
1064
- });
1065
- const bookmark = response.headers.get("x-d1-bookmark");
1066
- if (bookmark) {
1067
- this.bookmark.set(bookmark);
1068
- }
1069
- let body;
1070
- try {
1071
- body = await response.json();
1072
- } catch {
1073
- throw new LunoraError("INTERNAL", `LunoraClient: batch response was not JSON (status ${response.status.toString()})`);
1074
- }
1075
- if (!response.ok || body.error && !body.results) {
1076
- if (body.error) {
1077
- throw reconstructError(body.error);
1078
- }
1079
- throw new LunoraError("INTERNAL", `LunoraClient: batch request failed (status ${response.status.toString()})`);
1080
- }
1081
- return demuxBatchResults(body.results ?? [], calls.length);
1082
- }
1083
- /**
1084
- * Invoke a mutation. Errors propagate as rejections.
1085
- *
1086
- * Offline-queue semantics: a mutation is queued (and replayed on reconnect)
1087
- * only when the targeted shard's socket was open at least once already
1088
- * (`wasEverConnected`), so the registry / resubscribe handshake has run.
1089
- * Mutations issued before the very first WS connect to a shard fail fast.
1090
- * Opt into queueing-before-first-connect via
1091
- * `OfflineQueueOptions.queueBeforeFirstConnect`.
1092
- */
1093
- async mutation(function_, args, options = {}) {
1094
- if (this.closed) {
1095
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1096
- }
1097
- const argsRecord = args;
1098
- const mutationId = options.mutationId ?? nextId();
1099
- const { confirms: optimisticConfirms, rollbacks: optimisticRollbacks } = this.applyOptimisticUpdates(
1100
- function_.__lunoraRef,
1101
- argsRecord,
1102
- options.shardKey,
1103
- options.optimistic
1104
- );
1105
- if (options.optimisticUpdate) {
1106
- this.applyOptimisticUpdate(options.optimisticUpdate, args, options.shardKey, optimisticRollbacks, optimisticConfirms);
1107
- }
1108
- const conn = this.getConnection(options.shardKey);
1109
- const wsState = conn?.wsState ?? "idle";
1110
- const hasSocket = conn?.socket !== void 0;
1111
- const wasEverConnected = conn?.wasEverConnected ?? false;
1112
- const { queueBeforeFirstConnect } = this.offlineQueue;
1113
- const connectedGate = wasEverConnected || queueBeforeFirstConnect;
1114
- const shouldQueueOffline = this.WebSocketImpl !== void 0 && connectedGate;
1115
- const midReconnect = wsState === "connecting" && connectedGate;
1116
- if (wsState !== "open" && !hasSocket && shouldQueueOffline || midReconnect) {
1117
- return this.enqueueOfflineMutation(
1118
- function_,
1119
- argsRecord,
1120
- options.shardKey,
1121
- mutationId,
1122
- optimisticRollbacks,
1123
- optimisticConfirms,
1124
- options.precondition
1125
- );
1126
- }
1127
- try {
1128
- let commitCursor;
1129
- const result = await this.rpc(function_.__lunoraRef, argsRecord, options.shardKey, {
1130
- captureBookmark: true,
1131
- mutationId,
1132
- onCommitCursor: (cursor) => {
1133
- commitCursor = cursor;
1134
- }
1135
- });
1136
- for (const confirm of optimisticConfirms) {
1137
- confirm(commitCursor);
1138
- }
1139
- return result;
1140
- } catch (error) {
1141
- rollbackOptimistic(optimisticRollbacks);
1142
- throw error;
1143
- }
1144
- }
1145
- async action(function_, args, options = {}) {
1146
- if (this.closed) {
1147
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1148
- }
1149
- return await this.rpc(function_.__lunoraRef, args, options.shardKey);
1150
- }
1151
- // --- Advisor admin ------------------------------------------------------
1152
- /**
1153
- * Read the cross-shard request distribution for a `.shardBy(...)` table —
1154
- * the feed the studio's `hot_shard` advisor lint consumes. Hits the
1155
- * admin-gated `POST /_lunora/admin/shard-traffic` endpoint, which fans the
1156
- * cheap per-shard `getMetrics` read out across every live shard and returns
1157
- * each shard's `{ shardKey, requests }` total (a failed shard surfaces with
1158
- * `requests: 0`). Requires the worker to be built with a `queryCoordinator`
1159
- * and `adminToken`, and this client's auth token to match; defaults any
1160
- * absent field so an older worker yields an empty-but-valid shape.
1161
- */
1162
- async shardTraffic(table) {
1163
- if (this.closed) {
1164
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1165
- }
1166
- const body = await this.adminFetch(SHARD_TRAFFIC_PATH, "POST", { table });
1167
- return { failed: body.failed ?? 0, ok: body.ok ?? 0, shards: body.shards ?? [] };
1168
- }
1169
- // --- Scheduler admin ----------------------------------------------------
1170
- /**
1171
- * List the functions queued via `runAfter` / `runAt`, soonest-due last
1172
- * (the worker returns them in storage order). Hits the admin-gated
1173
- * `/_lunora/admin/scheduled` endpoint, so the worker must be built with a
1174
- * `schedulerDO` namespace and `adminToken`, and this client's auth token
1175
- * must match. Powers `@lunora/studio`'s scheduled-jobs panel.
1176
- */
1177
- async listScheduledJobs() {
1178
- if (this.closed) {
1179
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1180
- }
1181
- const body = await this.adminFetch(SCHEDULED_PATH, "GET");
1182
- return body.records ?? [];
1183
- }
1184
- /**
1185
- * Read the app-level workpool backlog that powers `@lunora/studio`'s SLO
1186
- * view: per-pool `{ name, queued, inFlight, maxConcurrency }` plus the
1187
- * app-wide `backlog` (total queued) and `inFlight` (total held slots) sums.
1188
- * Hits the admin-gated `GET /_lunora/admin/scheduled/status` endpoint, so the
1189
- * same preconditions as {@link listScheduledJobs} apply (a `schedulerDO`
1190
- * namespace + `adminToken` on the worker and a matching auth token here).
1191
- * Defaults any absent field so an older worker still yields a valid shape.
1192
- */
1193
- async schedulerStatus() {
1194
- if (this.closed) {
1195
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1196
- }
1197
- const body = await this.adminFetch(SCHEDULED_STATUS_PATH, "GET");
1198
- return {
1199
- backlog: body.backlog ?? 0,
1200
- inFlight: body.inFlight ?? 0,
1201
- pools: body.pools ?? []
1202
- };
1203
- }
1204
- /** Cancel a pending scheduled job by id. Returns whether a job was removed. */
1205
- async cancelScheduledJob(id) {
1206
- if (this.closed) {
1207
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1208
- }
1209
- const body = await this.adminFetch(SCHEDULED_CANCEL_PATH, "POST", { id });
1210
- return { cancelled: body.cancelled === true };
1211
- }
1212
- /**
1213
- * List the dead-letter jobs: schedules that exhausted their retry budget
1214
- * and were parked instead of dropped. These never appear in
1215
- * {@link listScheduledJobs} (their live header is gone), so this is the only
1216
- * way the studio surfaces a permanently-failed job. Hits the admin-gated
1217
- * `GET /_lunora/admin/scheduled/dead`; same preconditions as
1218
- * {@link listScheduledJobs}. Powers `@lunora/studio`'s dead-letter panel.
1219
- */
1220
- async listDeadJobs() {
1221
- if (this.closed) {
1222
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1223
- }
1224
- const body = await this.adminFetch(SCHEDULED_DEAD_PATH, "GET");
1225
- return body.records ?? [];
1226
- }
1227
- /**
1228
- * Resurrect a dead-letter job by id: it re-enters the schedule with a fresh
1229
- * retry budget and fires on the next drain. Returns whether a parked record
1230
- * matched. Hits the admin-gated `POST /_lunora/admin/scheduled/dead/retry`.
1231
- */
1232
- async retryDeadJob(id) {
1233
- if (this.closed) {
1234
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1235
- }
1236
- const body = await this.adminFetch(SCHEDULED_DEAD_RETRY_PATH, "POST", { id });
1237
- return { retried: body.retried === true };
1238
- }
1239
- /**
1240
- * Permanently drop a dead-letter job by id (the operator has decided not to
1241
- * recover it). Returns whether a parked record was removed. Hits the
1242
- * admin-gated `POST /_lunora/admin/scheduled/dead/cancel`.
1243
- */
1244
- async removeDeadJob(id) {
1245
- if (this.closed) {
1246
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1247
- }
1248
- const body = await this.adminFetch(SCHEDULED_DEAD_CANCEL_PATH, "POST", { id });
1249
- return { removed: body.removed === true };
1250
- }
1251
- /**
1252
- * List a workflow's instances via the admin Workflows proxy
1253
- * (`/_lunora/admin/workflows/instances`) — the Cloudflare control-plane data
1254
- * the `Workflow` binding can't expose. Requires the worker to be built with a
1255
- * `workflowsClient` (Cloudflare account id + API token). When one isn't
1256
- * configured this does NOT reject: the proxy returns a `200 { configured:
1257
- * false }` sentinel, so the result resolves with `configured === false` and an
1258
- * empty `instances` list — callers should branch on that flag rather than
1259
- * try/catch. (The instance-detail / status endpoints still reject with 501.)
1260
- * `name` is the deployed workflow name.
1261
- */
1262
- async listWorkflowInstances(options) {
1263
- if (this.closed) {
1264
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1265
- }
1266
- const query = new URLSearchParams({ name: options.name });
1267
- if (options.status !== void 0) {
1268
- query.set("status", options.status);
1269
- }
1270
- if (options.page !== void 0) {
1271
- query.set("page", String(options.page));
1272
- }
1273
- if (options.perPage !== void 0) {
1274
- query.set("perPage", String(options.perPage));
1275
- }
1276
- const body = await this.adminFetch(`${WORKFLOWS_INSTANCES_PATH}?${query.toString()}`, "GET");
1277
- return {
1278
- configured: body.configured,
1279
- instances: body.instances ?? [],
1280
- page: body.page ?? 1,
1281
- perPage: body.perPage ?? options.perPage ?? 0,
1282
- totalCount: body.totalCount
1283
- };
1284
- }
1285
- /** Read one workflow instance with its step timeline (`/_lunora/admin/workflows/instance`). */
1286
- async getWorkflowInstance(options) {
1287
- if (this.closed) {
1288
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1289
- }
1290
- const query = new URLSearchParams({ id: options.id, name: options.name });
1291
- const body = await this.adminFetch(`${WORKFLOWS_INSTANCE_PATH}?${query.toString()}`, "GET");
1292
- return {
1293
- createdOn: body.createdOn,
1294
- endedOn: body.endedOn,
1295
- error: body.error,
1296
- id: body.id ?? options.id,
1297
- output: body.output,
1298
- params: body.params,
1299
- startedOn: body.startedOn,
1300
- status: body.status ?? "unknown",
1301
- steps: body.steps ?? []
1302
- };
1303
- }
1304
- /** Pause / resume / terminate a workflow instance (`/_lunora/admin/workflows/status`). Needs an Edit-scoped Cloudflare token. */
1305
- async setWorkflowInstanceStatus(options) {
1306
- if (this.closed) {
1307
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1308
- }
1309
- const body = await this.adminFetch(WORKFLOWS_STATUS_PATH, "POST", { action: options.action, id: options.id, name: options.name });
1310
- return { status: body.status ?? "unknown" };
1311
- }
1312
- /**
1313
- * Subscribe to the live scheduled-jobs list over the SchedulerDO's admin
1314
- * WebSocket. `onJobs` fires with the full list on connect and on every
1315
- * change (schedule / cancel / alarm-fire). Reconnects with the client's
1316
- * configured backoff. Requires `wsToken` to be set to an admin credential
1317
- * (the browser can't send an `Authorization` header on a WS) — the master
1318
- * token, or preferably a {@link WsTokenProvider} minting the ephemeral
1319
- * sub-token so the master credential stays out of the URL. Returns an
1320
- * unsubscribe function that closes the socket and stops reconnecting.
1321
- */
1322
- subscribeScheduledJobs(onJobs) {
1323
- if (this.closed) {
1324
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1325
- }
1326
- if (this.WebSocketImpl === void 0) {
1327
- return () => void 0;
1328
- }
1329
- const base = joinUrl(deriveWsUrl(this.url), SCHEDULED_WS_PATH);
1330
- const reconnect = createReconnect(this.reconnectOptions);
1331
- let socket;
1332
- let timer;
1333
- let closed = false;
1334
- const openWith = (token) => {
1335
- if (closed || this.WebSocketImpl === void 0) {
1336
- return;
1337
- }
1338
- const url = token === void 0 ? base : `${base}?token=${encodeURIComponent(token)}`;
1339
- socket = new this.WebSocketImpl(url);
1340
- socket.addEventListener("open", () => {
1341
- reconnect.reset();
1342
- });
1343
- socket.addEventListener("message", (event) => {
1344
- try {
1345
- const message = JSON.parse(typeof event.data === "string" ? event.data : "");
1346
- if (message.type === "jobs" && Array.isArray(message.records)) {
1347
- onJobs(message.records);
1348
- }
1349
- } catch {
1350
- }
1351
- });
1352
- socket.addEventListener("close", () => {
1353
- socket = void 0;
1354
- if (!closed) {
1355
- timer = setTimeout(connect, reconnect.next());
1356
- }
1357
- });
1358
- socket.addEventListener("error", () => {
1359
- });
1360
- };
1361
- const connectWithProvider = async (provider) => {
1362
- let token;
1363
- try {
1364
- token = await provider();
1365
- } catch {
1366
- if (!closed) {
1367
- timer = setTimeout(connect, reconnect.next());
1368
- }
1369
- return;
1370
- }
1371
- openWith(token);
1372
- };
1373
- const connect = () => {
1374
- if (closed || this.WebSocketImpl === void 0) {
1375
- return;
1376
- }
1377
- const { wsToken } = this;
1378
- if (typeof wsToken === "function") {
1379
- connectWithProvider(wsToken).catch(() => void 0);
1380
- return;
1381
- }
1382
- openWith(wsToken);
1383
- };
1384
- connect();
1385
- return () => {
1386
- closed = true;
1387
- if (timer !== void 0) {
1388
- clearTimeout(timer);
1389
- }
1390
- socket?.close();
1391
- };
1392
- }
1393
- // --- Functions admin ----------------------------------------------------
1394
- /**
1395
- * List the registered public functions (queries / mutations / actions) with
1396
- * their kinds. Hits the admin-gated `GET /_lunora/admin/functions` endpoint —
1397
- * the worker must be built with a `functions` registry and `adminToken`, and
1398
- * this client's auth token must match. Powers `@lunora/studio`'s function
1399
- * runner auto-discovery.
1400
- */
1401
- async listFunctions() {
1402
- if (this.closed) {
1403
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1404
- }
1405
- const body = await this.adminFetch(FUNCTIONS_PATH, "GET");
1406
- return body.functions ?? [];
1407
- }
1408
- /**
1409
- * List the code-defined cron triggers (the `cronJobs()` map injected on the
1410
- * worker), each flattened to its firing `cron` expression. Hits the
1411
- * admin-gated `GET /_lunora/admin/cron-jobs` endpoint — the worker must be
1412
- * built with a `cronJobs` map and `adminToken`, and this client's auth token
1413
- * must match. These are static (Cloudflare exposes no runtime cron
1414
- * introspection), so the studio renders them read-only alongside the dynamic
1415
- * scheduler jobs.
1416
- */
1417
- async getCronJobs() {
1418
- if (this.closed) {
1419
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1420
- }
1421
- const body = await this.adminFetch(CRON_JOBS_PATH, "GET");
1422
- return body.jobs ?? [];
1423
- }
1424
- /**
1425
- * Manually fire one code-defined cron job by name — the same dispatch the
1426
- * scheduled trigger runs (dispatch the function, or start the durable
1427
- * workflow), on demand. Hits the admin-gated `POST /_lunora/admin/cron-jobs/run`
1428
- * endpoint; the worker must be built with a `cronJobs` map and `adminToken`,
1429
- * and this client's auth token must match. Resolves when the job has run (a
1430
- * function job's shard response is 2xx, or the workflow instance was created)
1431
- * and rejects with the dispatch error otherwise.
1432
- */
1433
- async runCronJob(name) {
1434
- if (this.closed) {
1435
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1436
- }
1437
- const body = await this.adminFetch(CRON_JOBS_RUN_PATH, "POST", { name });
1438
- return { name: body.name ?? name, ran: body.ran === true };
1439
- }
1440
- /**
1441
- * Fetch the generated OpenAPI 3.1 document. Hits the admin-gated
1442
- * `GET /_lunora/admin/openapi` endpoint — the worker must be built with an
1443
- * `openApiSpec` and `adminToken`, and this client's auth token must match.
1444
- * Powers `@lunora/studio`'s API-reference (Scalar) view. When the worker has
1445
- * no spec wired, the endpoint still resolves with an empty-but-valid OpenAPI
1446
- * document (no `paths`), so callers can render a "not configured" state.
1447
- */
1448
- async fetchOpenApi() {
1449
- if (this.closed) {
1450
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1451
- }
1452
- return await this.adminFetch(OPENAPI_PATH, "GET");
1453
- }
1454
- /**
1455
- * Fetch the generated OpenRPC 1.x document. Hits the admin-gated
1456
- * `GET /_lunora/admin/openrpc` endpoint — the worker must be built with an
1457
- * `openRpcSpec` and `adminToken`, and this client's auth token must match.
1458
- * OpenRPC is the RPC-native spec (a `methods` array over the JSON-RPC-shaped
1459
- * `POST /_lunora/rpc` transport); it documents the RPC functions only.
1460
- * Powers `@lunora/studio`'s OpenRPC API-reference view. When the worker has
1461
- * no spec wired, the endpoint still resolves with an empty-but-valid OpenRPC
1462
- * document (no `methods`), so callers can render a "not configured" state.
1463
- */
1464
- async fetchOpenRpc() {
1465
- if (this.closed) {
1466
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1467
- }
1468
- return await this.adminFetch(OPENRPC_PATH, "GET");
1469
- }
1470
- // --- Storage admin ------------------------------------------------------
1471
- /**
1472
- * List objects in the storage bucket, optionally under a `prefix` and from a
1473
- * pagination `cursor`. Hits the admin-gated `GET /_lunora/admin/storage`
1474
- * endpoint — the worker must be built with a `storageList` function and
1475
- * `adminToken`, and this client's auth token must match. Powers
1476
- * `@lunora/studio`'s file browser.
1477
- */
1478
- async listStorageObjects(options = {}) {
1479
- if (this.closed) {
1480
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1481
- }
1482
- const params = new URLSearchParams();
1483
- if (options.prefix !== void 0 && options.prefix !== "") {
1484
- params.set("prefix", options.prefix);
1485
- }
1486
- if (options.cursor !== void 0 && options.cursor !== "") {
1487
- params.set("cursor", options.cursor);
1488
- }
1489
- if (options.limit !== void 0) {
1490
- params.set("limit", String(options.limit));
1491
- }
1492
- if (options.bucket !== void 0 && options.bucket !== "") {
1493
- params.set("bucket", options.bucket);
1494
- }
1495
- const query = params.toString();
1496
- const path = query === "" ? STORAGE_PATH : `${STORAGE_PATH}?${query}`;
1497
- const body = await this.adminFetch(path, "GET");
1498
- return { cursor: body.cursor, objects: body.objects ?? [] };
1499
- }
1500
- /**
1501
- * Delete one object from the storage bucket by key. Hits the admin-gated
1502
- * `DELETE /_lunora/admin/storage?key=…` endpoint — the worker must be built
1503
- * with a `storageDelete` function and `adminToken`. Powers the studio file
1504
- * browser's per-row delete; resolves `{ deleted, key }`.
1505
- */
1506
- async deleteStorageObject(key, options) {
1507
- if (this.closed) {
1508
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1509
- }
1510
- const path = `${STORAGE_PATH}?key=${encodeURIComponent(key)}${bucketQuery(options?.bucket)}`;
1511
- const body = await this.adminFetch(path, "DELETE");
1512
- return { deleted: body.deleted ?? true, key: body.key ?? key };
1513
- }
1514
- /**
1515
- * List the storage bucket names the worker exposes, for the studio file
1516
- * browser's bucket picker. Hits the admin-gated
1517
- * `GET /_lunora/admin/storage/buckets` endpoint — always resolves (an empty
1518
- * array when the worker configures no `storageBuckets`, i.e. single-bucket).
1519
- */
1520
- async listStorageBuckets() {
1521
- if (this.closed) {
1522
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1523
- }
1524
- const body = await this.adminFetch(STORAGE_BUCKETS_PATH, "GET");
1525
- return body.buckets ?? [];
1526
- }
1527
- /**
1528
- * Upload one object to the storage bucket. Hits the admin-gated
1529
- * `PUT /_lunora/admin/storage?key=…` endpoint with the raw body and an
1530
- * optional `contentType` header — the worker must be built with a
1531
- * `storageUpload` function and `adminToken`. Powers the studio file
1532
- * browser's upload control; resolves `{ etag?, key }`.
1533
- */
1534
- async uploadStorageObject(options) {
1535
- if (this.closed) {
1536
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1537
- }
1538
- const path = `${STORAGE_PATH}?key=${encodeURIComponent(options.key)}${bucketQuery(options.bucket)}`;
1539
- const body = await this.adminFetch(path, "PUT", options.body, options.contentType);
1540
- return { etag: body.etag, key: body.key ?? options.key };
1541
- }
1542
- /**
1543
- * Build a (signed or public) URL for one object. Hits the admin-gated
1544
- * `GET /_lunora/admin/storage/url?key=…` endpoint — the worker must be built
1545
- * with a `storageSignedUrl` function and `adminToken`. Powers the studio
1546
- * file browser's copy-URL action; resolves the URL string.
1547
- *
1548
- * `options.expiresInSeconds` requests a share-link lifetime, which is
1549
- * validated/clamped server-side. The options object mirrors the worker's
1550
- * `StorageSignedUrlFunction` options (a `password` / download-limit are noted
1551
- * as future fields there).
1552
- */
1553
- async signedStorageUrl(key, options) {
1554
- if (this.closed) {
1555
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1556
- }
1557
- const expiresInSeconds = options?.expiresInSeconds;
1558
- const expiryQuery = expiresInSeconds === void 0 ? "" : `&expiresIn=${encodeURIComponent(expiresInSeconds.toString())}`;
1559
- const path = `${STORAGE_URL_PATH}?key=${encodeURIComponent(key)}${expiryQuery}${bucketQuery(options?.bucket)}`;
1560
- const body = await this.adminFetch(path, "GET");
1561
- if (typeof body.url !== "string") {
1562
- throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");
1563
- }
1564
- return body.url;
1565
- }
1566
- // --- Global (D1) tables admin -------------------------------------------
1567
- /**
1568
- * List the `.global()` (D1-backed) tables with their row counts. Hits the
1569
- * admin-gated `GET /_lunora/admin/global/tables` endpoint — the worker must
1570
- * be built with a `globalIntrospector` and `adminToken`. Powers the data
1571
- * browser's global mode.
1572
- */
1573
- async listGlobalTables() {
1574
- if (this.closed) {
1575
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1576
- }
1577
- return await this.adminFetch(GLOBAL_TABLES_PATH, "GET");
1578
- }
1579
- /**
1580
- * Read a page of rows from one `.global()` table. `filters` AND-narrows the
1581
- * page to rows matching each `column = value` eq constraint — the drill-down a
1582
- * facet-value click applies; the array is JSON-encoded into the `filters`
1583
- * query param and the values are bound server-side.
1584
- */
1585
- async readGlobalTablePage(options) {
1586
- if (this.closed) {
1587
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1588
- }
1589
- const params = new URLSearchParams({ table: options.table });
1590
- if (options.limit !== void 0) {
1591
- params.set("limit", String(options.limit));
1592
- }
1593
- if (options.offset !== void 0) {
1594
- params.set("offset", String(options.offset));
1595
- }
1596
- if (options.filters !== void 0 && options.filters.length > 0) {
1597
- params.set("filters", JSON.stringify(options.filters));
1598
- }
1599
- return await this.adminFetch(`${GLOBAL_TABLE_PATH}?${params.toString()}`, "GET");
1600
- }
1601
- /**
1602
- * Summarise the distinct values of one column in a `.global()` table over the
1603
- * active view (the same eq `filters` the browser is previewing) — the global
1604
- * twin of the shard browser's facet. Hits the admin-gated
1605
- * `GET /_lunora/admin/global/facet` endpoint; `column` is validated + bound
1606
- * server-side. Powers the global data browser's facet sidebar.
1607
- */
1608
- async facetGlobalColumn(options) {
1609
- if (this.closed) {
1610
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1611
- }
1612
- const params = new URLSearchParams({ column: options.column, table: options.table });
1613
- if (options.limit !== void 0) {
1614
- params.set("limit", String(options.limit));
1615
- }
1616
- if (options.filters !== void 0 && options.filters.length > 0) {
1617
- params.set("filters", JSON.stringify(options.filters));
1618
- }
1619
- return await this.adminFetch(`${GLOBAL_FACET_PATH}?${params.toString()}`, "GET");
1620
- }
1621
- // --- Vector indexes admin -----------------------------------------------
1622
- /**
1623
- * List the schema's Vectorize indexes with their declared shape (table,
1624
- * field, dimensions, metric, metadata) and live stats (vector count,
1625
- * processing watermark) when the binding is reachable. Hits the admin-gated
1626
- * `GET /_lunora/admin/vector/indexes` endpoint — the worker must be built
1627
- * with a `vectorIntrospector` and `adminToken`. Powers the studio's vector
1628
- * browser. Vectorize can't enumerate indexes at runtime, so this list comes
1629
- * from the generated `LUNORA_VECTOR_INDEXES` registry.
1630
- */
1631
- async listVectorIndexes() {
1632
- if (this.closed) {
1633
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1634
- }
1635
- const body = await this.adminFetch(VECTOR_INDEXES_PATH, "GET");
1636
- return body.indexes ?? [];
1637
- }
1638
- /**
1639
- * Run a nearest-neighbour similarity query against one vector index: the
1640
- * worker embeds `text` via the index's embedder and returns the top matches.
1641
- * Hits the admin-gated `POST /_lunora/admin/vector/query` endpoint. Throws
1642
- * `VECTOR_QUERY_UNSUPPORTED` when the worker's introspector has no embedder
1643
- * wired (the index lists read-only).
1644
- */
1645
- async queryVectorIndex(options) {
1646
- if (this.closed) {
1647
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1648
- }
1649
- const body = await this.adminFetch(VECTOR_QUERY_PATH, "POST", options);
1650
- return body.matches ?? [];
1651
- }
1652
- // --- KV namespace admin -------------------------------------------------
1653
- /**
1654
- * List the worker's registered Workers KV namespaces (binding names). Hits
1655
- * the admin-gated `GET /_lunora/admin/kv/namespaces` endpoint — the worker
1656
- * must be built with a `kvIntrospector` and `adminToken`. Powers the
1657
- * studio's KV browser.
1658
- */
1659
- async listKvNamespaces() {
1660
- if (this.closed) {
1661
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1662
- }
1663
- const body = await this.adminFetch(KV_NAMESPACES_PATH, "GET");
1664
- return body.namespaces ?? [];
1665
- }
1666
- /**
1667
- * List keys in a KV namespace, optionally filtered by `prefix` and
1668
- * paginated via `cursor`. Hits the admin-gated
1669
- * `GET /_lunora/admin/kv/keys` endpoint.
1670
- */
1671
- async listKvKeys(options) {
1672
- if (this.closed) {
1673
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1674
- }
1675
- const path = withQuery(KV_KEYS_PATH, {
1676
- cursor: options.cursor,
1677
- limit: options.limit,
1678
- namespace: options.namespace,
1679
- prefix: options.prefix
1680
- });
1681
- return await this.adminFetch(path, "GET");
1682
- }
1683
- /**
1684
- * Read a KV value (as text) and its metadata. Hits the admin-gated
1685
- * `GET /_lunora/admin/kv/value` endpoint. Returns `{ value: null, metadata: null }`
1686
- * when the key is absent.
1687
- */
1688
- async getKvValue(options) {
1689
- if (this.closed) {
1690
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1691
- }
1692
- const path = withQuery(KV_VALUE_PATH, { key: options.key, namespace: options.namespace });
1693
- return await this.adminFetch(path, "GET");
1694
- }
1695
- /**
1696
- * Write a string value to a KV namespace. Accepts an absolute `expiration`
1697
- * (Unix seconds) or a relative `expirationTtl`, plus optional `metadata` —
1698
- * re-send the loaded values on edit so a save preserves rather than clears
1699
- * them. Hits the admin-gated `PUT /_lunora/admin/kv/value` endpoint.
1700
- */
1701
- async putKvValue(options) {
1702
- if (this.closed) {
1703
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1704
- }
1705
- await this.adminFetch(KV_VALUE_PATH, "PUT", options);
1706
- }
1707
- /**
1708
- * Delete a key from a KV namespace. No-op when the key is absent. Hits the
1709
- * admin-gated `DELETE /_lunora/admin/kv/value` endpoint.
1710
- */
1711
- async deleteKvKey(options) {
1712
- if (this.closed) {
1713
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1714
- }
1715
- const path = withQuery(KV_VALUE_PATH, { key: options.key, namespace: options.namespace });
1716
- await this.adminFetch(path, "DELETE");
1717
- }
1718
- // --- Auth admin ---------------------------------------------------------
1719
- /**
1720
- * List authenticated users, paged and optionally searched / filtered / sorted.
1721
- * Hits the admin-gated `GET /_lunora/admin/auth/users` endpoint — the worker
1722
- * must be built with an `authAdmin` and `adminToken`. Powers the studio's
1723
- * users dashboard.
1724
- */
1725
- async listAuthUsers(options = {}) {
1726
- if (this.closed) {
1727
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1728
- }
1729
- const path = withQuery(AUTH_USERS_PATH, {
1730
- filterField: options.filterField,
1731
- filterValue: options.filterValue,
1732
- limit: options.limit,
1733
- offset: options.offset,
1734
- search: options.search,
1735
- searchField: options.searchField,
1736
- sortBy: options.sortBy,
1737
- sortDirection: options.sortDirection
1738
- });
1739
- return await this.adminFetch(path, "GET");
1740
- }
1741
- /**
1742
- * Create a user. Hits the admin-gated `POST /_lunora/admin/auth/users/create`
1743
- * endpoint (requires the worker's `authAdmin` to implement `createUser`).
1744
- * `data` carries any app-defined `user.additionalFields`.
1745
- */
1746
- async createAuthUser(input) {
1747
- return await this.adminFetch(AUTH_CREATE_USER_PATH, "POST", input);
1748
- }
1749
- /** Set a user's role (string, or array joined comma-wise server-side). */
1750
- async setAuthUserRole(input) {
1751
- return await this.adminFetch(AUTH_SET_ROLE_PATH, "POST", input);
1752
- }
1753
- /** Ban a user. `expiresInSeconds` sets a temporary ban; omit it for a permanent one. Revokes the user's live sessions. */
1754
- async banAuthUser(input) {
1755
- return await this.adminFetch(AUTH_BAN_PATH, "POST", input);
1756
- }
1757
- /** Lift a user's ban. */
1758
- async unbanAuthUser(input) {
1759
- return await this.adminFetch(AUTH_UNBAN_PATH, "POST", input);
1760
- }
1761
- /** Set a user's password (admin override — no current-password challenge). */
1762
- async setAuthUserPassword(input) {
1763
- await this.adminFetch(AUTH_SET_PASSWORD_PATH, "POST", input);
1764
- }
1765
- /** Permanently delete a user and revoke their sessions. */
1766
- async removeAuthUser(input) {
1767
- await this.adminFetch(AUTH_REMOVE_USER_PATH, "POST", input);
1768
- }
1769
- /**
1770
- * Mint an impersonation session for a user, returning its bearer `token`.
1771
- * The caller is responsible for using the token (e.g. setting the session
1772
- * cookie); the server performs no cookie round-trip.
1773
- */
1774
- async impersonateAuthUser(input) {
1775
- return await this.adminFetch(AUTH_IMPERSONATE_PATH, "POST", input);
1776
- }
1777
- /** Revoke a single session by its id (force sign-out of one device). */
1778
- async revokeAuthSession(input) {
1779
- await this.adminFetch(AUTH_REVOKE_SESSION_PATH, "POST", input);
1780
- }
1781
- /** Revoke every session for a user (force sign-out everywhere). */
1782
- async revokeAuthUserSessions(input) {
1783
- await this.adminFetch(AUTH_REVOKE_SESSIONS_PATH, "POST", input);
1784
- }
1785
- /**
1786
- * Report which auth dashboard surfaces are available — derived server-side
1787
- * from the enabled better-auth plugins. The studio renders only the panels
1788
- * whose capability is `true`.
1789
- */
1790
- async getAuthCapabilities() {
1791
- return await this.adminFetch(AUTH_CAPABILITIES_PATH, "GET");
1792
- }
1793
- /** Update a user's fields (name/email/app-defined `additionalFields`). */
1794
- async updateAuthUser(input) {
1795
- return await this.adminFetch(AUTH_UPDATE_USER_PATH, "POST", input);
1796
- }
1797
- /** List a user's linked accounts (credential / OAuth providers). Token material is stripped server-side. */
1798
- async listAuthAccounts(input) {
1799
- return await this.adminFetch(withQuery(AUTH_ACCOUNTS_PATH, { userId: input.userId }), "GET");
1800
- }
1801
- /** Unlink a linked account from a user. */
1802
- async unlinkAuthAccount(input) {
1803
- await this.adminFetch(AUTH_UNLINK_ACCOUNT_PATH, "POST", input);
1804
- }
1805
- /** List a user's registered passkeys (requires the passkey plugin). */
1806
- async listAuthPasskeys(input) {
1807
- return await this.adminFetch(withQuery(AUTH_PASSKEYS_PATH, { userId: input.userId }), "GET");
1808
- }
1809
- /** Delete a passkey by id (requires the passkey plugin). */
1810
- async deleteAuthPasskey(input) {
1811
- await this.adminFetch(AUTH_DELETE_PASSKEY_PATH, "POST", input);
1812
- }
1813
- /** Disable two-factor auth for a user (requires the two-factor plugin). */
1814
- async disableAuthTwoFactor(input) {
1815
- await this.adminFetch(AUTH_DISABLE_2FA_PATH, "POST", input);
1816
- }
1817
- /** List organizations, paged (requires the organization plugin). */
1818
- async listAuthOrganizations(options = {}) {
1819
- return await this.adminFetch(withQuery(AUTH_ORGS_PATH, { limit: options.limit, offset: options.offset }), "GET");
1820
- }
1821
- /** List the members of an organization (requires the organization plugin). */
1822
- async listAuthOrgMembers(input) {
1823
- const path = withQuery(AUTH_ORG_MEMBERS_PATH, { limit: input.limit, offset: input.offset, organizationId: input.organizationId });
1824
- return await this.adminFetch(path, "GET");
1825
- }
1826
- /** List an organization's pending invitations (requires the organization plugin). */
1827
- async listAuthOrgInvitations(input) {
1828
- const path = withQuery(AUTH_ORG_INVITATIONS_PATH, { limit: input.limit, offset: input.offset, organizationId: input.organizationId });
1829
- return await this.adminFetch(path, "GET");
1830
- }
1831
- /** Remove a member from an organization. */
1832
- async removeAuthOrgMember(input) {
1833
- await this.adminFetch(AUTH_REMOVE_MEMBER_PATH, "POST", input);
1834
- }
1835
- /** Cancel a pending organization invitation. */
1836
- async cancelAuthOrgInvitation(input) {
1837
- await this.adminFetch(AUTH_CANCEL_INVITATION_PATH, "POST", input);
1838
- }
1839
- /**
1840
- * Report the deployment's auth configuration — enabled plugins, sign-in
1841
- * methods, user-settable create-user fields, organization sub-features
1842
- * (teams / roles), and session / rate-limit policy. Drives the config panel
1843
- * and the dynamic create-user form. Never carries a secret.
1844
- */
1845
- async getAuthConfig() {
1846
- return await this.adminFetch(AUTH_CONFIG_PATH, "GET");
1847
- }
1848
- /** Create an organization; optionally seed an `owner` member for `ownerId`. */
1849
- async createAuthOrganization(input) {
1850
- return await this.adminFetch(AUTH_CREATE_ORG_PATH, "POST", input);
1851
- }
1852
- /** Update an organization's name/slug/logo/metadata. */
1853
- async updateAuthOrganization(input) {
1854
- return await this.adminFetch(AUTH_UPDATE_ORG_PATH, "POST", input);
1855
- }
1856
- /** Delete an organization and cascade its members, invitations, teams, and custom roles. */
1857
- async deleteAuthOrganization(input) {
1858
- await this.adminFetch(AUTH_REMOVE_ORG_PATH, "POST", input);
1859
- }
1860
- /** Directly add an existing user to an organization (no invitation/acceptance). */
1861
- async addAuthOrgMember(input) {
1862
- return await this.adminFetch(AUTH_ADD_MEMBER_PATH, "POST", input);
1863
- }
1864
- /** Create a pending email invitation to an organization. */
1865
- async inviteAuthOrgMember(input) {
1866
- return await this.adminFetch(AUTH_INVITE_MEMBER_PATH, "POST", input);
1867
- }
1868
- /** Change a member's role. */
1869
- async setAuthOrgMemberRole(input) {
1870
- return await this.adminFetch(AUTH_MEMBER_ROLE_PATH, "POST", input);
1871
- }
1872
- /** List an organization's teams (requires the organization plugin with teams enabled). */
1873
- async listAuthOrgTeams(input) {
1874
- const path = withQuery(AUTH_ORG_TEAMS_PATH, { limit: input.limit, offset: input.offset, organizationId: input.organizationId });
1875
- return await this.adminFetch(path, "GET");
1876
- }
1877
- /** Create a team under an organization. */
1878
- async createAuthOrgTeam(input) {
1879
- return await this.adminFetch(AUTH_CREATE_TEAM_PATH, "POST", input);
1880
- }
1881
- /** Rename a team. */
1882
- async updateAuthOrgTeam(input) {
1883
- return await this.adminFetch(AUTH_UPDATE_TEAM_PATH, "POST", input);
1884
- }
1885
- /** Delete a team and its memberships. */
1886
- async removeAuthOrgTeam(input) {
1887
- await this.adminFetch(AUTH_REMOVE_TEAM_PATH, "POST", input);
1888
- }
1889
- /** List a team's members. */
1890
- async listAuthOrgTeamMembers(input) {
1891
- const path = withQuery(AUTH_ORG_TEAM_MEMBERS_PATH, { limit: input.limit, offset: input.offset, teamId: input.teamId });
1892
- return await this.adminFetch(path, "GET");
1893
- }
1894
- /** Add a user to a team. */
1895
- async addAuthOrgTeamMember(input) {
1896
- return await this.adminFetch(AUTH_ADD_TEAM_MEMBER_PATH, "POST", input);
1897
- }
1898
- /** Remove a member from a team. */
1899
- async removeAuthOrgTeamMember(input) {
1900
- await this.adminFetch(AUTH_REMOVE_TEAM_MEMBER_PATH, "POST", input);
1901
- }
1902
- /** List an organization's custom roles (requires the organization plugin with dynamic access control). */
1903
- async listAuthOrgRoles(input) {
1904
- const path = withQuery(AUTH_ORG_ROLES_PATH, { limit: input.limit, offset: input.offset, organizationId: input.organizationId });
1905
- return await this.adminFetch(path, "GET");
1906
- }
1907
- /** Create a custom org role with a permission grant (a `resource -> actions[]` map). */
1908
- async createAuthOrgRole(input) {
1909
- return await this.adminFetch(AUTH_CREATE_ROLE_PATH, "POST", input);
1910
- }
1911
- /** Replace a custom org role's permission grant. */
1912
- async updateAuthOrgRole(input) {
1913
- return await this.adminFetch(AUTH_UPDATE_ROLE_PATH, "POST", input);
1914
- }
1915
- /** Delete a custom org role. */
1916
- async deleteAuthOrgRole(input) {
1917
- await this.adminFetch(AUTH_REMOVE_ROLE_PATH, "POST", input);
1918
- }
1919
- /** List auth sessions, paged and optionally filtered to one user. */
1920
- async listAuthSessions(options = {}) {
1921
- if (this.closed) {
1922
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1923
- }
1924
- const params = new URLSearchParams();
1925
- if (options.userId !== void 0 && options.userId !== "") {
1926
- params.set("userId", options.userId);
1927
- }
1928
- if (options.limit !== void 0) {
1929
- params.set("limit", String(options.limit));
1930
- }
1931
- if (options.offset !== void 0) {
1932
- params.set("offset", String(options.offset));
1933
- }
1934
- const query = params.toString();
1935
- return await this.adminFetch(query === "" ? AUTH_SESSIONS_PATH : `${AUTH_SESSIONS_PATH}?${query}`, "GET");
1936
- }
1937
- // --- Subscriptions ------------------------------------------------------
1938
- subscribe(function_, args, callback, options = {}) {
1939
- if (this.closed) {
1940
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
1941
- }
1942
- const argsRecord = args ?? {};
1943
- const key = SubscriptionRegistry.key(function_.__lunoraRef, argsRecord, options.shardKey);
1944
- let state = this.subscriptions.get(key);
1945
- const subscriptionCallback = callback;
1946
- const errorCallback = options.onError;
1947
- if (!state) {
1948
- this.nextSubId += 1;
1949
- const id = `sub_${this.nextSubId.toString()}`;
1950
- const argsKey = stableWireKey(argsRecord);
1951
- const cached = this.takeHydratedCache(function_.__lunoraRef, argsKey, options.shardKey);
1952
- state = {
1953
- acked: false,
1954
- args: argsRecord,
1955
- argsKey,
1956
- callbacks: /* @__PURE__ */ new Set(),
1957
- checkpointCallbacks: /* @__PURE__ */ new Set(),
1958
- errorCallbacks: /* @__PURE__ */ new Set(),
1959
- fn: function_,
1960
- id,
1961
- lastValue: cached?.value,
1962
- optimisticLayers: [],
1963
- serverBase: cached?.value,
1964
- serverCursor: cached?.serverCursor,
1965
- shardKey: options.shardKey,
1966
- ...cached?.serverEpoch === void 0 ? {} : { serverEpoch: cached.serverEpoch }
1967
- };
1968
- this.subscriptions.add(state);
1969
- }
1970
- state.callbacks.add(subscriptionCallback);
1971
- if (errorCallback) {
1972
- state.errorCallbacks.add(errorCallback);
1973
- }
1974
- if (options.onCheckpoint) {
1975
- state.checkpointCallbacks.add(options.onCheckpoint);
1976
- }
1977
- if (state.lastValue !== void 0) {
1978
- try {
1979
- subscriptionCallback(state.lastValue);
1980
- } catch {
1981
- }
1982
- }
1983
- this.ensureSocket(options.shardKey);
1984
- this.sendSubscribeIfOpen(state);
1985
- const subscriptionState = state;
1986
- return () => {
1987
- subscriptionState.callbacks.delete(subscriptionCallback);
1988
- if (errorCallback) {
1989
- subscriptionState.errorCallbacks.delete(errorCallback);
1990
- }
1991
- if (options.onCheckpoint) {
1992
- subscriptionState.checkpointCallbacks.delete(options.onCheckpoint);
1993
- }
1994
- if (subscriptionState.callbacks.size === 0) {
1995
- const conn = this.getConnection(subscriptionState.shardKey);
1996
- const ok = conn ? sendOn(conn, { id: subscriptionState.id, type: "unsubscribe" }) : false;
1997
- if (!ok && conn) {
1998
- conn.pendingUnsubscribes.push({ id: subscriptionState.id, type: "unsubscribe" });
1999
- }
2000
- this.subscriptions.remove(subscriptionState);
2001
- }
2002
- };
2003
- }
2004
- /**
2005
- * Subscribe to a declarative **shape** — server-side partial replication
2006
- * scoped by `shardBy` + the shape's predicate + RLS. The parallel to
2007
- * {@link subscribe} for the poke protocol: the client sends the shape *name* +
2008
- * validated `args` (never a `where` the client could forge), the server seeds
2009
- * the current membership as an insert-poke and streams live membership diffs.
2010
- * Each applied poke materializes the shape's rowset and invokes `callback`.
2011
- *
2012
- * Unlike {@link subscribe}, shape subscriptions are NOT deduped by
2013
- * (name, args): the server resolves them under the socket's verified identity,
2014
- * so every call gets its own id + view. The returned function unsubscribes.
2015
- */
2016
- subscribeShape(shape, callback, options = {}) {
2017
- if (this.closed) {
2018
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
2019
- }
2020
- this.nextShapeId += 1;
2021
- const id = `shape_${this.nextShapeId.toString()}`;
2022
- const state = {
2023
- args: shape.args,
2024
- callbacks: /* @__PURE__ */ new Set([callback]),
2025
- errorCallbacks: options.onError ? /* @__PURE__ */ new Set([options.onError]) : /* @__PURE__ */ new Set(),
2026
- id,
2027
- name: shape.name,
2028
- onCheckpoint: options.onCheckpoint,
2029
- rows: /* @__PURE__ */ new Map(),
2030
- shardKey: options.shardKey,
2031
- // Encode ONCE, here, so an unsupported arg value throws at this call
2032
- // site instead of inside a reconnect's open handler.
2033
- wireArgs: shape.args === void 0 ? void 0 : encodeCallArgs(shape.args, `shape args for '${shape.name}'`)
2034
- };
2035
- this.shapeSubscriptions.set(id, state);
2036
- this.ensureSocket(options.shardKey);
2037
- this.sendShapeSubscribeIfOpen(state);
2038
- return () => {
2039
- this.shapeSubscriptions.delete(id);
2040
- const conn = this.getConnection(state.shardKey);
2041
- const ok = conn ? sendOn(conn, { id, type: "shape_unsubscribe" }) : false;
2042
- if (!ok && conn) {
2043
- conn.pendingUnsubscribes.push({ id, type: "shape_unsubscribe" });
2044
- }
2045
- };
2046
- }
2047
- /**
2048
- * Open a streaming query. The function reference must be a
2049
- * `kind:"stream"` registration (built with `c.query.input(...).stream(...)`);
2050
- * the type constraint catches accidental use of a query/mutation/action
2051
- * reference at compile time. The returned iterable yields one element per
2052
- * chunk frame the server pushes, terminating when the server sends
2053
- * `complete` or the consumer calls `.cancel()`. Errors arrive as a
2054
- * rejection on the next `next()`.
2055
- *
2056
- * Streams ride the same WS as subscriptions and share the unsubscribe
2057
- * channel: cancelling sends `{type:"unsubscribe", id}` with the stream id,
2058
- * which the DO recognises as an abort signal for the in-flight iterator.
2059
- *
2060
- * Stream-start frames buffered while the socket is (re)connecting are
2061
- * capped at {@link MAX_PENDING_STREAMS} per connection — overflowing the
2062
- * cap drops the oldest queued frame (and fails its consumer) so a stuck
2063
- * reconnect can't OOM the page.
2064
- */
2065
- stream(function_, args, options = {}) {
2066
- if (this.closed) {
2067
- throw new LunoraError("INTERNAL", "LunoraClient is closed");
2068
- }
2069
- if (this.WebSocketImpl === void 0) {
2070
- throw new LunoraError("INTERNAL", "LunoraClient: streams require a WebSocket implementation");
2071
- }
2072
- this.nextStreamId += 1;
2073
- const id = `stream_${this.nextStreamId.toString()}`;
2074
- const { shardKey } = options;
2075
- const argsRecord = args ?? {};
2076
- const { handle, iterable } = createStream({
2077
- maxBuffer: options.maxBuffer,
2078
- onCancel: () => {
2079
- const conn2 = this.getConnection(shardKey);
2080
- if (conn2) {
2081
- sendOn(conn2, { id, type: "unsubscribe" });
2082
- }
2083
- this.streams.delete(id);
2084
- }
2085
- });
2086
- this.streams.set(id, { handle, shardKey });
2087
- this.ensureSocket(shardKey);
2088
- const conn = this.getConnection(shardKey);
2089
- const message = {
2090
- id,
2091
- // Wire-encode the stream args so `bigint`/bytes survive the send (raw
2092
- // `JSON.stringify` throws on a bigint); the shard `decodeWire`s them
2093
- // before invoking the stream handler.
2094
- query: {
2095
- args: encodeCallArgs(argsRecord, `stream args for '${function_.__lunoraRef}'`),
2096
- functionPath: function_.__lunoraRef,
2097
- shardKey
2098
- },
2099
- type: "stream"
2100
- };
2101
- const sentImmediately = conn?.wsState === "open" && sendOn(conn, message);
2102
- if (!sentImmediately && conn) {
2103
- conn.pendingStreams = conn.pendingStreams ?? [];
2104
- while (conn.pendingStreams.length >= MAX_PENDING_STREAMS) {
2105
- const dropped = conn.pendingStreams.shift();
2106
- const droppedId = dropped?.id;
2107
- const droppedStream = droppedId ? this.streams.get(droppedId) : void 0;
2108
- if (droppedStream) {
2109
- droppedStream.handle.fail(new LunoraError("STREAM_QUEUE_OVERFLOW", "stream-start frame evicted while socket was unreachable"));
2110
- this.streams.delete(droppedId);
2111
- }
2112
- }
2113
- conn.pendingStreams.push(message);
2114
- }
2115
- return iterable;
2116
- }
2117
- /**
2118
- * Open a typed **HTTP-SSE route stream** (`httpRoute.&lt;verb>(path).stream()`).
2119
- * Distinct from {@link LunoraClient.stream}, which consumes the WS procedure
2120
- * stream (`kind: "stream"`): this one opens the route's own URL with `fetch`
2121
- * and parses the Server-Sent Events framing the route pump writes (`data:`
2122
- * chunks, a final `event: complete`, an `event: error` on throw).
2123
- *
2124
- * The reference comes from the generated `httpStreams.*` registry, so the
2125
- * yielded chunk type is the route handler's yielded type. Cancelling the
2126
- * returned iterable (or aborting `options.signal`) aborts the fetch, which
2127
- * the server handler observes via its `signal`. The client's bearer token
2128
- * (when set) rides as an `authorization` header.
2129
- * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
2130
- */
2131
- httpStream(route, args, options = {}) {
2132
- if (this.closed) {
2133
- throw new LunoraError("CLIENT_CLOSED", "LunoraClient is closed");
2134
- }
2135
- if (!this.fetchImpl) {
2136
- throw new LunoraError("INTERNAL", "LunoraClient: no `fetch` implementation available");
2137
- }
2138
- const headers = {
2139
- ...this.authToken ? { authorization: `Bearer ${this.authToken}` } : {},
2140
- ...options.headers
2141
- };
2142
- return httpStream(route, args, {
2143
- baseUrl: this.url,
2144
- fetch: this.fetchImpl,
2145
- headers,
2146
- maxBuffer: options.maxBuffer,
2147
- signal: options.signal
2148
- });
2149
- }
2150
- close() {
2151
- this.closed = true;
2152
- this.outboxLeaderRelease?.();
2153
- this.outboxLeaderRelease = void 0;
2154
- for (const stream of this.streams.values()) {
2155
- stream.handle.fail(new LunoraError("CLIENT_CLOSED", "LunoraClient closed"));
2156
- }
2157
- this.streams.clear();
2158
- for (const conn of this.connections.values()) {
2159
- if (conn.reconnectTimer !== void 0) {
2160
- clearTimeout(conn.reconnectTimer);
2161
- conn.reconnectTimer = void 0;
2162
- }
2163
- if (conn.connectTimer !== void 0) {
2164
- clearTimeout(conn.connectTimer);
2165
- conn.connectTimer = void 0;
2166
- }
2167
- this.stopHeartbeat(conn);
2168
- if (conn.socket) {
2169
- try {
2170
- conn.socket.close();
2171
- } catch {
2172
- }
2173
- conn.socket = void 0;
2174
- }
2175
- conn.wsState = "closed";
2176
- }
2177
- this.offlineQueue.clear();
2178
- this.queuedIdentities.clear();
2179
- if (this.cacheFlushTimer !== void 0) {
2180
- clearTimeout(this.cacheFlushTimer);
2181
- this.cacheFlushTimer = void 0;
2182
- }
2183
- if (this.pendingCacheWrites.size > 0) {
2184
- this.flushQueryCacheWrites().catch(() => void 0);
2185
- }
2186
- this.authTokenListeners.clear();
2187
- this.statusListeners.clear();
2188
- this.tokenExpiredListeners.clear();
2189
- this.mutationSettledListeners.clear();
2190
- this.pendingChangeListeners.clear();
2191
- this.whisperHandlers.clear();
2192
- this.shapeSubscriptions.clear();
2193
- this.pokeBuffers.clear();
2194
- this.tabCoordinator?.stop();
2195
- this.tabCoordinator = void 0;
2196
- }
2197
- // --- Internals ----------------------------------------------------------
2198
- /**
2199
- * Persist a mutation that can't go out on the wire right now (offline, or
2200
- * mid-reconnect after a prior connect). The optimistic update has already
2201
- * been applied by `mutation`; this only chooses the durable write path and
2202
- * rolls the optimistic write back if persistence is rejected.
2203
- *
2204
- * Two paths: when an `outbox` sink is wired (the `@lunora/db` executor) it
2205
- * owns persistence + at-least-once replay, so we delegate and return
2206
- * optimistically (confirmation rides the synced view). Otherwise the
2207
- * built-in `OfflineQueue` resolves/rejects the returned promise on replay.
2208
- */
2209
- async enqueueOfflineMutation(function_, argsRecord, shardKey, mutationId, optimisticRollbacks, optimisticConfirms, precondition) {
2210
- const issuingIdentity = this.identityFingerprint();
2211
- if (this.outbox) {
2212
- this.outboxMutationCounter += 1;
2213
- const outboxMutationId = this.outboxMutationCounter;
2214
- try {
2215
- await this.outbox.enqueue({
2216
- args: argsRecord,
2217
- clientId: this.clientId,
2218
- functionPath: function_.__lunoraRef,
2219
- idempotencyKey: `${this.clientId}:${String(outboxMutationId)}`,
2220
- identity: issuingIdentity,
2221
- mutationId: outboxMutationId,
2222
- shardKey
2223
- });
2224
- } catch (error) {
2225
- rollbackOptimistic(optimisticRollbacks);
2226
- throw error instanceof Error ? error : new Error(String(error));
2227
- }
2228
- for (const confirm of optimisticConfirms) {
2229
- confirm(void 0);
2230
- }
2231
- return void 0;
2232
- }
2233
- return new Promise((resolve, reject) => {
2234
- const entry = {
2235
- args: argsRecord,
2236
- functionPath: function_.__lunoraRef,
2237
- // A live caller is awaiting this Promise, so a terminal verdict
2238
- // reaches them directly; the observer event carries
2239
- // `hadAwaiter: true`. Hydrated replays leave this unset.
2240
- liveAwaiter: true,
2241
- // Reuse the call's idempotency key as the queue id so the replay
2242
- // carries the same `x-lunora-mutation-id` the server dedups on.
2243
- id: mutationId,
2244
- // Persist the stamp alongside the record so a hydrated write can
2245
- // only replay under the identity that queued it.
2246
- identity: issuingIdentity,
2247
- // Optional precondition checked before replay — see drainConflict.
2248
- precondition,
2249
- // Confirm the per-call optimistic layer(s) against the commit cursor
2250
- // the flush replay echoes (see flushOfflineQueue).
2251
- onCommit: (commitCursor) => {
2252
- for (const confirm of optimisticConfirms) {
2253
- confirm(commitCursor);
2254
- }
2255
- },
2256
- reject: (error) => {
2257
- this.queuedIdentities.delete(mutationId);
2258
- rollbackOptimistic(optimisticRollbacks);
2259
- reject(error instanceof Error ? error : new Error(String(error)));
2260
- },
2261
- resolve,
2262
- shardKey
2263
- };
2264
- this.offlineQueue.enqueue(entry);
2265
- if (entry.id !== void 0) {
2266
- this.queuedIdentities.set(entry.id, issuingIdentity);
2267
- }
2268
- });
2269
- }
2270
- /**
2271
- * Restore offline mutations persisted in a prior session and open a socket
2272
- * for each shard they target so they flush once the WS reconnects. Failures
2273
- * are swallowed — a broken durable store must not stop the client booting.
2274
- */
2275
- async hydratePersistedQueue() {
2276
- try {
2277
- const shardKeys = await this.offlineQueue.hydrate();
2278
- for (const shardKey of shardKeys) {
2279
- this.ensureSocket(shardKey);
2280
- }
2281
- } catch {
2282
- }
2283
- }
2284
- /**
2285
- * Re-queue the durable offline writes — but only as the multi-tab LEADER. The
2286
- * persisted queue is shared across a profile's tabs; without coordination
2287
- * every tab would re-queue and replay the same writes (correct only because
2288
- * the server dedups by idempotency key, but wasteful + racy). A Web Lock makes
2289
- * exactly one tab hydrate; it holds the lock for its lifetime, so when it
2290
- * closes another tab acquires the lock and takes over. Falls back to
2291
- * unconditional hydration where Web Locks are unavailable (React Native, older
2292
- * browsers, SSR) — single-context there, so no coordination is needed.
2293
- */
2294
- hydrateAsOutboxLeader() {
2295
- const hydrate = () => {
2296
- this.hydratePersistedQueue().catch(() => void 0);
2297
- };
2298
- const locks = globalThis.navigator?.locks;
2299
- if (!locks) {
2300
- hydrate();
2301
- return;
2302
- }
2303
- locks.request(`lunora:outbox-leader:${this.url}`, () => {
2304
- if (!this.closed) {
2305
- hydrate();
2306
- }
2307
- return new Promise((resolve) => {
2308
- if (this.closed) {
2309
- resolve();
2310
- return;
2311
- }
2312
- this.outboxLeaderRelease = resolve;
2313
- });
2314
- }).catch(hydrate);
2315
- }
2316
- /**
2317
- * Load every cached query into {@link hydratedQueryCache} so the next
2318
- * `subscribe()` for each key seeds its initial value off disk. A
2319
- * subscription created before this resolves simply misses the cache (it
2320
- * gets a live snapshot as before); the gate at seed time also drops any
2321
- * entry whose stamped identity no longer matches the current one.
2322
- */
2323
- async hydrateQueryCache() {
2324
- if (!this.queryCache) {
2325
- return;
2326
- }
2327
- try {
2328
- const entries = await this.queryCache.load();
2329
- for (const { key, ...entry } of entries) {
2330
- if (isStaleVersion(this.persistenceVersion, entry.version)) {
2331
- this.queryCache.remove(key).catch(() => void 0);
2332
- continue;
2333
- }
2334
- this.hydratedQueryCache.set(key, entry);
2335
- }
2336
- } catch {
2337
- }
2338
- }
2339
- /**
2340
- * Consume the hydrated read-cache entry for a key (if any), gated on
2341
- * identity. The entry is removed whether or not it matches — the cache only
2342
- * ever seeds a subscription's first value. A mismatch (the cache was written
2343
- * under a different identity) yields `undefined` so a signed-out cache never
2344
- * leaks into a new session.
2345
- */
2346
- takeHydratedCache(functionPath, argsKey, shardKey) {
2347
- const key = queryCacheKey(functionPath, argsKey, shardKey);
2348
- const entry = this.hydratedQueryCache.get(key);
2349
- if (entry === void 0) {
2350
- return void 0;
2351
- }
2352
- this.hydratedQueryCache.delete(key);
2353
- return entry.identity === this.identityFingerprint() ? entry : void 0;
2354
- }
2355
- /**
2356
- * Queue a coalesced read-cache write for a subscription's current value.
2357
- * Latest-wins per key; flushed on a short debounce so a delta burst writes
2358
- * once. No-op when the read cache is disabled or the value is undefined
2359
- * (nothing to render offline).
2360
- */
2361
- persistQueryValue(state) {
2362
- const authoritative = state.serverBase;
2363
- if (!this.queryCache || authoritative === void 0) {
2364
- return;
2365
- }
2366
- const key = queryCacheKey(state.fn.__lunoraRef, state.argsKey, state.shardKey);
2367
- this.pendingCacheWrites.set(key, {
2368
- identity: this.identityFingerprint(),
2369
- serverCursor: state.serverCursor,
2370
- ts: Date.now(),
2371
- value: authoritative,
2372
- ...state.serverEpoch === void 0 ? {} : { serverEpoch: state.serverEpoch },
2373
- ...this.persistenceVersion === void 0 ? {} : { version: this.persistenceVersion }
2374
- });
2375
- this.cacheFlushTimer ??= setTimeout(() => {
2376
- this.flushQueryCacheWrites().catch(() => void 0);
2377
- }, QUERY_CACHE_DEBOUNCE_MS);
2378
- }
2379
- /** Drain {@link pendingCacheWrites} to the durable store. */
2380
- async flushQueryCacheWrites() {
2381
- this.cacheFlushTimer = void 0;
2382
- const { queryCache } = this;
2383
- if (!queryCache) {
2384
- this.pendingCacheWrites.clear();
2385
- return;
2386
- }
2387
- const batch = [...this.pendingCacheWrites.entries()];
2388
- this.pendingCacheWrites.clear();
2389
- await Promise.allSettled(batch.map(([key, entry]) => queryCache.put(key, entry)));
2390
- }
2391
- /** Derive the aggregate status from the per-shard socket states. */
2392
- computeStatus() {
2393
- const conns = [...this.connections.values()];
2394
- if (conns.length === 0) {
2395
- return "idle";
2396
- }
2397
- if (conns.some((conn) => conn.wsState === "open")) {
2398
- return "connected";
2399
- }
2400
- if (conns.some((conn) => conn.wsState === "connecting")) {
2401
- return "connecting";
2402
- }
2403
- return "offline";
2404
- }
2405
- /** Recompute the aggregate status and notify listeners if it changed. */
2406
- emitConnectionStatus() {
2407
- const next = this.computeStatus();
2408
- if (next === this.lastStatus) {
2409
- return;
2410
- }
2411
- this.lastStatus = next;
2412
- this.statusListeners.emit(next);
2413
- }
2414
- /**
2415
- * Build a {@link MutationSettledEvent} from a queued entry and emit it on the
2416
- * {@link onMutationSettled} channel. `item.id` is always assigned by the time
2417
- * a write settles (`enqueue`/`hydrate` guarantee it), so the `?? ""` fallback
2418
- * is unreachable — present only to satisfy the optional queue-id type.
2419
- */
2420
- emitItemSettled(item, status, error) {
2421
- this.mutationSettledListeners.emit({
2422
- args: item.args,
2423
- code: error === void 0 ? void 0 : error.code,
2424
- error,
2425
- functionPath: item.functionPath,
2426
- hadAwaiter: item.liveAwaiter ?? false,
2427
- id: item.id ?? "",
2428
- shardKey: item.shardKey,
2429
- status
2430
- });
2431
- }
2432
- /**
2433
- * Apply an optimistic update to the subscription that matches the mutation's
2434
- * `(functionRef, args, shardKey)` triple, returning the rollback callbacks to
2435
- * invoke if the mutation later fails.
2436
- *
2437
- * The registry is already indexed by exactly this triple via
2438
- * `SubscriptionRegistry.key`, so at most one subscription can match. A direct
2439
- * O(1) keyed lookup replaces the former O(N) linear scan over all subscriptions.
2440
- *
2441
- * `shardKey` normalization: both `undefined` and `""` map to the empty string
2442
- * inside `SubscriptionRegistry.key` (via `?? ""`), so a mutation fired without
2443
- * a shardKey correctly matches a subscription registered without one regardless
2444
- * of whether the caller passed `undefined` or omitted the field.
2445
- */
2446
- applyOptimisticUpdates(functionRef, argsRecord, mutationShardKey, optimistic) {
2447
- const confirms = [];
2448
- const rollbacks = [];
2449
- if (!optimistic) {
2450
- return { confirms, rollbacks };
2451
- }
2452
- const matchKey = SubscriptionRegistry.key(functionRef, argsRecord, mutationShardKey);
2453
- const state = this.subscriptions.get(matchKey);
2454
- if (state) {
2455
- const handle = applyOptimisticLayer(state, optimistic);
2456
- if (handle) {
2457
- confirms.push(handle.confirm);
2458
- rollbacks.push(handle.rollback);
2459
- }
2460
- }
2461
- return { confirms, rollbacks };
2462
- }
2463
- /**
2464
- * Run a Convex-parity `optimisticUpdate` callback against a localStore bound
2465
- * to the live subscription registry. Each `setQuery` registers a constant
2466
- * optimistic LAYER on its target subscription (via the same engine the
2467
- * per-call `optimistic` path uses), so the multi-query patch rebases onto
2468
- * incoming deltas and drops gaplessly on its commit cursor — its `confirm` /
2469
- * `rollback` closures are appended to the mutation's settle lists. A throwing
2470
- * callback unwinds its own partial writes — LIFO over just the rollbacks it
2471
- * produced — and is swallowed, so a buggy optimistic update can never fail the
2472
- * mutation or leave a partial patch live.
2473
- */
2474
- applyOptimisticUpdate(optimisticUpdate, args, shardKey, optimisticRollbacks, optimisticConfirms) {
2475
- const { confirms, rollbacks, store } = createLocalStore(this.subscriptions, shardKey);
2476
- try {
2477
- optimisticUpdate(store, args);
2478
- } catch {
2479
- for (let index = rollbacks.length - 1; index >= 0; index -= 1) {
2480
- rollbacks[index]?.();
2481
- }
2482
- return;
2483
- }
2484
- optimisticRollbacks.push(...rollbacks);
2485
- optimisticConfirms.push(...confirms);
2486
- }
2487
- getConnection(shardKey) {
2488
- return this.connections.get(connectionKey(shardKey));
2489
- }
2490
- getOrCreateConnection(shardKey) {
2491
- const key = connectionKey(shardKey);
2492
- let conn = this.connections.get(key);
2493
- if (!conn) {
2494
- conn = {
2495
- connectTimer: void 0,
2496
- heartbeatTimer: void 0,
2497
- pendingUnsubscribes: [],
2498
- reconnect: createReconnect(this.reconnectOptions),
2499
- reconnectTimer: void 0,
2500
- shardKey,
2501
- socket: void 0,
2502
- wasEverConnected: false,
2503
- wsState: "idle"
2504
- };
2505
- this.connections.set(key, conn);
2506
- }
2507
- return conn;
2508
- }
2509
- wsUrlFor(shardKey, token) {
2510
- const params = [];
2511
- if (shardKey !== void 0) {
2512
- params.push(`shard=${encodeURIComponent(shardKey)}`);
2513
- }
2514
- if (token !== void 0) {
2515
- params.push(`token=${encodeURIComponent(token)}`);
2516
- }
2517
- if (params.length === 0) {
2518
- return this.wsUrl;
2519
- }
2520
- const separator = this.wsUrl.includes("?") ? "&" : "?";
2521
- return `${this.wsUrl}${separator}${params.join("&")}`;
2522
- }
2523
- /**
2524
- * Build the outbound RPC headers: JSON content type, optional bearer auth,
2525
- * the optional mutation-replay idempotency key, and the D1 read-your-writes
2526
- * bookmark when the caller opted into `attachBookmark`. The mutation id
2527
- * rides both the direct send and any offline-queue replay of the same write,
2528
- * so a mutation the server already committed returns its cached result
2529
- * instead of running twice.
2530
- */
2531
- rpcRequestHeaders(flags) {
2532
- const headers = { "content-type": "application/json" };
2533
- if (this.authToken) {
2534
- headers["authorization"] = `Bearer ${this.authToken}`;
2535
- }
2536
- if (flags.mutationId) {
2537
- headers["x-lunora-mutation-id"] = flags.mutationId;
2538
- }
2539
- if (flags.clientId !== void 0) {
2540
- headers["x-lunora-client-id"] = flags.clientId;
2541
- }
2542
- if (flags.clientSeq !== void 0) {
2543
- headers["x-lunora-client-seq"] = flags.clientSeq.toString();
2544
- }
2545
- if (flags.attachBookmark) {
2546
- const bookmark = this.bookmark.get();
2547
- if (bookmark) {
2548
- headers["x-d1-bookmark"] = bookmark;
2549
- }
2550
- }
2551
- return headers;
2552
- }
2553
- async rpc(functionPath, args, shardKey, flags = {}) {
2554
- if (!this.fetchImpl) {
2555
- throw new LunoraError("INTERNAL", "LunoraClient: no `fetch` implementation available");
2556
- }
2557
- const headers = this.rpcRequestHeaders(flags);
2558
- const response = await this.fetchImpl(joinUrl(this.url, RPC_PATH), {
2559
- // `encodeWire` tags leaves plain JSON can't carry (`bigint`,
2560
- // `ArrayBuffer`/typed arrays, `NaN`/±Infinity); a pure-JSON `args`
2561
- // encodes byte-identically, so a pre-codec server still interops.
2562
- body: JSON.stringify({ args: encodeCallArgs(args, `args for '${functionPath}'`), functionPath, shardKey }),
2563
- headers,
2564
- method: "POST"
2565
- });
2566
- if (flags.captureBookmark) {
2567
- const value = response.headers.get("x-d1-bookmark");
2568
- if (value) {
2569
- this.bookmark.set(value);
2570
- }
2571
- }
2572
- let body;
2573
- try {
2574
- body = await response.json();
2575
- } catch {
2576
- const statusText = response.statusText ? ` ${response.statusText}` : "";
2577
- throw new LunoraError("INTERNAL", `LunoraClient: response was not JSON (status ${response.status.toString()}${statusText})`);
2578
- }
2579
- if ("error" in body) {
2580
- throw reconstructError(body.error);
2581
- }
2582
- if (!response.ok) {
2583
- const statusText = response.statusText ? ` ${response.statusText}` : "";
2584
- throw new LunoraError("INTERNAL", `LunoraClient: request failed (status ${response.status.toString()}${statusText})`);
2585
- }
2586
- flags.onMutationAck?.(body.lastMutationId);
2587
- flags.onCommitCursor?.(body.commitCursor);
2588
- return decodeWire(body.result);
2589
- }
2590
- /**
2591
- * Authenticated request to a non-RPC admin endpoint (the scheduler list /
2592
- * cancel routes). Attaches the bearer token, parses JSON, and surfaces the
2593
- * worker's `{ error: { code, message } }` envelope as a coded `Error` —
2594
- * mirroring {@link rpc} so callers see the same failure shape.
2595
- */
2596
- async adminFetch(path, method, payload, contentType) {
2597
- if (!this.fetchImpl) {
2598
- throw new LunoraError("INTERNAL", "LunoraClient: no `fetch` implementation available");
2599
- }
2600
- const headers = {};
2601
- if (this.authToken) {
2602
- headers["authorization"] = `Bearer ${this.authToken}`;
2603
- }
2604
- const isBinary = payload instanceof ArrayBuffer || payload instanceof Blob;
2605
- let requestBody;
2606
- if (payload === void 0) {
2607
- requestBody = void 0;
2608
- } else if (isBinary) {
2609
- requestBody = payload;
2610
- if (contentType !== void 0) {
2611
- headers["content-type"] = contentType;
2612
- }
2613
- } else {
2614
- requestBody = JSON.stringify(payload);
2615
- headers["content-type"] = "application/json";
2616
- }
2617
- const response = await this.fetchImpl(joinUrl(this.url, path), {
2618
- body: requestBody,
2619
- headers,
2620
- method
2621
- });
2622
- let body;
2623
- try {
2624
- body = await response.json();
2625
- } catch {
2626
- const statusText = response.statusText ? ` ${response.statusText}` : "";
2627
- throw new LunoraError("INTERNAL", `LunoraClient: response was not JSON (status ${response.status.toString()}${statusText})`);
2628
- }
2629
- if (typeof body === "object" && body !== null && "error" in body) {
2630
- const envelope = body.error;
2631
- const error = new Error(envelope.message ?? "admin request failed");
2632
- error.code = envelope.code;
2633
- throw error;
2634
- }
2635
- if (!response.ok) {
2636
- const statusText = response.statusText ? ` ${response.statusText}` : "";
2637
- throw new LunoraError("INTERNAL", `LunoraClient: admin request failed (status ${response.status.toString()}${statusText})`);
2638
- }
2639
- return body;
2640
- }
2641
- /**
2642
- * Resolve the effective connection context for a shard: the most-recently
2643
- * acquired refcounted holder ({@link acquireConnectionContext}) wins, falling
2644
- * back to the imperative {@link setConnectionContext} override, then the
2645
- * client-wide default. Returns `undefined` when none apply.
2646
- */
2647
- effectiveConnectionContext(key) {
2648
- const holders = this.connectionContextHolders.get(key);
2649
- if (holders && holders.length > 0) {
2650
- return holders[holders.length - 1]?.context;
2651
- }
2652
- return this.connectionContexts.get(key) ?? this.defaultConnectionContext;
2653
- }
2654
- /** Re-send the `connect` envelope for a shard whose effective context just changed (if its socket is open). */
2655
- refreshConnectionContext(key) {
2656
- const conn = this.connections.get(key);
2657
- if (conn?.wsState === "open") {
2658
- this.sendConnectEnvelope(conn);
2659
- }
2660
- }
2661
- /**
2662
- * Send the one-shot `connect` envelope on an open shard socket. Always sent
2663
- * once per socket open, so the server's `onConnect` hooks fire symmetrically
2664
- * with `onDisconnect` (which the DO dispatches unconditionally at close for
2665
- * every lifecycle-aware socket). The DO no-ops cheaply when no `onConnect`
2666
- * hooks are registered, so the single frame costs nothing in the common case.
2667
- *
2668
- * The shard's registered context (or the client-wide default) rides along
2669
- * when one is set — the DO records it on the attachment for replay to
2670
- * `onDisconnect`. A socket with no registered context still announces itself;
2671
- * the envelope simply omits `context`, which is optional on the wire.
2672
- * Register a context — e.g. `setConnectionContext({})` — to attach app state
2673
- * to the lifecycle dispatch.
2674
- */
2675
- sendConnectEnvelope(conn) {
2676
- const context = this.effectiveConnectionContext(connectionKey(conn.shardKey));
2677
- sendOn(conn, {
2678
- // Lets the server scope this connection's `__client_watermark` so
2679
- // custom-mutator pokes can echo this client's `lastMutationId`.
2680
- clientId: this.clientId,
2681
- id: "connect",
2682
- type: "connect",
2683
- ...context === void 0 ? {} : { context }
2684
- });
2685
- }
2686
- /**
2687
- * Re-send every shape subscription bound to `shardKey` over its (now open)
2688
- * socket. Each frame carries the shape's last applied checkpoint, so the
2689
- * server resumes from it — or re-seeds when the cursor fell below CDC
2690
- * retention or the epoch forked.
2691
- */
2692
- resendShapeSubscriptions(shardKey) {
2693
- for (const state of this.shapeSubscriptions.values()) {
2694
- if (connectionKey(state.shardKey) === connectionKey(shardKey)) {
2695
- this.sendShapeSubscribeIfOpen(state);
2696
- }
2697
- }
2698
- }
2699
- ensureSocket(shardKey) {
2700
- if (this.closed || this.WebSocketImpl === void 0) {
2701
- return;
2702
- }
2703
- if (this.tabCoordinator && !this.tabCoordinator.isLeader()) {
2704
- return;
2705
- }
2706
- const conn = this.getOrCreateConnection(shardKey);
2707
- if (conn.wsState === "open" || conn.wsState === "connecting") {
2708
- return;
2709
- }
2710
- conn.wsState = "connecting";
2711
- this.emitConnectionStatus();
2712
- if (typeof this.wsToken === "function") {
2713
- this.openSocketWithProvidedToken(conn, shardKey, this.wsToken).catch(() => void 0);
2714
- return;
2715
- }
2716
- this.openSocket(conn, shardKey, this.wsToken);
2717
- }
2718
- /**
2719
- * Resolve the {@link WsTokenProvider} and open the shard socket with the
2720
- * minted token. The connection is already in the `connecting` state, so the
2721
- * async gap is race-guarded: a client `close()`, a `setWsToken` bounce, or a
2722
- * competing connect that landed first all abandon this attempt. A provider
2723
- * failure fails the attempt through {@link handleDisconnect}, which arms the
2724
- * normal reconnect backoff — a broken mint endpoint degrades to retries, not
2725
- * a silent tokenless socket the admin gate would reject.
2726
- */
2727
- async openSocketWithProvidedToken(conn, shardKey, provider) {
2728
- let token;
2729
- try {
2730
- token = await provider();
2731
- } catch {
2732
- this.handleDisconnect(conn);
2733
- return;
2734
- }
2735
- if (this.closed || this.WebSocketImpl === void 0 || conn.wsState !== "connecting" || conn.socket !== void 0) {
2736
- return;
2737
- }
2738
- this.openSocket(conn, shardKey, token);
2739
- }
2740
- /** Construct the shard socket and wire its lifecycle handlers. The connection must already be in the `connecting` state. */
2741
- openSocket(conn, shardKey, token) {
2742
- if (this.WebSocketImpl === void 0) {
2743
- return;
2744
- }
2745
- const socket = new this.WebSocketImpl(this.wsUrlFor(shardKey, token));
2746
- conn.socket = socket;
2747
- if (this.connectTimeoutMs > 0) {
2748
- conn.connectTimer = setTimeout(() => {
2749
- conn.connectTimer = void 0;
2750
- if (conn.socket !== socket || conn.wsState !== "connecting") {
2751
- return;
2752
- }
2753
- try {
2754
- socket.close();
2755
- } catch {
2756
- }
2757
- this.handleDisconnect(conn);
2758
- }, this.connectTimeoutMs);
2759
- }
2760
- socket.addEventListener("open", () => {
2761
- if (conn.socket !== socket) {
2762
- return;
2763
- }
2764
- if (conn.connectTimer !== void 0) {
2765
- clearTimeout(conn.connectTimer);
2766
- conn.connectTimer = void 0;
2767
- }
2768
- conn.wsState = "open";
2769
- conn.wasEverConnected = true;
2770
- conn.reconnect.reset();
2771
- this.emitConnectionStatus();
2772
- this.sendConnectEnvelope(conn);
2773
- this.markShardPendingAck(shardKey);
2774
- for (const state of this.subscriptions.all()) {
2775
- if (connectionKey(state.shardKey) === connectionKey(shardKey)) {
2776
- this.sendSubscribeIfOpen(state);
2777
- }
2778
- }
2779
- this.resendShapeSubscriptions(shardKey);
2780
- if (conn.pendingUnsubscribes.length > 0) {
2781
- const pending = conn.pendingUnsubscribes;
2782
- conn.pendingUnsubscribes = [];
2783
- for (const { id, type } of pending) {
2784
- sendOn(conn, { id, type });
2785
- }
2786
- }
2787
- if (conn.pendingStreams && conn.pendingStreams.length > 0) {
2788
- const pending = conn.pendingStreams;
2789
- conn.pendingStreams = [];
2790
- for (const message of pending) {
2791
- sendOn(conn, message);
2792
- }
2793
- }
2794
- const byTopic = this.whisperHandlers.get(connectionKey(shardKey));
2795
- if (byTopic) {
2796
- for (const topic of byTopic.keys()) {
2797
- sendOn(conn, { topic, type: "whisper_subscribe" });
2798
- }
2799
- }
2800
- this.flushOfflineQueue(shardKey).catch(() => void 0);
2801
- this.startHeartbeat(conn);
2802
- });
2803
- socket.addEventListener("message", (event) => {
2804
- this.handleServerMessage(event.data, shardKey);
2805
- });
2806
- socket.addEventListener("close", (event) => {
2807
- if (conn.socket !== socket) {
2808
- return;
2809
- }
2810
- if (event?.code === 4001) {
2811
- this.notifyTokenExpired();
2812
- }
2813
- this.handleDisconnect(conn);
2814
- });
2815
- socket.addEventListener("error", () => {
2816
- if (conn.socket !== socket) {
2817
- return;
2818
- }
2819
- if (conn.wsState === "connecting" || conn.wsState === "open") {
2820
- this.handleDisconnect(conn);
2821
- }
2822
- });
2823
- }
2824
- handleDisconnect(conn) {
2825
- if (this.closed) {
2826
- return;
2827
- }
2828
- if (conn.wsState === "idle" || conn.wsState === "closed") {
2829
- return;
2830
- }
2831
- this.stopHeartbeat(conn);
2832
- if (conn.connectTimer !== void 0) {
2833
- clearTimeout(conn.connectTimer);
2834
- conn.connectTimer = void 0;
2835
- }
2836
- conn.socket = void 0;
2837
- conn.wsState = "idle";
2838
- this.emitConnectionStatus();
2839
- this.markShardPendingAck(conn.shardKey);
2840
- const pendingStreamIds = new Set((conn.pendingStreams ?? []).map((message) => message.id));
2841
- for (const [id, stream] of this.streams) {
2842
- if (connectionKey(stream.shardKey) === connectionKey(conn.shardKey) && !pendingStreamIds.has(id)) {
2843
- stream.handle.fail(new LunoraError("STREAM_DISCONNECTED", "stream terminated: WebSocket disconnected"));
2844
- this.streams.delete(id);
2845
- }
2846
- }
2847
- if (this.WebSocketImpl === void 0) {
2848
- return;
2849
- }
2850
- const delay = conn.reconnect.next();
2851
- conn.reconnectTimer = setTimeout(() => {
2852
- conn.reconnectTimer = void 0;
2853
- this.ensureSocket(conn.shardKey);
2854
- }, delay);
2855
- }
2856
- /**
2857
- * Begin the keepalive heartbeat on an open connection. Each tick sends a
2858
- * {@link WS_KEEPALIVE_PING} text frame the server answers from its
2859
- * hibernation auto-response without waking the DO. A no-op when the
2860
- * heartbeat is disabled (an interval of zero or less); idempotent — any
2861
- * existing timer is cleared first so a reconnect can't leak intervals.
2862
- */
2863
- startHeartbeat(conn) {
2864
- this.stopHeartbeat(conn);
2865
- if (this.heartbeatIntervalMs <= 0) {
2866
- return;
2867
- }
2868
- conn.heartbeatTimer = setInterval(() => {
2869
- if (conn.wsState !== "open" || !conn.socket) {
2870
- return;
2871
- }
2872
- try {
2873
- conn.socket.send(WS_KEEPALIVE_PING);
2874
- } catch {
2875
- }
2876
- }, this.heartbeatIntervalMs);
2877
- }
2878
- /** Clear a connection's keepalive timer, if any. Safe to call repeatedly. */
2879
- // eslint-disable-next-line class-methods-use-this -- cohesive connection helper; pairs with startHeartbeat
2880
- stopHeartbeat(conn) {
2881
- if (conn.heartbeatTimer !== void 0) {
2882
- clearInterval(conn.heartbeatTimer);
2883
- conn.heartbeatTimer = void 0;
2884
- }
2885
- }
2886
- /** Mark every subscription bound to `shardKey` as needing a fresh ack. */
2887
- markShardPendingAck(shardKey) {
2888
- const key = connectionKey(shardKey);
2889
- for (const state of this.subscriptions.all()) {
2890
- if (connectionKey(state.shardKey) === key) {
2891
- state.acked = false;
2892
- }
2893
- }
2894
- }
2895
- sendSubscribeIfOpen(state) {
2896
- const conn = this.getConnection(state.shardKey);
2897
- if (conn?.wsState !== "open" || state.acked) {
2898
- return;
2899
- }
2900
- const table = state.fn.__lunoraTable ?? state.fn.__lunoraRef;
2901
- sendOn(conn, {
2902
- id: state.id,
2903
- // `sinceSeq` rides along when we hold a persisted cursor for this
2904
- // sub (a hydrated read or an earlier frame), so the server can
2905
- // resume instead of re-snapshotting. Omitted on a cold sub.
2906
- query: {
2907
- // Wire-encode so a `bigint`/`Date`/bytes arg survives the frame's
2908
- // `JSON.stringify` (the shard `decodeWire`s at its subscribe entry
2909
- // point). Identity for pure-JSON args. Cannot throw here: the
2910
- // registry key (`stableWireKey`) already encoded these args at
2911
- // subscribe() time, so reconnect resends stay safe.
2912
- args: encodeWire(state.args),
2913
- functionPath: state.fn.__lunoraRef,
2914
- table,
2915
- ...state.serverCursor === void 0 ? {} : { sinceSeq: state.serverCursor },
2916
- ...state.serverEpoch === void 0 ? {} : { sinceEpoch: state.serverEpoch }
2917
- },
2918
- type: "subscribe"
2919
- });
2920
- }
2921
- sendShapeSubscribeIfOpen(state) {
2922
- const conn = this.getConnection(state.shardKey);
2923
- if (conn?.wsState !== "open") {
2924
- return;
2925
- }
2926
- sendOn(conn, {
2927
- id: state.id,
2928
- // `wireArgs` is the pre-encoded form of `args` (computed at
2929
- // `subscribeShape` time) so a `bigint`/`Date`/bytes arg survives the
2930
- // frame's `JSON.stringify`; the shard `decodeWire`s it at its
2931
- // `shape_subscribe` entry point. Identity for pure-JSON args.
2932
- shape: { name: state.name, ...state.wireArgs === void 0 ? {} : { args: state.wireArgs } },
2933
- type: "shape_subscribe",
2934
- // Resume from the last applied checkpoint when we hold one; a cold
2935
- // subscribe omits it and the server seeds the full membership.
2936
- ...state.serverCursor === void 0 ? {} : { sinceCheckpoint: state.serverCursor },
2937
- ...state.serverEpoch === void 0 ? {} : { sinceEpoch: state.serverEpoch }
2938
- });
2939
- }
2940
- handleServerMessage(raw, shardKey) {
2941
- const text = decodeServerFrame(raw);
2942
- if (text === void 0) {
2943
- return;
2944
- }
2945
- let message;
2946
- try {
2947
- message = JSON.parse(text);
2948
- } catch {
2949
- return;
2950
- }
2951
- switch (message.type) {
2952
- case "ack": {
2953
- const state = this.subscriptions.getById(message.id);
2954
- if (state) {
2955
- state.acked = true;
2956
- }
2957
- return;
2958
- }
2959
- case "chunk": {
2960
- const { data, id } = message;
2961
- const stream = this.streams.get(id);
2962
- stream?.handle.push(decodeWire(data));
2963
- return;
2964
- }
2965
- case "complete": {
2966
- this.handleCompleteMessage(message.id);
2967
- return;
2968
- }
2969
- case "data":
2970
- case "delta": {
2971
- this.handleDataMessage(message);
2972
- return;
2973
- }
2974
- case "error": {
2975
- this.handleErrorMessage(message);
2976
- break;
2977
- }
2978
- case "pokeEnd": {
2979
- this.handlePokeEnd(message);
2980
- break;
2981
- }
2982
- case "pokePart": {
2983
- this.handlePokePart(message);
2984
- break;
2985
- }
2986
- case "pokeStart": {
2987
- this.handlePokeStart(message);
2988
- break;
2989
- }
2990
- case "resume": {
2991
- this.handleResumeMessage(message);
2992
- break;
2993
- }
2994
- case "settled": {
2995
- this.handleSettledMessage(message);
2996
- break;
2997
- }
2998
- case "whisper": {
2999
- this.dispatchWhisper(message, shardKey);
3000
- break;
3001
- }
3002
- }
3003
- }
3004
- handleErrorMessage(message) {
3005
- const errorCode = message.error?.code;
3006
- if (errorCode === "TOKEN_EXPIRED") {
3007
- this.notifyTokenExpired();
3008
- return;
3009
- }
3010
- const { id } = message;
3011
- const stream = id === void 0 ? void 0 : this.streams.get(id);
3012
- if (stream && id !== void 0) {
3013
- stream.handle.fail(buildStreamError(message));
3014
- this.streams.delete(id);
3015
- return;
3016
- }
3017
- const state = id === void 0 ? void 0 : this.subscriptions.getById(id);
3018
- if (state) {
3019
- fanSubscriptionError(state.errorCallbacks, buildSubscriptionError(message));
3020
- return;
3021
- }
3022
- const shapeState = id === void 0 ? void 0 : this.shapeSubscriptions.get(id);
3023
- if (shapeState) {
3024
- fanSubscriptionError(shapeState.errorCallbacks, buildSubscriptionError(message));
3025
- }
3026
- }
3027
- handlePokeStart(message) {
3028
- evictOldestEntry(this.pokeBuffers, LunoraClient.MAX_POKE_BUFFERS);
3029
- this.pokeBuffers.set(message.pokeId, { baseCheckpoint: message.baseCheckpoint, epoch: message.epoch, lastMutationId: /* @__PURE__ */ new Map(), parts: /* @__PURE__ */ new Map() });
3030
- }
3031
- handlePokePart(message) {
3032
- const buffer = this.pokeBuffers.get(message.pokeId);
3033
- if (!buffer) {
3034
- return;
3035
- }
3036
- const existing = buffer.parts.get(message.shapeId) ?? [];
3037
- for (const op of message.rowsPatch) {
3038
- existing.push(op.value === void 0 ? op : { ...op, value: decodeWire(op.value) });
3039
- }
3040
- buffer.parts.set(message.shapeId, existing);
3041
- if (message.lastMutationId !== void 0) {
3042
- buffer.lastMutationId.set(message.shapeId, message.lastMutationId);
3043
- }
3044
- }
3045
- handlePokeEnd(message) {
3046
- const buffer = this.pokeBuffers.get(message.pokeId);
3047
- if (!buffer) {
3048
- return;
3049
- }
3050
- this.pokeBuffers.delete(message.pokeId);
3051
- for (const [shapeId, ops] of buffer.parts) {
3052
- const state = this.shapeSubscriptions.get(shapeId);
3053
- if (!state) {
3054
- continue;
3055
- }
3056
- const epochForked = buffer.epoch !== void 0 && state.serverEpoch !== void 0 && buffer.epoch !== state.serverEpoch;
3057
- const baseDiverged = buffer.baseCheckpoint !== void 0 && state.serverCursor !== void 0 && state.serverCursor !== buffer.baseCheckpoint;
3058
- if (epochForked || baseDiverged) {
3059
- state.rows.clear();
3060
- state.serverCursor = void 0;
3061
- state.serverEpoch = void 0;
3062
- this.emitShapeRows(state);
3063
- this.sendShapeSubscribeIfOpen(state);
3064
- continue;
3065
- }
3066
- applyRowOpsToView(state.rows, ops);
3067
- if (message.checkpoint !== void 0) {
3068
- state.serverCursor = message.checkpoint;
3069
- }
3070
- if (message.epoch !== void 0) {
3071
- state.serverEpoch = message.epoch;
3072
- }
3073
- const watermark = buffer.lastMutationId.get(shapeId);
3074
- if (watermark !== void 0) {
3075
- state.lastMutationId = watermark;
3076
- }
3077
- this.emitShapeRows(state);
3078
- state.onCheckpoint?.({ checkpoint: state.serverCursor, mutationId: state.lastMutationId });
3079
- }
3080
- }
3081
- /** Materialize a shape's keyed view to an array and invoke its callbacks. */
3082
- // eslint-disable-next-line class-methods-use-this -- a pure state→callback fan-out kept beside the shape-subscription pipeline it serves.
3083
- emitShapeRows(state) {
3084
- const rows = [...state.rows.values()];
3085
- for (const shapeCallback of state.callbacks) {
3086
- try {
3087
- shapeCallback(rows);
3088
- } catch {
3089
- }
3090
- }
3091
- }
3092
- handleDataMessage(message) {
3093
- const { id } = message;
3094
- const state = id ? this.subscriptions.getById(id) : void 0;
3095
- if (!state) {
3096
- return;
3097
- }
3098
- const payload = this.resolveDataPayload(message, state);
3099
- state.serverBase = payload;
3100
- if (message.cursor !== void 0) {
3101
- state.serverCursor = message.cursor;
3102
- }
3103
- if (message.epoch !== void 0) {
3104
- state.serverEpoch = message.epoch;
3105
- }
3106
- this.persistQueryValue(state);
3107
- dropConfirmedLayers(state, state.serverCursor);
3108
- notifySubscription(state, state.optimisticLayers.length === 0 ? payload : foldOptimistic(payload, state.optimisticLayers));
3109
- if (this.tabCoordinator?.isLeader()) {
3110
- const key = SubscriptionRegistry.key(state.fn.__lunoraRef, state.args, state.shardKey);
3111
- this.tabCoordinator.broadcastSubscriptionData(key, payload);
3112
- }
3113
- }
3114
- /**
3115
- * Handle a `resume` frame (Pillar 1b): the server proved nothing the
3116
- * subscription reads changed since our `sinceSeq`, so the cached value is
3117
- * still current. We keep `lastValue` as-is, mark the sub acked, and advance
3118
- * the cursor (re-persisting so the next reconnect resumes from the newer
3119
- * watermark). No callback fires — the value didn't change, and `subscribe()`
3120
- * already replayed the cached value to every consumer synchronously.
3121
- */
3122
- handleResumeMessage(message) {
3123
- const state = this.subscriptions.getById(message.id);
3124
- if (!state) {
3125
- return;
3126
- }
3127
- this.ackAndAdvanceCursor(state, message.cursor, message.epoch);
3128
- }
3129
- /**
3130
- * Handle a `settled` frame: a write touched one of this subscription's read
3131
- * tables but produced a byte-identical result, so the server suppressed the
3132
- * data frame. Like {@link handleResumeMessage} the value didn't change — we
3133
- * advance the resume position and re-persist — but we ALSO surface the echoed
3134
- * custom-mutator watermark via `onCheckpoint` so a `@lunora/db` list
3135
- * collection drops the optimistic overlay for the confirmed write (otherwise
3136
- * its checkpoint gate, fed only by data frames, would hang forever). Sent
3137
- * only to custom-mutator clients; plain `useQuery` subscribers leave
3138
- * `onCheckpoint` unset and this is a near no-op.
3139
- */
3140
- handleSettledMessage(message) {
3141
- const state = this.subscriptions.getById(message.id);
3142
- if (!state) {
3143
- return;
3144
- }
3145
- this.ackAndAdvanceCursor(state, message.cursor, message.epoch);
3146
- if (message.lastMutationId !== void 0) {
3147
- state.lastMutationId = message.lastMutationId;
3148
- }
3149
- for (const onCheckpoint of state.checkpointCallbacks) {
3150
- onCheckpoint({ checkpoint: state.serverCursor, mutationId: state.lastMutationId });
3151
- }
3152
- }
3153
- /**
3154
- * Mark `state` acked and, when the frame carries a newer cursor/epoch than
3155
- * the cached position, advance the resume watermark and re-persist. Shared by
3156
- * the `resume` and `settled` frame handlers — both acknowledge "nothing the
3157
- * client must re-render changed, but the resume position may have moved".
3158
- */
3159
- ackAndAdvanceCursor(state, cursor, epoch) {
3160
- state.acked = true;
3161
- if (cursor !== void 0 && cursor !== state.serverCursor || epoch !== void 0 && epoch !== state.serverEpoch) {
3162
- if (cursor !== void 0) {
3163
- state.serverCursor = cursor;
3164
- }
3165
- if (epoch !== void 0) {
3166
- state.serverEpoch = epoch;
3167
- }
3168
- this.persistQueryValue(state);
3169
- if (dropConfirmedLayers(state, state.serverCursor)) {
3170
- notifySubscription(state, foldOptimistic(state.serverBase, state.optimisticLayers));
3171
- }
3172
- }
3173
- }
3174
- /**
3175
- * Resolve the value to publish for a `data`/`delta` frame.
3176
- *
3177
- * A `data` frame is an authoritative snapshot (the server re-execution path)
3178
- * and always replaces the cached value wholesale. A `delta` frame carrying a
3179
- * structured `MutationDelta` (the `broadcastDelta` row-change path) is
3180
- * merged incrementally into the cached list — preserving order, no dup/loss —
3181
- * so each subscription (including every paginated page) updates by delta
3182
- * rather than a full re-send. We fall back to full replacement when the
3183
- * delta isn't a recognisable row change, when there's no cached value yet,
3184
- * or when it can't be applied cleanly against the current cached shape.
3185
- */
3186
- // eslint-disable-next-line class-methods-use-this -- instance method for symmetry with the other message handlers; reads no shared client state
3187
- resolveDataPayload(message, state) {
3188
- if ("data" in message && message.data !== void 0) {
3189
- return decodeWire(message.data);
3190
- }
3191
- const delta = decodeWire(message.delta);
3192
- if (isMutationDelta(delta) && state.serverBase !== void 0) {
3193
- const merged = applyDelta(state.serverBase, delta);
3194
- if (merged !== void 0) {
3195
- return merged;
3196
- }
3197
- }
3198
- return delta;
3199
- }
3200
- /** Route an inbound whisper to the topic's handlers on the originating shard. */
3201
- dispatchWhisper(message, shardKey) {
3202
- const handlers = this.whisperHandlers.get(connectionKey(shardKey))?.get(message.topic);
3203
- if (!handlers) {
3204
- return;
3205
- }
3206
- const data = decodeWire(message.data);
3207
- for (const handler of handlers) {
3208
- try {
3209
- handler(data, message.from);
3210
- } catch {
3211
- }
3212
- }
3213
- }
3214
- /** Notify every {@link onTokenExpired} listener (best-effort, listener throws swallowed). */
3215
- notifyTokenExpired() {
3216
- this.tokenExpiredListeners.emit();
3217
- }
3218
- handleCompleteMessage(id) {
3219
- const stream = this.streams.get(id);
3220
- if (stream) {
3221
- stream.handle.complete();
3222
- this.streams.delete(id);
3223
- return;
3224
- }
3225
- const state = this.subscriptions.getById(id);
3226
- if (state) {
3227
- this.subscriptions.remove(state);
3228
- }
3229
- }
3230
- unpersist(id) {
3231
- if (id) {
3232
- this.persistence?.remove(id).catch((error) => {
3233
- reportPersistenceError(this.onPersistenceError, "remove", error, id);
3234
- });
3235
- }
3236
- }
3237
- /**
3238
- * Stable, non-reversible fingerprint of the current auth identity used to
3239
- * stamp queued offline writes. `null` (signed out) is its own identity and
3240
- * never matches a bearer-token fingerprint. The raw token is never stored;
3241
- * a length-prefixed FNV-1a hash is enough to detect an identity *change*
3242
- * without keeping the credential around in the queue map.
3243
- */
3244
- // `null` is the distinct "signed out" identity (separate from `undefined`,
3245
- // which means "not stamped / hydrated"); the two must not be conflated.
3246
- identityFingerprint() {
3247
- if (this.authSubject !== void 0) {
3248
- return this.authSubject === null ? null : `subj:${this.authSubject}`;
3249
- }
3250
- const token = this.authToken;
3251
- if (token === null) {
3252
- return null;
3253
- }
3254
- return this.hashToken(token);
3255
- }
3256
- /**
3257
- * Stable token-hash fingerprint of a bearer token (the `&lt;len>:&lt;fnv>:&lt;djb2>`
3258
- * format a token-stamped queued write carries). Extracted so the replay gate
3259
- * can recompute the hash of the current credential and recognise a write
3260
- * stamped under it — even after the fingerprint was relabelled to a subject.
3261
- *
3262
- * Two independent 32-bit passes (FNV-1a + djb2) give a ~64-bit digest, so
3263
- * two distinct equal-length tokens are astronomically unlikely to share a
3264
- * fingerprint. A single 32-bit hash collides ~1-in-4e9 per equal-length
3265
- * pair — enough that, on a shared device, user B could hydrate A's cached
3266
- * reads. Different algorithms (not the same FNV with a different seed, which
3267
- * would be affine-related) keep the two passes genuinely independent.
3268
- * Still synchronous (no crypto) and stable across surrogate pairs.
3269
- */
3270
- // eslint-disable-next-line class-methods-use-this -- pure helper; a method for locality with identityFingerprint, reads no shared state
3271
- hashToken(token) {
3272
- let fnv = 2166136261;
3273
- let djb2 = 5381;
3274
- for (let index = 0; index < token.length; index += 1) {
3275
- const code = token.charCodeAt(index);
3276
- fnv ^= code;
3277
- fnv = Math.imul(fnv, 16777619);
3278
- djb2 = Math.imul(djb2, 33) + code;
3279
- }
3280
- return `${token.length.toString(36)}:${(fnv >>> 0).toString(36)}:${(djb2 >>> 0).toString(36)}`;
3281
- }
3282
- /**
3283
- * True when `stamped` is a token-hash of the SAME credential still held now,
3284
- * even though the live identity has since been relabelled to a subject. Covers
3285
- * `setAuthToken(token, userId)` where the subject resolved a tick after the
3286
- * token was set: a write persisted (or requeued) under the token hash must
3287
- * still replay — the credential never changed, only its label — instead of
3288
- * being dropped as an identity mismatch. This is the durable counterpart to
3289
- * {@link restampQueuedIdentity}, which only relabels the in-memory live stamp
3290
- * (consumed on the first flush) and never touches `item.identity` or the
3291
- * persisted record, so a reload or a transient-failure requeue would otherwise
3292
- * fall back to the stale token-hash and wrongly reject the same user's write.
3293
- */
3294
- isSameCredentialUnderTokenHash(stamped) {
3295
- if (stamped === null || stamped.startsWith("subj:")) {
3296
- return false;
3297
- }
3298
- const token = this.authToken;
3299
- return token === null ? false : this.hashToken(token) === stamped;
3300
- }
3301
- /**
3302
- * Drain every in-memory offline write and reject it because the auth
3303
- * identity changed. Durable entries are also dropped from persistence so a
3304
- * later `hydrate` can't resurrect another user's writes. Stamps are cleared
3305
- * alongside. Persisted entries restored without a live awaiter still get
3306
- * unpersisted here.
3307
- */
3308
- rejectQueuedForIdentityChange() {
3309
- const drained = this.offlineQueue.drain();
3310
- for (const item of drained) {
3311
- this.queuedIdentities.delete(item.id ?? "");
3312
- this.unpersist(item.id);
3313
- const error = new Error("offline mutation discarded: auth identity changed before replay");
3314
- error.code = "OFFLINE_IDENTITY_CHANGED";
3315
- item.reject(error);
3316
- this.emitItemSettled(item, "rejected", error);
3317
- }
3318
- this.clearQueryCacheForIdentityChange();
3319
- }
3320
- /**
3321
- * Migrate every live identity stamp from `from` to `to` — used when the auth
3322
- * identity label changes but the underlying credential (token) does NOT, e.g.
3323
- * the user id resolves a tick after the token was set. The in-memory
3324
- * `queuedIdentities` map is the flush-time source of truth, so re-stamping it
3325
- * keeps the in-flight writes replayable under the new (more stable) identity
3326
- * instead of the flush guard discarding them as a mismatch.
3327
- */
3328
- restampQueuedIdentity(from, to) {
3329
- for (const [id, stamp] of this.queuedIdentities) {
3330
- if (stamp === from) {
3331
- this.queuedIdentities.set(id, to);
3332
- }
3333
- }
3334
- }
3335
- /**
3336
- * Drop the durable read cache on an identity change so a cached value stamped
3337
- * under the previous identity can never hydrate into a new session. Clears
3338
- * the in-flight write batch and the not-yet-consumed hydrated entries too;
3339
- * the durable `clear()` is best-effort.
3340
- */
3341
- clearQueryCacheForIdentityChange() {
3342
- if (this.cacheFlushTimer !== void 0) {
3343
- clearTimeout(this.cacheFlushTimer);
3344
- this.cacheFlushTimer = void 0;
3345
- }
3346
- this.pendingCacheWrites.clear();
3347
- this.hydratedQueryCache.clear();
3348
- this.queryCache?.clear().catch(() => void 0);
3349
- }
3350
- async flushOfflineQueue(shardKey) {
3351
- const conflicted = this.offlineQueue.drainConflict();
3352
- for (const item of conflicted) {
3353
- this.unpersist(item.id);
3354
- this.queuedIdentities.delete(item.id ?? "");
3355
- const error = new Error("offline mutation skipped: precondition failed before replay");
3356
- error.code = "OFFLINE_PRECONDITION_FAILED";
3357
- this.emitItemSettled(item, "rejected", error);
3358
- }
3359
- const key = connectionKey(shardKey);
3360
- const drained = this.offlineQueue.drain((item) => connectionKey(item.shardKey) === key);
3361
- if (drained.length === 0) {
3362
- return;
3363
- }
3364
- const currentIdentity = this.identityFingerprint();
3365
- const sendable = [];
3366
- for (const item of drained) {
3367
- if (this.passesReplayIdentityGate(item, currentIdentity)) {
3368
- sendable.push(item);
3369
- }
3370
- }
3371
- if (sendable.length === 0) {
3372
- return;
3373
- }
3374
- const encodable = this.encodableOrSettleTerminal(sendable);
3375
- if (encodable.length === 0) {
3376
- return;
3377
- }
3378
- if (encodable.length === 1) {
3379
- await this.replaySequential(encodable);
3380
- return;
3381
- }
3382
- const toRequeue = [];
3383
- for (let start = 0; start < encodable.length; start += MAX_BATCH_ENTRIES) {
3384
- const chunk = encodable.slice(start, start + MAX_BATCH_ENTRIES);
3385
- const outcome = await this.replayBatched(chunk);
3386
- toRequeue.push(...outcome.requeue);
3387
- if (outcome.stop) {
3388
- toRequeue.push(...encodable.slice(start + MAX_BATCH_ENTRIES));
3389
- break;
3390
- }
3391
- }
3392
- if (toRequeue.length > 0) {
3393
- this.offlineQueue.requeue(toRequeue);
3394
- }
3395
- }
3396
- /**
3397
- * Partition already-gated writes into the encodable ones (returned) and reject
3398
- * the rest terminally. A write whose args can't be wire-encoded (e.g. a RegExp
3399
- * or class instance in a `v.any()` field) can NEVER replay — the codec failure
3400
- * is deterministic, not transient. Rejecting here is essential: otherwise
3401
- * `encodeWire` throws mid-flush, is classified as transient (a codec error has
3402
- * no `.code`), and re-queues forever — a silent hang where the caller's Promise
3403
- * never settles and the optimistic write never rolls back. Encoding is cheap;
3404
- * the flush is the slow reconnect path.
3405
- */
3406
- encodableOrSettleTerminal(items) {
3407
- const encodable = [];
3408
- for (const item of items) {
3409
- try {
3410
- encodeCallArgs(item.args, `args for '${item.functionPath}'`);
3411
- encodable.push(item);
3412
- } catch (error) {
3413
- this.settleReplayTerminal(item, error instanceof Error ? error : new Error(String(error)));
3414
- }
3415
- }
3416
- return encodable;
3417
- }
3418
- /**
3419
- * Identity guard for one queued write about to replay: a write stamped under
3420
- * one identity must never replay under another. The live `queuedIdentities`
3421
- * map is the source of truth for the current session; a hydrated write whose
3422
- * id isn't in the map falls back to the stamp persisted with the record
3423
- * (`item.identity`), so a reload can't replay another user's queued writes.
3424
- * Only legacy records (persisted before stamps were durable —
3425
- * `item.identity === undefined`) replay under whatever identity is current.
3426
- *
3427
- * `Map.get` returns `undefined` for unstamped/hydrated ids and `item.identity`
3428
- * is `undefined` for legacy records; a persisted `null` (queued while signed
3429
- * out) is a real value that must not collapse into `undefined` — hence the
3430
- * explicit `=== undefined` check rather than `??`. Returns `true` when the
3431
- * write may replay; otherwise settles it `OFFLINE_IDENTITY_CHANGED` and returns
3432
- * `false`. Either way the live stamp is consumed.
3433
- */
3434
- passesReplayIdentityGate(item, currentIdentity) {
3435
- const liveStamp = item.id === void 0 ? void 0 : this.queuedIdentities.get(item.id);
3436
- const stamped = liveStamp === void 0 ? item.identity : liveStamp;
3437
- if (stamped !== void 0 && stamped !== currentIdentity && !this.isSameCredentialUnderTokenHash(stamped)) {
3438
- this.queuedIdentities.delete(item.id ?? "");
3439
- this.unpersist(item.id);
3440
- const error = new Error("offline mutation skipped: auth identity changed before replay");
3441
- error.code = "OFFLINE_IDENTITY_CHANGED";
3442
- item.reject(error);
3443
- this.emitItemSettled(item, "rejected", error);
3444
- return false;
3445
- }
3446
- this.queuedIdentities.delete(item.id ?? "");
3447
- return true;
3448
- }
3449
- /** Settle a write that replayed successfully: confirm its optimistic layer against the echoed commit cursor BEFORE resolving, so the gapless drop is in place when the awaiter (and any confirming frame) observes the settle. */
3450
- settleReplaySuccess(item, value, commitCursor) {
3451
- this.unpersist(item.id);
3452
- item.onCommit?.(commitCursor);
3453
- item.resolve(value);
3454
- this.emitItemSettled(item, "committed");
3455
- }
3456
- /** Settle a write the server reached a coded verdict on: replaying would re-trigger the same failure (a poison-message loop), so drop it. */
3457
- settleReplayTerminal(item, error) {
3458
- this.unpersist(item.id);
3459
- item.reject(error);
3460
- this.emitItemSettled(item, "rejected", error);
3461
- }
3462
- /**
3463
- * Replay already-identity-gated writes one at a time on the single-call `/rpc`
3464
- * path, preserving FIFO order (parallel `.then()` chains would race the
3465
- * ordering callers depend on). Each replays under its stable `mutationId` so
3466
- * the server dedups a write it already committed (exactly-once). A coded error
3467
- * is a server verdict (drop it); a codeless (transport/transient) failure stops
3468
- * the flush and re-queues this write and every unreplayed one for the next
3469
- * reconnect — their callers stay pending, and the identity guard re-applies on
3470
- * retry via each record's persisted stamp.
3471
- */
3472
- async replaySequential(items) {
3473
- for (let index = 0; index < items.length; index += 1) {
3474
- const item = items[index];
3475
- if (!item) {
3476
- continue;
3477
- }
3478
- try {
3479
- let commitCursor;
3480
- const value = await this.rpc(item.functionPath, item.args, item.shardKey, {
3481
- captureBookmark: true,
3482
- mutationId: item.id,
3483
- onCommitCursor: (cursor) => {
3484
- commitCursor = cursor;
3485
- }
3486
- });
3487
- this.settleReplaySuccess(item, value, commitCursor);
3488
- } catch (error) {
3489
- if (error.code !== void 0) {
3490
- this.settleReplayTerminal(item, error);
3491
- continue;
3492
- }
3493
- this.offlineQueue.requeue(items.slice(index));
3494
- return;
3495
- }
3496
- }
3497
- }
3498
- /**
3499
- * Coalesce already-identity-gated writes for a single shard into ONE
3500
- * `/_lunora/rpc-batch` round trip (plan 088 follow-on). The worker forwards
3501
- * them to the shard DO, which replays each through its single-call dispatch, so
3502
- * per-entry `mutationId` idempotency and in-order application are inherited from
3503
- * the proven path. Per-slot demux mirrors {@link replaySequential}'s
3504
- * classification: success confirms the optimistic layer against the echoed
3505
- * `commitCursor`; a coded application verdict is terminal; a transient shard
3506
- * failure (`SHARD_UNAVAILABLE`/`SHARD_ERROR`), a missing slot, or a whole-batch
3507
- * transport failure re-queues for the next reconnect (never dropping a durable
3508
- * write). A whole-batch coded rejection (bad request / authorization denial the
3509
- * server reached a verdict on) is terminal for every entry.
3510
- *
3511
- * Returns the writes that must be re-queued and `stop` — `true` when the whole
3512
- * chunk failed at the transport level, so the caller leaves later chunks queued
3513
- * rather than sending on. The caller re-queues once, in order, so requeuing is
3514
- * NOT done here.
3515
- */
3516
- async replayBatched(items) {
3517
- if (!this.fetchImpl) {
3518
- return { requeue: items, stop: true };
3519
- }
3520
- let response;
3521
- try {
3522
- response = await this.fetchImpl(joinUrl(this.url, RPC_BATCH_PATH), {
3523
- body: JSON.stringify({
3524
- calls: items.map((item, index) => {
3525
- return {
3526
- args: encodeCallArgs(item.args, `args for '${item.functionPath}'`),
3527
- functionPath: item.functionPath,
3528
- id: index,
3529
- // Stable per-write key so the DO dedups a write it already
3530
- // committed (exactly-once), exactly as the single-call replay.
3531
- mutationId: item.id,
3532
- shardKey: item.shardKey
3533
- };
3534
- })
3535
- }),
3536
- headers: this.rpcRequestHeaders({ attachBookmark: true }),
3537
- method: "POST"
3538
- });
3539
- } catch {
3540
- return { requeue: items, stop: true };
3541
- }
3542
- const bookmark = response.headers.get("x-d1-bookmark");
3543
- if (bookmark) {
3544
- this.bookmark.set(bookmark);
3545
- }
3546
- let body;
3547
- try {
3548
- body = await response.json();
3549
- } catch {
3550
- return { requeue: items, stop: true };
3551
- }
3552
- if (!body.results) {
3553
- if (body.error) {
3554
- const error = reconstructError(body.error);
3555
- for (const item of items) {
3556
- this.settleReplayTerminal(item, error);
3557
- }
3558
- return { requeue: [], stop: false };
3559
- }
3560
- return { requeue: items, stop: true };
3561
- }
3562
- return { requeue: this.settleReplayBatchSlots(items, body.results), stop: false };
3563
- }
3564
- /**
3565
- * Demux a `/_lunora/rpc-batch` reply back onto the queued writes it replayed,
3566
- * in input order. Each slot's envelope classifies its write the same way
3567
- * {@link replaySequential} does: a success confirms the optimistic layer
3568
- * against the echoed `commitCursor`; a coded application verdict is terminal;
3569
- * a transient shard failure ({@link TRANSIENT_BATCH_ERROR_CODES}) or a slot the
3570
- * server never returned is returned for the caller to re-queue.
3571
- * @returns the writes that must be re-queued (transient slots), in input order
3572
- */
3573
- settleReplayBatchSlots(items, results) {
3574
- const bySlot = /* @__PURE__ */ new Map();
3575
- for (const entry of results) {
3576
- if (typeof entry.id === "number" && entry.body !== void 0) {
3577
- bySlot.set(entry.id, entry.body);
3578
- }
3579
- }
3580
- const requeue = [];
3581
- for (const [index, item] of items.entries()) {
3582
- const inner = bySlot.get(index);
3583
- if (inner === void 0) {
3584
- requeue.push(item);
3585
- } else if ("error" in inner) {
3586
- if (TRANSIENT_BATCH_ERROR_CODES.has(inner.error.code)) {
3587
- requeue.push(item);
3588
- } else {
3589
- this.settleReplayTerminal(item, reconstructError(inner.error));
3590
- }
3591
- } else {
3592
- this.settleReplaySuccess(item, decodeWire(inner.result), inner.commitCursor);
3593
- }
3594
- }
3595
- return requeue;
3596
- }
3597
- }
3598
-
3599
- export { LunoraClient };