@lunora/client 1.0.0-alpha.22 → 1.0.0-alpha.221

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