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

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