@lunora/client 1.0.0-alpha.16 → 1.0.0-alpha.160

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