@lunora/client 1.0.0-alpha.15 → 1.0.0-alpha.150

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