@lunora/client 1.0.0-alpha.21 → 1.0.0-alpha.210

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