@lunora/client 1.0.0-alpha.18 → 1.0.0-alpha.180

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