@tapedb/tapedb 0.0.0-stage → 0.1.0

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.
package/dist/index.js ADDED
@@ -0,0 +1,3007 @@
1
+ import {
2
+ cloneJson,
3
+ stableStringify
4
+ } from "./chunk-UYZJAMBR.js";
5
+ import {
6
+ MAX_SOCKET_MESSAGE_BYTES,
7
+ MAX_SOCKET_MESSAGE_PARTS,
8
+ MAX_SOCKET_PENDING_BYTES,
9
+ socketProtocols
10
+ } from "./chunk-CYDXFAEB.js";
11
+ import {
12
+ check,
13
+ filter,
14
+ findLinkByApiName,
15
+ model,
16
+ role,
17
+ schema,
18
+ shapeFor,
19
+ t,
20
+ toEngineNode,
21
+ toEngineWhere
22
+ } from "./chunk-VWW5OS5B.js";
23
+ import {
24
+ WORKSPACE_ROLE_LEVELS,
25
+ hasRole,
26
+ hasRoleLevel
27
+ } from "./chunk-3AL32Q4K.js";
28
+
29
+ // src/client/id.ts
30
+ function randomBytes(length) {
31
+ const crypto2 = globalThis.crypto;
32
+ if (crypto2 && typeof crypto2.getRandomValues === "function") {
33
+ return crypto2.getRandomValues(new Uint8Array(length));
34
+ }
35
+ return null;
36
+ }
37
+ function formatUuid(bytes) {
38
+ let hex = "";
39
+ for (const byte of bytes) {
40
+ hex += byte.toString(16).padStart(2, "0");
41
+ }
42
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(
43
+ 12,
44
+ 16
45
+ )}-${hex.slice(16, 20)}-${hex.slice(20)}`;
46
+ }
47
+ function fallbackId() {
48
+ const crypto2 = globalThis.crypto;
49
+ if (crypto2 && typeof crypto2.randomUUID === "function") {
50
+ return crypto2.randomUUID();
51
+ }
52
+ const bytes = new Uint8Array(16);
53
+ for (let index = 0; index < bytes.length; index += 1) {
54
+ bytes[index] = Math.floor(Math.random() * 256);
55
+ }
56
+ bytes[6] = bytes[6] & 15 | 64;
57
+ bytes[8] = bytes[8] & 63 | 128;
58
+ return formatUuid(bytes);
59
+ }
60
+ var lastMs = -1;
61
+ var counter = 0;
62
+ function id() {
63
+ const random = randomBytes(10);
64
+ if (!random) return fallbackId();
65
+ const bytes = new Uint8Array(16);
66
+ let now = Date.now();
67
+ if (now > lastMs) {
68
+ lastMs = now;
69
+ counter = (random[0] << 8 | random[1]) & 2047;
70
+ } else {
71
+ now = lastMs;
72
+ counter += 1;
73
+ if (counter > 4095) {
74
+ lastMs += 1;
75
+ now = lastMs;
76
+ counter = 0;
77
+ }
78
+ }
79
+ bytes[0] = Math.floor(now / 2 ** 40) & 255;
80
+ bytes[1] = Math.floor(now / 2 ** 32) & 255;
81
+ bytes[2] = Math.floor(now / 2 ** 24) & 255;
82
+ bytes[3] = Math.floor(now / 2 ** 16) & 255;
83
+ bytes[4] = Math.floor(now / 2 ** 8) & 255;
84
+ bytes[5] = now & 255;
85
+ bytes.set(random, 6);
86
+ bytes[6] = 112 | counter >> 8 & 15;
87
+ bytes[7] = counter & 255;
88
+ bytes[8] = bytes[8] & 63 | 128;
89
+ return formatUuid(bytes);
90
+ }
91
+
92
+ // src/client/recovering.ts
93
+ var RECOVERING_WAIT_MS = 6e4;
94
+ var MAX_PAUSE_MS = 5e3;
95
+ var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
96
+ function pauseFor(response) {
97
+ const header = response.headers?.get("retry-after");
98
+ const seconds = header === null || header === void 0 ? NaN : Number(header);
99
+ return Math.min(MAX_PAUSE_MS, Number.isFinite(seconds) && seconds > 0 ? seconds * 1e3 : 1e3);
100
+ }
101
+ function retryWhileRecovering(fetchImpl, options = {}) {
102
+ const waitMs = options.waitMs ?? RECOVERING_WAIT_MS;
103
+ const sleep = options.sleep ?? defaultSleep;
104
+ const now = options.now ?? Date.now;
105
+ return async (url, init) => {
106
+ const started = now();
107
+ for (; ; ) {
108
+ const response = await fetchImpl(url, init);
109
+ if (response.status !== 503 || typeof ReadableStream !== "undefined" && init.body instanceof ReadableStream) {
110
+ return response;
111
+ }
112
+ const payload = await response.json().catch(() => null);
113
+ const code = payload?.error?.code;
114
+ const answered = {
115
+ ok: response.ok,
116
+ status: response.status,
117
+ statusText: response.statusText ?? "",
118
+ headers: response.headers,
119
+ body: null,
120
+ json: async () => payload,
121
+ text: async () => payload === null ? "" : JSON.stringify(payload)
122
+ };
123
+ if (code !== "workspace_recovering") return answered;
124
+ const pause = pauseFor(response);
125
+ if (now() - started + pause > waitMs) return answered;
126
+ await sleep(pause);
127
+ }
128
+ };
129
+ }
130
+
131
+ // src/client/storage-client.ts
132
+ var UPLOAD_PART_BYTES = 16 * 1024 * 1024;
133
+ var StorageError = class extends Error {
134
+ constructor(status, code) {
135
+ super(`Storage request failed (${status}, ${code}).`);
136
+ this.status = status;
137
+ this.code = code;
138
+ this.name = "StorageError";
139
+ }
140
+ status;
141
+ code;
142
+ };
143
+ function createStorageClient(config) {
144
+ const scope = config.workspaceId ?? config.appId;
145
+ if (!scope || Boolean(config.workspaceId) === Boolean(config.appId) || !/^[A-Za-z0-9_-]{1,64}$/.test(scope))
146
+ throw new Error("Storage requires a valid registered app id.");
147
+ const base = new URL(config.apiUrl);
148
+ if (!/^https?:$/.test(base.protocol) || base.username || base.password || base.search || base.hash)
149
+ throw new Error(
150
+ "Storage requires an HTTP(S) API URL without credentials, query or fragment."
151
+ );
152
+ const fetcher = retryWhileRecovering(
153
+ (input, init) => (config.fetch ?? globalThis.fetch)(input, init),
154
+ config.recoveringRetry
155
+ );
156
+ const url = (path) => {
157
+ if (!/^[A-Za-z0-9!_.*'()/-]{1,512}$/.test(path) || path.split("/").some((part) => !part || part === "." || part === ".."))
158
+ throw new Error("Invalid storage object path.");
159
+ return `${base.href.replace(/\/+$/, "")}/${config.workspaceId ? `engine/workspaces/${scope}/files` : `storage/${scope}`}/${path.split("/").map(encodeURIComponent).join("/")}`;
160
+ };
161
+ async function request(path, method, body, signal, query = "", contentType) {
162
+ const target = `${url(path)}${query}`;
163
+ const token = await config.getToken();
164
+ if (!token) throw new Error("Storage requires a workspace claim.");
165
+ const response = await fetcher(target, {
166
+ method,
167
+ body,
168
+ signal,
169
+ credentials: "omit",
170
+ cache: "no-store",
171
+ redirect: "error",
172
+ headers: {
173
+ authorization: `Bearer ${token}`,
174
+ ...contentType !== void 0 ? { "content-type": contentType } : body ? { "content-type": body.type || "application/octet-stream" } : {}
175
+ }
176
+ });
177
+ if (!response.ok) {
178
+ const error = await response.json().catch(() => null);
179
+ throw new StorageError(
180
+ response.status,
181
+ typeof error?.error?.code === "string" ? error.error.code : "storage_request_failed"
182
+ );
183
+ }
184
+ return response;
185
+ }
186
+ return {
187
+ async upload(path, file, signal) {
188
+ if (file.size <= UPLOAD_PART_BYTES) {
189
+ return (await request(path, "PUT", file, signal)).json();
190
+ }
191
+ const type = file.type || "application/octet-stream";
192
+ const { uploadId } = await (await request(path, "POST", void 0, signal, "?uploads", type)).json();
193
+ const id2 = encodeURIComponent(uploadId);
194
+ try {
195
+ const parts = [];
196
+ for (let offset = 0, partNumber = 1; offset < file.size; offset += UPLOAD_PART_BYTES, partNumber += 1) {
197
+ const chunk = file.slice(offset, Math.min(offset + UPLOAD_PART_BYTES, file.size));
198
+ const response = await request(path, "PUT", chunk, signal, `?uploadId=${id2}&partNumber=${partNumber}`, "application/octet-stream");
199
+ parts.push(await response.json());
200
+ }
201
+ const done = new Blob([JSON.stringify({ parts })], { type: "application/json" });
202
+ return (await request(path, "POST", done, signal, `?uploadId=${id2}`)).json();
203
+ } catch (error) {
204
+ await request(path, "DELETE", void 0, void 0, `?uploadId=${id2}`).catch(() => void 0);
205
+ throw error;
206
+ }
207
+ },
208
+ async download(path, signal) {
209
+ return (await request(path, "GET", void 0, signal)).blob();
210
+ },
211
+ async delete(path, signal) {
212
+ await request(path, "DELETE", void 0, signal);
213
+ }
214
+ };
215
+ }
216
+
217
+ // src/client/outbox.ts
218
+ var OUTBOX_DB_NAME = "tapedb-data-outbox";
219
+ var OUTBOX_STORE_NAME = "pending";
220
+ function scopedOutboxName(apiUrl, userId) {
221
+ return `${OUTBOX_DB_NAME}:v2:${JSON.stringify([apiUrl.replace(/\/+$/, ""), userId === void 0 ? ["development"] : ["user", userId]])}`;
222
+ }
223
+ function indexedDbAvailable() {
224
+ return defaultIndexedDb() !== null;
225
+ }
226
+ function sortEntries(entries) {
227
+ return [...entries].sort(
228
+ (left, right) => left.createdAt - right.createdAt || left.clientTxId.localeCompare(right.clientTxId)
229
+ );
230
+ }
231
+ function isOutboxEntry(value) {
232
+ if (typeof value !== "object" || value === null) return false;
233
+ const candidate = value;
234
+ return typeof candidate.clientTxId === "string" && typeof candidate.txId === "string" && typeof candidate.workspaceId === "string" && Array.isArray(candidate.ops) && typeof candidate.createdAt === "number";
235
+ }
236
+ var MemoryOutbox = class {
237
+ entries = /* @__PURE__ */ new Map();
238
+ async add(entry) {
239
+ this.entries.set(entry.clientTxId, entry);
240
+ }
241
+ async list(workspaceId) {
242
+ return sortEntries(
243
+ [...this.entries.values()].filter(
244
+ (entry) => entry.workspaceId === workspaceId
245
+ )
246
+ );
247
+ }
248
+ async remove(clientTxId) {
249
+ this.entries.delete(clientTxId);
250
+ }
251
+ async clear(workspaceId) {
252
+ if (workspaceId === void 0) {
253
+ this.entries.clear();
254
+ return;
255
+ }
256
+ for (const [clientTxId, entry] of this.entries) {
257
+ if (entry.workspaceId === workspaceId) this.entries.delete(clientTxId);
258
+ }
259
+ }
260
+ };
261
+ var IndexedDbOutbox = class {
262
+ factory;
263
+ dbName;
264
+ openPromise = null;
265
+ fallback = new MemoryOutbox();
266
+ constructor(factory, dbName) {
267
+ this.factory = factory;
268
+ this.dbName = dbName;
269
+ }
270
+ async add(entry) {
271
+ try {
272
+ await this.request("readwrite", (store) => store.put(entry));
273
+ await this.fallback.remove(entry.clientTxId);
274
+ } catch {
275
+ await this.fallback.add(entry);
276
+ }
277
+ }
278
+ async list(workspaceId) {
279
+ try {
280
+ const values = await this.request(
281
+ "readonly",
282
+ (store) => store.getAll()
283
+ );
284
+ return sortEntries(
285
+ [...new Map([
286
+ ...values.filter(isOutboxEntry).filter((entry) => entry.workspaceId === workspaceId),
287
+ ...await this.fallback.list(workspaceId)
288
+ ].map((entry) => [entry.clientTxId, entry])).values()]
289
+ );
290
+ } catch {
291
+ return this.fallback.list(workspaceId);
292
+ }
293
+ }
294
+ async remove(clientTxId) {
295
+ await this.fallback.remove(clientTxId);
296
+ try {
297
+ await this.request("readwrite", (store) => store.delete(clientTxId));
298
+ } catch {
299
+ await this.fallback.remove(clientTxId);
300
+ }
301
+ }
302
+ async clear(workspaceId) {
303
+ await this.fallback.clear(workspaceId);
304
+ try {
305
+ if (workspaceId === void 0) {
306
+ await this.request("readwrite", (store) => store.clear());
307
+ return;
308
+ }
309
+ const values = await this.request(
310
+ "readonly",
311
+ (store) => store.getAll()
312
+ );
313
+ const clientTxIds = values.filter(isOutboxEntry).filter((entry) => entry.workspaceId === workspaceId).map((entry) => entry.clientTxId);
314
+ for (const clientTxId of clientTxIds) {
315
+ await this.request("readwrite", (store) => store.delete(clientTxId));
316
+ }
317
+ } catch {
318
+ await this.fallback.clear(workspaceId);
319
+ }
320
+ }
321
+ open() {
322
+ if (this.openPromise) return this.openPromise;
323
+ this.openPromise = new Promise((resolve, reject) => {
324
+ let request;
325
+ try {
326
+ request = this.factory.open(this.dbName, 1);
327
+ } catch (error) {
328
+ reject(error);
329
+ return;
330
+ }
331
+ request.onupgradeneeded = () => {
332
+ const db = request.result;
333
+ if (!db.objectStoreNames.contains(OUTBOX_STORE_NAME)) {
334
+ db.createObjectStore(OUTBOX_STORE_NAME, { keyPath: "clientTxId" });
335
+ }
336
+ };
337
+ request.onsuccess = () => resolve(request.result);
338
+ request.onerror = () => reject(request.error ?? new Error("IndexedDB open failed."));
339
+ request.onblocked = () => reject(new Error("IndexedDB open was blocked."));
340
+ });
341
+ return this.openPromise;
342
+ }
343
+ async request(mode, run) {
344
+ const db = await this.open();
345
+ return new Promise((resolve, reject) => {
346
+ let transaction;
347
+ try {
348
+ transaction = db.transaction(OUTBOX_STORE_NAME, mode);
349
+ } catch (error) {
350
+ reject(error);
351
+ return;
352
+ }
353
+ const request = run(transaction.objectStore(OUTBOX_STORE_NAME));
354
+ let result;
355
+ request.onsuccess = () => {
356
+ result = request.result;
357
+ };
358
+ transaction.oncomplete = () => resolve(result);
359
+ request.onerror = () => reject(request.error ?? new Error("IndexedDB request failed."));
360
+ transaction.onerror = () => reject(transaction.error ?? new Error("IndexedDB transaction failed."));
361
+ transaction.onabort = () => reject(
362
+ transaction.error ?? new Error("IndexedDB transaction aborted.")
363
+ );
364
+ });
365
+ }
366
+ };
367
+ function defaultIndexedDb() {
368
+ try {
369
+ return typeof indexedDB === "undefined" ? null : indexedDB;
370
+ } catch {
371
+ return null;
372
+ }
373
+ }
374
+ function createOutbox(options = {}) {
375
+ const factory = options.indexedDB === void 0 ? defaultIndexedDb() : options.indexedDB;
376
+ if (!factory) return new MemoryOutbox();
377
+ return new IndexedDbOutbox(factory, options.dbName ?? OUTBOX_DB_NAME);
378
+ }
379
+
380
+ // src/client/local-where.ts
381
+ function and(values) {
382
+ if (values.some((value) => value === false)) return false;
383
+ return values.every((value) => value === true) ? true : void 0;
384
+ }
385
+ function or(values) {
386
+ if (values.some((value) => value === true)) return true;
387
+ return values.every((value) => value === false) ? false : void 0;
388
+ }
389
+ function not(value) {
390
+ return value === void 0 ? void 0 : !value;
391
+ }
392
+ function plain(value) {
393
+ return typeof value === "object" && value !== null && !Array.isArray(value);
394
+ }
395
+ var UNKNOWN = /* @__PURE__ */ Symbol("unknown");
396
+ function comparable(value) {
397
+ if (value === void 0 || value === null) return null;
398
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
399
+ return UNKNOWN;
400
+ }
401
+ function same(stored, wanted) {
402
+ if (stored === null || wanted === null) return stored === wanted;
403
+ const left = typeof stored === "boolean" ? Number(stored) : stored;
404
+ const right = typeof wanted === "boolean" ? Number(wanted) : wanted;
405
+ if (typeof left !== typeof right) return void 0;
406
+ return left === right;
407
+ }
408
+ var ASCII = /^[\x00-\x7f]*$/;
409
+ function order(stored, operand, operator) {
410
+ if (stored === null) return false;
411
+ if (operand === null) return void 0;
412
+ const left = typeof stored === "boolean" ? Number(stored) : stored;
413
+ const right = typeof operand === "boolean" ? Number(operand) : operand;
414
+ if (typeof left !== typeof right) return void 0;
415
+ if (typeof left === "string" && !(ASCII.test(left) && ASCII.test(right))) return void 0;
416
+ switch (operator) {
417
+ case "$gt":
418
+ return left > right;
419
+ case "$gte":
420
+ return left >= right;
421
+ case "$lt":
422
+ return left < right;
423
+ case "$lte":
424
+ return left <= right;
425
+ }
426
+ return void 0;
427
+ }
428
+ function field(row, name, condition) {
429
+ if (!(name in row)) return void 0;
430
+ const stored = comparable(row[name]);
431
+ if (stored === UNKNOWN) return void 0;
432
+ if (!plain(condition)) {
433
+ const wanted = comparable(condition);
434
+ return wanted === UNKNOWN ? void 0 : same(stored, wanted);
435
+ }
436
+ const results = [];
437
+ for (const [operator, operand] of Object.entries(condition)) {
438
+ if (operand === void 0) continue;
439
+ if (operator === "$in" || operator === "$nin") {
440
+ if (!Array.isArray(operand)) return void 0;
441
+ const items = operand.map(comparable);
442
+ if (items.some((item) => item === UNKNOWN)) return void 0;
443
+ const hit = or(items.map((item) => same(stored, item)));
444
+ if (operator === "$in") results.push(hit);
445
+ else results.push(stored === null ? !items.includes(null) : not(hit));
446
+ continue;
447
+ }
448
+ const value = comparable(operand);
449
+ if (value === UNKNOWN) return void 0;
450
+ if (operator === "$ne") results.push(value === null ? stored !== null : stored === null ? true : not(same(stored, value)));
451
+ else if (operator === "$eq") results.push(same(stored, value));
452
+ else if (["$gt", "$gte", "$lt", "$lte"].includes(operator)) results.push(order(stored, value, operator));
453
+ else return void 0;
454
+ }
455
+ return and(results);
456
+ }
457
+ function matchesWhere(row, where) {
458
+ if (where === void 0) return true;
459
+ if (!plain(where)) return void 0;
460
+ const results = [];
461
+ for (const [key, value] of Object.entries(where)) {
462
+ if (value === void 0) continue;
463
+ if (key === "$and") {
464
+ if (!Array.isArray(value)) return void 0;
465
+ results.push(and(value.map((branch) => matchesWhere(row, branch))));
466
+ } else if (key === "$or") {
467
+ if (!Array.isArray(value)) return void 0;
468
+ results.push(or(value.map((branch) => matchesWhere(row, branch))));
469
+ } else if (key === "$not") {
470
+ results.push(not(matchesWhere(row, value)));
471
+ } else if (key.startsWith("$")) {
472
+ results.push(void 0);
473
+ } else {
474
+ results.push(field(row, key, value));
475
+ }
476
+ }
477
+ return and(results);
478
+ }
479
+
480
+ // src/client/query-cache.ts
481
+ function entityId(value) {
482
+ if (typeof value !== "object" || value === null) return void 0;
483
+ const id2 = value.id;
484
+ return typeof id2 === "string" && id2.length > 0 ? id2 : void 0;
485
+ }
486
+ function asEntity(value) {
487
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
488
+ return void 0;
489
+ }
490
+ const entity = value;
491
+ return entityId(entity) === void 0 ? void 0 : entity;
492
+ }
493
+ function isRecord(value) {
494
+ return typeof value === "object" && value !== null && !Array.isArray(value);
495
+ }
496
+ function applyQueryDiff(data, diff) {
497
+ const previous = Array.isArray(data[diff.namespace]) ? data[diff.namespace] : [];
498
+ const byId = /* @__PURE__ */ new Map();
499
+ for (const entity of previous) {
500
+ const id2 = entityId(entity);
501
+ if (id2 !== void 0) byId.set(id2, entity);
502
+ }
503
+ for (const removedId of diff.removed) byId.delete(removedId);
504
+ const order2 = [];
505
+ const seen = /* @__PURE__ */ new Set();
506
+ for (const entity of previous) {
507
+ const id2 = entityId(entity);
508
+ if (id2 === void 0 || !byId.has(id2) || seen.has(id2)) continue;
509
+ order2.push(id2);
510
+ seen.add(id2);
511
+ }
512
+ for (const value of [...diff.added, ...diff.updated]) {
513
+ const entity = asEntity(value);
514
+ if (!entity) continue;
515
+ const id2 = entityId(entity);
516
+ byId.set(id2, entity);
517
+ if (!seen.has(id2)) {
518
+ order2.push(id2);
519
+ seen.add(id2);
520
+ }
521
+ }
522
+ if (diff.order !== void 0) {
523
+ const rank = new Map(diff.order.map((id2, index) => [id2, index]));
524
+ const unlisted = order2.filter((id2) => !rank.has(id2));
525
+ order2.length = 0;
526
+ order2.push(...diff.order.filter((id2) => byId.has(id2)), ...unlisted);
527
+ }
528
+ const next = order2.map((id2) => byId.get(id2)).filter((entity) => entity !== void 0);
529
+ return { ...data, [diff.namespace]: next };
530
+ }
531
+ function applyOptimisticOps(data, ops, schema2) {
532
+ let next = cloneJson(data);
533
+ const pendingValues = /* @__PURE__ */ new Map();
534
+ for (const op of ops) {
535
+ if (op.op === "link" || op.op === "unlink" || op.op === "delete" || op.op === "patchMany" || op.op === "deleteMany") {
536
+ continue;
537
+ }
538
+ pendingValues.set(op.id, {
539
+ ...pendingValues.get(op.id) ?? {},
540
+ ...op.op === "upsert" ? op.create : {},
541
+ ...op.values
542
+ });
543
+ }
544
+ for (const op of ops) {
545
+ next = applyOptimisticOp(next, op, schema2, pendingValues);
546
+ }
547
+ return next;
548
+ }
549
+ function applyOptimisticOp(data, op, schema2, pendingValues) {
550
+ switch (op.op) {
551
+ // Which rows a bulk write matches is the engine's answer. The cache
552
+ // changes the rows it holds that certainly match; rows whose match it
553
+ // cannot judge (a relation filter, a field it does not hold) wait for the
554
+ // engine's push, which also settles everything here.
555
+ case "patchMany":
556
+ case "deleteMany":
557
+ for (const id2 of certainMatches(data, op.namespace, op.where)) {
558
+ if (op.op === "deleteMany") removeEntity(data, op.namespace, id2);
559
+ else applyValues(data, op.namespace, id2, op.values);
560
+ }
561
+ return data;
562
+ case "insert":
563
+ case "patch":
564
+ case "update":
565
+ case "merge":
566
+ applyValues(data, op.namespace, op.id, op.values);
567
+ return data;
568
+ case "upsert":
569
+ applyValues(
570
+ data,
571
+ op.namespace,
572
+ op.id,
573
+ findEntity(data, op.id) === void 0 ? op.create : op.values
574
+ );
575
+ return data;
576
+ case "delete":
577
+ removeEntity(data, op.namespace, op.id);
578
+ return data;
579
+ case "link":
580
+ applyLink(data, op, schema2, true, pendingValues);
581
+ return data;
582
+ case "unlink":
583
+ applyLink(data, op, schema2, false, pendingValues);
584
+ return data;
585
+ }
586
+ }
587
+ function certainMatches(data, namespace, where) {
588
+ const entities = data[namespace];
589
+ if (!Array.isArray(entities)) return [];
590
+ return entities.filter((entity) => matchesWhere(entity, where) === true).map((entity) => entityId(entity)).filter((id2) => typeof id2 === "string");
591
+ }
592
+ function applyValues(data, namespace, id2, values) {
593
+ const entities = data[namespace];
594
+ if (Array.isArray(entities)) {
595
+ const index = entities.findIndex((entity) => entityId(entity) === id2);
596
+ if (index >= 0) {
597
+ entities[index] = { ...entities[index], ...values, id: id2 };
598
+ } else {
599
+ entities.push({ id: id2, ...values });
600
+ }
601
+ }
602
+ updateOccurrences(data, id2, values);
603
+ }
604
+ function removeEntity(data, namespace, id2) {
605
+ const entities = data[namespace];
606
+ if (Array.isArray(entities)) {
607
+ data[namespace] = entities.filter((entity) => entityId(entity) !== id2);
608
+ }
609
+ removeOccurrences(data, id2);
610
+ }
611
+ function applyLink(data, op, schema2, linked, pendingValues) {
612
+ const definition = findLinkByApiName(schema2, op.link);
613
+ if (!definition) return;
614
+ const { forward, reverse } = definition;
615
+ let parentId;
616
+ let childId;
617
+ if (op.namespace === forward.on) {
618
+ parentId = op.id;
619
+ childId = op.targetId;
620
+ } else if (op.namespace === reverse.on) {
621
+ parentId = op.targetId;
622
+ childId = op.id;
623
+ } else {
624
+ return;
625
+ }
626
+ const foreignKeyAttribute = `${reverse.label}Id`;
627
+ const foreignKeyValue = linked ? parentId : null;
628
+ const values = pendingValues?.get(childId) ?? {};
629
+ updateOccurrences(data, childId, {
630
+ ...values,
631
+ [foreignKeyAttribute]: foreignKeyValue
632
+ });
633
+ const childEntities = data[reverse.on];
634
+ if (Array.isArray(childEntities)) {
635
+ const exists = childEntities.some((entity) => entityId(entity) === childId);
636
+ if (!exists) {
637
+ childEntities.push({
638
+ id: childId,
639
+ ...values,
640
+ [foreignKeyAttribute]: foreignKeyValue
641
+ });
642
+ }
643
+ }
644
+ const child = findEntity(data, childId) ?? {
645
+ id: childId,
646
+ ...values,
647
+ [foreignKeyAttribute]: foreignKeyValue
648
+ };
649
+ if (linked && forward.has === "many") {
650
+ detachFromLabel(data, forward.label, childId);
651
+ }
652
+ for (const parent of findEntities(data, parentId)) {
653
+ if (forward.has === "many") {
654
+ const current = parent[forward.label];
655
+ const list = Array.isArray(current) ? current.filter((entity) => entityId(entity) !== childId) : [];
656
+ if (linked) list.push({ ...child });
657
+ parent[forward.label] = list;
658
+ } else {
659
+ parent[forward.label] = linked ? { ...child } : null;
660
+ }
661
+ }
662
+ }
663
+ function detachFromLabel(node, label, childId) {
664
+ if (Array.isArray(node)) {
665
+ for (const item of node) detachFromLabel(item, label, childId);
666
+ return;
667
+ }
668
+ if (!isRecord(node)) return;
669
+ for (const [key, value] of Object.entries(node)) {
670
+ if (key === label && Array.isArray(value)) {
671
+ node[key] = value.filter((entry) => entityId(entry) !== childId);
672
+ continue;
673
+ }
674
+ if (typeof value === "object" && value !== null) {
675
+ detachFromLabel(value, label, childId);
676
+ }
677
+ }
678
+ }
679
+ function updateOccurrences(node, id2, values) {
680
+ if (Array.isArray(node)) {
681
+ for (const item of node) updateOccurrences(item, id2, values);
682
+ return;
683
+ }
684
+ if (!isRecord(node)) return;
685
+ if (node.id === id2) Object.assign(node, values);
686
+ for (const [key, value] of Object.entries(node)) {
687
+ if (key === "id") continue;
688
+ if (typeof value === "object" && value !== null) {
689
+ updateOccurrences(value, id2, values);
690
+ }
691
+ }
692
+ }
693
+ function removeOccurrences(node, id2) {
694
+ if (Array.isArray(node)) {
695
+ for (let index = node.length - 1; index >= 0; index -= 1) {
696
+ if (entityId(node[index]) === id2) {
697
+ node.splice(index, 1);
698
+ } else {
699
+ removeOccurrences(node[index], id2);
700
+ }
701
+ }
702
+ return;
703
+ }
704
+ if (!isRecord(node)) return;
705
+ for (const [key, value] of Object.entries(node)) {
706
+ if (key === "id") continue;
707
+ if (isRecord(value) && entityId(value) === id2) {
708
+ node[key] = null;
709
+ continue;
710
+ }
711
+ if (typeof value === "object" && value !== null) {
712
+ removeOccurrences(value, id2);
713
+ }
714
+ }
715
+ }
716
+ function findEntity(data, id2) {
717
+ const found = findEntities(data, id2);
718
+ return found[0];
719
+ }
720
+ function findEntities(data, id2) {
721
+ const found = [];
722
+ collectEntities(data, id2, found, /* @__PURE__ */ new Set());
723
+ return found;
724
+ }
725
+ function collectEntities(node, id2, found, visited) {
726
+ if (typeof node !== "object" || node === null) return;
727
+ if (visited.has(node)) return;
728
+ visited.add(node);
729
+ if (Array.isArray(node)) {
730
+ for (const item of node) collectEntities(item, id2, found, visited);
731
+ return;
732
+ }
733
+ const record = node;
734
+ if (record.id === id2) found.push(record);
735
+ for (const value of Object.values(record)) {
736
+ if (typeof value === "object" && value !== null) {
737
+ collectEntities(value, id2, found, visited);
738
+ }
739
+ }
740
+ }
741
+
742
+ // src/client/socket.ts
743
+ var DEFAULT_MIN_RECONNECT_DELAY_MS = 250;
744
+ var DEFAULT_MAX_RECONNECT_DELAY_MS = 5e3;
745
+ function defaultWebSocketFactory() {
746
+ return (url, protocols) => {
747
+ if (typeof WebSocket === "undefined") {
748
+ throw new Error("tapedb-data: WebSocket is not available in this runtime.");
749
+ }
750
+ return new WebSocket(url, protocols);
751
+ };
752
+ }
753
+ var FRAME_PART_CHARS = 256 * 1024;
754
+ function splitText(text, size) {
755
+ const parts = [];
756
+ for (let start = 0; start < text.length; ) {
757
+ let end = Math.min(start + size, text.length);
758
+ const last = text.charCodeAt(end - 1);
759
+ if (end < text.length && last >= 55296 && last <= 56319) end -= 1;
760
+ parts.push(text.slice(start, end));
761
+ start = end;
762
+ }
763
+ return parts;
764
+ }
765
+ function framesFor(message, size = FRAME_PART_CHARS) {
766
+ const text = JSON.stringify(message);
767
+ if (text.length <= size) return [text];
768
+ const id2 = crypto.randomUUID();
769
+ if (message.type === "topic:send" && "message" in message) {
770
+ const parts2 = splitText(JSON.stringify(message.message), size);
771
+ return parts2.map(
772
+ (data, index) => JSON.stringify({
773
+ type: "topic:send",
774
+ topic: message.topic,
775
+ part: { id: id2, index, last: index === parts2.length - 1 },
776
+ data,
777
+ ...message.origin !== void 0 ? { origin: message.origin } : {}
778
+ })
779
+ );
780
+ }
781
+ const parts = splitText(text, size);
782
+ return parts.map((data, index) => JSON.stringify({ type: "part", id: id2, index, last: index === parts.length - 1, data }));
783
+ }
784
+ var TopicParts = class {
785
+ pending = /* @__PURE__ */ new Map();
786
+ take(message) {
787
+ if (!("part" in message)) return message;
788
+ const key = `${message.from.clientId}\0${message.part.id}`;
789
+ const now = Date.now();
790
+ for (const [id2, entry2] of this.pending) if (now - entry2.at > 6e4) this.pending.delete(id2);
791
+ const entry = this.pending.get(key) ?? { next: 0, parts: [], bytes: 0, at: now };
792
+ const bytes = message.data.length > MAX_SOCKET_MESSAGE_BYTES ? MAX_SOCKET_MESSAGE_BYTES + 1 : new TextEncoder().encode(message.data).byteLength;
793
+ const total = [...this.pending.values()].reduce((sum, item) => sum + item.bytes, 0);
794
+ if (entry.next >= MAX_SOCKET_MESSAGE_PARTS || entry.bytes + bytes > MAX_SOCKET_MESSAGE_BYTES || total + bytes > MAX_SOCKET_PENDING_BYTES || !this.pending.has(key) && this.pending.size >= 32) {
795
+ this.pending.delete(key);
796
+ return null;
797
+ }
798
+ entry.bytes += bytes;
799
+ if (message.part.index !== entry.next) {
800
+ this.pending.delete(key);
801
+ return null;
802
+ }
803
+ entry.parts.push(message.data);
804
+ entry.next += 1;
805
+ if (!message.part.last) {
806
+ this.pending.set(key, entry);
807
+ return null;
808
+ }
809
+ this.pending.delete(key);
810
+ try {
811
+ return {
812
+ type: "topic:message",
813
+ topic: message.topic,
814
+ message: JSON.parse(entry.parts.join("")),
815
+ from: message.from,
816
+ // The last part's sequence stands for the whole message.
817
+ ...message.seq !== void 0 ? { seq: message.seq } : {},
818
+ ...message.origin !== void 0 ? { origin: message.origin } : {}
819
+ };
820
+ } catch {
821
+ return null;
822
+ }
823
+ }
824
+ clear() {
825
+ this.pending.clear();
826
+ }
827
+ };
828
+ function parseServerMessage(value) {
829
+ let text = null;
830
+ if (typeof value === "string") {
831
+ text = value;
832
+ } else if (value instanceof ArrayBuffer) {
833
+ text = new TextDecoder().decode(value);
834
+ }
835
+ if (text === null) return null;
836
+ try {
837
+ const parsed = JSON.parse(text);
838
+ if (typeof parsed === "object" && parsed !== null && typeof parsed.type === "string") {
839
+ return parsed;
840
+ }
841
+ } catch {
842
+ }
843
+ return null;
844
+ }
845
+ var QuerySocket = class {
846
+ baseUrl;
847
+ getToken;
848
+ onMessage;
849
+ topicParts = new TopicParts();
850
+ onSessionReady;
851
+ createWebSocket;
852
+ minReconnectDelayMs;
853
+ maxReconnectDelayMs;
854
+ ws = null;
855
+ connectPromise = null;
856
+ retryTimer = null;
857
+ attempt = 0;
858
+ manuallyClosed = false;
859
+ generation = 0;
860
+ cancelPending = null;
861
+ /** True when reconnecting is paused until an explicit `connect()`. */
862
+ suspended = false;
863
+ onlineHandler = null;
864
+ constructor(options) {
865
+ this.baseUrl = options.baseUrl;
866
+ this.getToken = options.getToken;
867
+ this.onMessage = options.onMessage;
868
+ this.onSessionReady = options.onSessionReady;
869
+ this.createWebSocket = options.createWebSocket ?? defaultWebSocketFactory();
870
+ this.minReconnectDelayMs = options.minReconnectDelayMs ?? DEFAULT_MIN_RECONNECT_DELAY_MS;
871
+ this.maxReconnectDelayMs = options.maxReconnectDelayMs ?? DEFAULT_MAX_RECONNECT_DELAY_MS;
872
+ if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
873
+ this.onlineHandler = () => this.reconnectNow();
874
+ window.addEventListener("online", this.onlineHandler);
875
+ }
876
+ }
877
+ get isOpen() {
878
+ return this.ws !== null;
879
+ }
880
+ connect() {
881
+ if (this.connectPromise) return this.connectPromise;
882
+ if (this.ws) return Promise.resolve();
883
+ this.manuallyClosed = false;
884
+ this.suspended = false;
885
+ const generation = ++this.generation;
886
+ this.connectPromise = new Promise((resolve, reject) => {
887
+ this.cancelPending = () => reject(new Error("Connection attempt cancelled."));
888
+ void this.open(generation, () => {
889
+ if (generation === this.generation) this.cancelPending = null;
890
+ resolve();
891
+ }, (error) => {
892
+ if (generation === this.generation) this.cancelPending = null;
893
+ reject(error);
894
+ });
895
+ });
896
+ return this.connectPromise;
897
+ }
898
+ send(message) {
899
+ if (!this.ws) return false;
900
+ try {
901
+ for (const frame of framesFor(message)) this.ws.send(frame);
902
+ return true;
903
+ } catch {
904
+ this.scheduleReconnect();
905
+ return false;
906
+ }
907
+ }
908
+ /**
909
+ * Stops reconnecting without tearing the instance down, so an explicit
910
+ * `connect()` (or an `online` event) can resume later.
911
+ */
912
+ suspend() {
913
+ this.suspended = true;
914
+ this.clearRetryTimer();
915
+ this.cancelOpen();
916
+ const previous = this.ws;
917
+ this.ws = null;
918
+ this.connectPromise = null;
919
+ if (previous) {
920
+ try {
921
+ previous.close();
922
+ } catch {
923
+ }
924
+ }
925
+ }
926
+ reconnectNow() {
927
+ if (this.manuallyClosed) return;
928
+ this.clearRetryTimer();
929
+ this.cancelOpen();
930
+ const previous = this.ws;
931
+ this.ws = null;
932
+ if (previous) {
933
+ try {
934
+ previous.close();
935
+ } catch {
936
+ }
937
+ }
938
+ this.connectPromise = null;
939
+ this.attempt = 0;
940
+ void this.connect().catch(() => {
941
+ });
942
+ }
943
+ close() {
944
+ this.manuallyClosed = true;
945
+ this.clearRetryTimer();
946
+ this.cancelOpen();
947
+ const previous = this.ws;
948
+ this.ws = null;
949
+ this.connectPromise = null;
950
+ if (previous) {
951
+ try {
952
+ previous.close();
953
+ } catch {
954
+ }
955
+ }
956
+ if (this.onlineHandler && typeof window !== "undefined" && typeof window.removeEventListener === "function") {
957
+ window.removeEventListener("online", this.onlineHandler);
958
+ this.onlineHandler = null;
959
+ }
960
+ }
961
+ cancelOpen() {
962
+ this.generation += 1;
963
+ this.cancelPending?.();
964
+ this.cancelPending = null;
965
+ this.connectPromise = null;
966
+ }
967
+ async open(generation, resolve, reject) {
968
+ let settled = false;
969
+ try {
970
+ const token = await this.getToken();
971
+ if (generation !== this.generation || this.manuallyClosed || this.suspended) {
972
+ reject(new Error("Connection attempt cancelled."));
973
+ return;
974
+ }
975
+ const ws = this.createWebSocket(this.baseUrl, socketProtocols(token));
976
+ this.ws = ws;
977
+ ws.onopen = () => {
978
+ if (settled || generation !== this.generation || this.ws !== ws) return;
979
+ settled = true;
980
+ this.attempt = 0;
981
+ resolve();
982
+ };
983
+ ws.onmessage = (event) => {
984
+ if (this.ws !== ws) return;
985
+ const parsed = parseServerMessage(event.data);
986
+ const message = parsed?.type === "topic:message" ? this.topicParts.take(parsed) : parsed;
987
+ if (!message) return;
988
+ if (message.type === "session:ready") this.onSessionReady?.();
989
+ this.onMessage(message);
990
+ };
991
+ ws.onerror = () => {
992
+ };
993
+ ws.onclose = () => {
994
+ if (this.ws !== ws) return;
995
+ this.topicParts.clear();
996
+ this.ws = null;
997
+ this.connectPromise = null;
998
+ if (!settled) {
999
+ settled = true;
1000
+ reject(new Error("tapedb-data: WebSocket closed before opening."));
1001
+ }
1002
+ if (!this.manuallyClosed) this.scheduleReconnect();
1003
+ };
1004
+ } catch (error) {
1005
+ if (generation !== this.generation) {
1006
+ reject(error);
1007
+ return;
1008
+ }
1009
+ this.ws = null;
1010
+ this.connectPromise = null;
1011
+ if (!settled) {
1012
+ settled = true;
1013
+ reject(error);
1014
+ }
1015
+ if (!this.manuallyClosed) this.scheduleReconnect();
1016
+ }
1017
+ }
1018
+ scheduleReconnect() {
1019
+ if (this.manuallyClosed || this.suspended || this.retryTimer !== null)
1020
+ return;
1021
+ const delay = Math.min(
1022
+ this.maxReconnectDelayMs,
1023
+ this.minReconnectDelayMs * 2 ** this.attempt
1024
+ );
1025
+ this.attempt += 1;
1026
+ this.retryTimer = setTimeout(() => {
1027
+ this.retryTimer = null;
1028
+ void this.connect().catch(() => {
1029
+ });
1030
+ }, delay);
1031
+ }
1032
+ clearRetryTimer() {
1033
+ if (this.retryTimer === null) return;
1034
+ clearTimeout(this.retryTimer);
1035
+ this.retryTimer = null;
1036
+ }
1037
+ };
1038
+
1039
+ // src/client/data-client.ts
1040
+ var DEFAULT_API_URL = "http://localhost:8787";
1041
+ var MAX_RETRY_DELAY_MS = 3e4;
1042
+ var BASE_RETRY_DELAY_MS = 1e3;
1043
+ var MAX_AUTH_ATTEMPTS = 3;
1044
+ var LOAD_MORE_TIMEOUT_MS = 15e3;
1045
+ var TERMINAL_AUTH_CODES = /* @__PURE__ */ new Set([
1046
+ "unauthenticated",
1047
+ "permission_denied",
1048
+ "claim_expired",
1049
+ "wrong_workspace",
1050
+ "invalid_config"
1051
+ ]);
1052
+ var ServerError = class extends Error {
1053
+ code;
1054
+ status;
1055
+ constructor(code, message, status = 0) {
1056
+ super(message);
1057
+ this.name = "ServerError";
1058
+ this.code = code;
1059
+ this.status = status;
1060
+ }
1061
+ };
1062
+ function isServerError(error) {
1063
+ return error instanceof ServerError;
1064
+ }
1065
+ function isRetryableServerError(error) {
1066
+ if (error.status === 408 || error.status === 429 || error.code === "workspace_moving") return true;
1067
+ return error.status >= 500;
1068
+ }
1069
+ function isRecord2(value) {
1070
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1071
+ }
1072
+ function isTxStep(value) {
1073
+ return isRecord2(value) && Array.isArray(value.ops) && isRecord2(value.op);
1074
+ }
1075
+ function isTxOp(value) {
1076
+ return isRecord2(value) && typeof value.op === "string" && typeof value.namespace === "string" && typeof value.id === "string";
1077
+ }
1078
+ function mergeRows(existing, incoming) {
1079
+ const seen = /* @__PURE__ */ new Set();
1080
+ const merged = [];
1081
+ for (const row of [...existing, ...incoming]) {
1082
+ const rowId = typeof row.id === "string" ? row.id : null;
1083
+ if (rowId !== null) {
1084
+ if (seen.has(rowId)) continue;
1085
+ seen.add(rowId);
1086
+ }
1087
+ merged.push(row);
1088
+ }
1089
+ return merged;
1090
+ }
1091
+ function normalizeOps(input) {
1092
+ const ops = [];
1093
+ const visit = (value) => {
1094
+ if (Array.isArray(value)) {
1095
+ for (const item of value) visit(item);
1096
+ return;
1097
+ }
1098
+ if (isTxStep(value)) {
1099
+ for (const op of value.ops) ops.push(op);
1100
+ return;
1101
+ }
1102
+ if (isTxOp(value)) {
1103
+ ops.push(value);
1104
+ return;
1105
+ }
1106
+ throw new Error("tapedb: transact() received an invalid operation.");
1107
+ };
1108
+ for (const item of input) visit(item);
1109
+ return ops;
1110
+ }
1111
+ function readServerError(payload) {
1112
+ if (!isRecord2(payload) || !isRecord2(payload.error)) return null;
1113
+ const { code, message } = payload.error;
1114
+ if (typeof code !== "string" || typeof message !== "string") return null;
1115
+ return { code, message };
1116
+ }
1117
+ function isOkPayload(payload) {
1118
+ return isRecord2(payload) && payload.ok === true;
1119
+ }
1120
+ function trimTrailingSlash(value) {
1121
+ return value.replace(/\/+$/, "");
1122
+ }
1123
+ function deriveWebSocketUrl(apiUrl, workspaceId) {
1124
+ const base = trimTrailingSlash(apiUrl).replace(/^http/, "ws");
1125
+ return `${base}/engine/workspaces/${workspaceId}/websocket`;
1126
+ }
1127
+ function createDevTokenProvider(apiUrl, workspaceId) {
1128
+ return async () => {
1129
+ const response = await fetch(`${apiUrl}/_tapedb/claim`, {
1130
+ method: "POST",
1131
+ headers: { "content-type": "application/json" },
1132
+ body: JSON.stringify({ workspaceId })
1133
+ });
1134
+ if (!response.ok) {
1135
+ throw new Error(
1136
+ `tapedb: no getToken provided and the dev claim route returned ${response.status}. Pass init({ getToken: () => Promise<string> }) for production.`
1137
+ );
1138
+ }
1139
+ const body = await response.json();
1140
+ if (typeof body.token !== "string") {
1141
+ throw new Error("tapedb: dev claim route returned no token.");
1142
+ }
1143
+ return body.token;
1144
+ };
1145
+ }
1146
+ var AuthScopeError = class extends Error {
1147
+ };
1148
+ function scopedToken(getToken, userId) {
1149
+ if (userId === void 0) return getToken;
1150
+ return async () => {
1151
+ const token = await getToken();
1152
+ let subject;
1153
+ try {
1154
+ const payload = token.split(".")[1];
1155
+ const base64 = payload.replace(/-/g, "+").replace(/_/g, "/");
1156
+ const decoded = Uint8Array.from(atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")), (char) => char.charCodeAt(0));
1157
+ subject = JSON.parse(new TextDecoder().decode(decoded)).sub;
1158
+ } catch {
1159
+ }
1160
+ if (subject !== userId) throw new AuthScopeError("tapedb: token subject differs from userId; close this client and create one for the current user.");
1161
+ return token;
1162
+ };
1163
+ }
1164
+ function resolveConfig(config) {
1165
+ const workspaceId = config.workspaceId ?? "";
1166
+ const apiUrl = trimTrailingSlash(config.apiUrl ?? DEFAULT_API_URL);
1167
+ const websocketUrl = config.websocketUrl ?? deriveWebSocketUrl(apiUrl, workspaceId);
1168
+ return {
1169
+ workspaceId,
1170
+ apiUrl,
1171
+ websocketUrl,
1172
+ getToken: scopedToken(config.getToken ?? createDevTokenProvider(apiUrl, workspaceId), config.userId),
1173
+ schema: config.schema,
1174
+ onWriteRejected: config.onWriteRejected
1175
+ };
1176
+ }
1177
+ var TOPIC_QUEUE_MESSAGES = 100;
1178
+ var TOPIC_QUEUE_MS = 6e4;
1179
+ var DataClientImpl = class {
1180
+ config;
1181
+ fetchImpl;
1182
+ createWebSocket;
1183
+ outbox;
1184
+ missingUserScope;
1185
+ now;
1186
+ cache = /* @__PURE__ */ new Map();
1187
+ subIdToKey = /* @__PURE__ */ new Map();
1188
+ nextSubId = 0;
1189
+ /** One-shot page subscriptions, keyed by their ephemeral subscription id. */
1190
+ pages = /* @__PURE__ */ new Map();
1191
+ /** Coalesces concurrent `loadMore()` calls for the same query. */
1192
+ pagesInFlight = /* @__PURE__ */ new Map();
1193
+ nextPageId = 0;
1194
+ socket = null;
1195
+ retryTimer = null;
1196
+ retryAttempt = 0;
1197
+ authFailures = 0;
1198
+ flushing = null;
1199
+ inFlight = /* @__PURE__ */ new Set();
1200
+ /** Unacked optimistic ops, replayed over server data until they are acked. */
1201
+ pendingOps = /* @__PURE__ */ new Map();
1202
+ presencePeers = /* @__PURE__ */ new Map();
1203
+ topicListeners = /* @__PURE__ */ new Map();
1204
+ /** Last sequence seen per joined topic; a rejoin asks for what came after. */
1205
+ topicSeq = /* @__PURE__ */ new Map();
1206
+ /** Sends made while the socket was down, sent after reconnecting. */
1207
+ topicQueue = /* @__PURE__ */ new Map();
1208
+ /** This client's id across connections: replay skips its own messages. */
1209
+ topicOrigin = crypto.randomUUID();
1210
+ presenceListeners = /* @__PURE__ */ new Map();
1211
+ localPresence = /* @__PURE__ */ new Map();
1212
+ onlineHandler = null;
1213
+ closed = false;
1214
+ constructor(config, deps = {}) {
1215
+ this.config = resolveConfig(config);
1216
+ this.fetchImpl = retryWhileRecovering(deps.fetch ?? ((url, init) => fetch(url, init)), deps.recoveringRetry);
1217
+ this.createWebSocket = deps.createWebSocket;
1218
+ this.missingUserScope = deps.outbox === void 0 && indexedDbAvailable() && !(typeof config.userId === "string" && config.userId.length > 0);
1219
+ this.outbox = deps.outbox ?? createOutbox({ dbName: scopedOutboxName(this.config.apiUrl, config.userId) });
1220
+ this.now = deps.now ?? (() => Date.now());
1221
+ if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
1222
+ this.onlineHandler = () => {
1223
+ this.retryAttempt = 0;
1224
+ this.authFailures = 0;
1225
+ this.socket?.reconnectNow();
1226
+ void this.flushOutbox();
1227
+ };
1228
+ window.addEventListener("online", this.onlineHandler);
1229
+ queueMicrotask(() => {
1230
+ void this.flushOutbox();
1231
+ });
1232
+ }
1233
+ }
1234
+ /**
1235
+ * Applies ops optimistically, queues them, and sends them. Resolves to
1236
+ * "applied" once the engine acknowledged them, or "queued" when the send
1237
+ * failed transiently and the outbox will retry. Permanent refusals reject.
1238
+ */
1239
+ async transact(input) {
1240
+ const ops = normalizeOps(input);
1241
+ if (ops.length === 0) return "applied";
1242
+ return (await this.submit(ops)).status;
1243
+ }
1244
+ /**
1245
+ * The write path every write takes: optimistic apply, outbox, send. Returns
1246
+ * the engine's result when it answered, so a bulk write can report the rows
1247
+ * it matched.
1248
+ */
1249
+ async submit(ops) {
1250
+ const problem = this.configProblem();
1251
+ if (problem) {
1252
+ this.failActiveQueries("invalid_config", problem);
1253
+ throw new Error(problem);
1254
+ }
1255
+ const txId = id();
1256
+ const clientTxId = id();
1257
+ const outboxEntry = {
1258
+ clientTxId,
1259
+ txId,
1260
+ workspaceId: this.config.workspaceId,
1261
+ ops: ops.map((op) => cloneJson(op)),
1262
+ createdAt: this.now(),
1263
+ // Persisted with the entry before the first send. A retry reuses the
1264
+ // clientTxId, whose receipt the engine keeps permanently, so it
1265
+ // is applied at most once however many attempts it takes; past the
1266
+ // legacy receipt boundary the engine refuses it as retry_expired.
1267
+ attempts: 1
1268
+ };
1269
+ const snapshot = this.snapshot();
1270
+ this.inFlight.add(clientTxId);
1271
+ try {
1272
+ await this.outbox.add(outboxEntry);
1273
+ } catch (error) {
1274
+ this.inFlight.delete(clientTxId);
1275
+ throw error;
1276
+ }
1277
+ this.pendingOps.set(clientTxId, outboxEntry.ops);
1278
+ this.applyOptimistic(ops);
1279
+ this.ensureSocket();
1280
+ try {
1281
+ const result = await this.sendTransaction(outboxEntry);
1282
+ await this.outbox.remove(clientTxId);
1283
+ this.pendingOps.delete(clientTxId);
1284
+ this.retryAttempt = 0;
1285
+ this.clearRetryTimer();
1286
+ return { status: "applied", result };
1287
+ } catch (error) {
1288
+ if (error instanceof AuthScopeError || isServerError(error) && !isRetryableServerError(error)) {
1289
+ try {
1290
+ await this.outbox.remove(clientTxId);
1291
+ } finally {
1292
+ this.pendingOps.delete(clientTxId);
1293
+ this.restore(snapshot);
1294
+ }
1295
+ throw error;
1296
+ }
1297
+ this.scheduleRetry();
1298
+ return { status: "queued" };
1299
+ } finally {
1300
+ this.inFlight.delete(clientTxId);
1301
+ }
1302
+ }
1303
+ /**
1304
+ * A bulk write, on the same path as every write: applied to the cached rows
1305
+ * it certainly matches, kept in the outbox, sent. The engine resolves the
1306
+ * rows when the write reaches it and writes them all in one transaction.
1307
+ * Online, `count` is the engine's; queued offline, it is the cached rows
1308
+ * changed so far, and `queued` is true.
1309
+ */
1310
+ async bulk(op) {
1311
+ const problem = this.configProblem();
1312
+ if (problem) throw new Error(problem);
1313
+ const local = /* @__PURE__ */ new Set();
1314
+ if (op.op === "patchMany" || op.op === "deleteMany") {
1315
+ for (const entry of this.cache.values()) {
1316
+ if (entry.state.data === null) continue;
1317
+ for (const match of certainMatches(entry.state.data, op.namespace, op.where)) local.add(match);
1318
+ }
1319
+ }
1320
+ const { status, result } = await this.submit([op]);
1321
+ if (status === "queued") return { count: local.size, queued: true };
1322
+ return { count: result?.matched?.[0] ?? 0 };
1323
+ }
1324
+ /**
1325
+ * The workspace export, one parsed NDJSON record at a time, read from the
1326
+ * response stream as it arrives rather than buffered.
1327
+ */
1328
+ async erasePerson(subject) {
1329
+ if (!subject) throw new Error("A subject is required.");
1330
+ const token = await this.requireToken();
1331
+ const response = await this.fetchImpl(
1332
+ `${this.config.apiUrl}/engine/workspaces/${this.config.workspaceId}/subjects/${encodeURIComponent(subject)}`,
1333
+ { method: "DELETE", headers: { authorization: `Bearer ${token}` } }
1334
+ );
1335
+ if (!response.ok) {
1336
+ const error = readServerError(await response.json().catch(() => null));
1337
+ throw new ServerError(error?.code ?? "http_error", error?.message ?? `Erasure failed with HTTP ${response.status}.`, response.status);
1338
+ }
1339
+ }
1340
+ async history(model2, id2) {
1341
+ if (!model2 || !id2) throw new Error("A model and a row id are required.");
1342
+ const token = await this.requireToken();
1343
+ const query = new URLSearchParams({ model: model2, id: id2 });
1344
+ const response = await this.fetchImpl(
1345
+ `${this.config.apiUrl}/engine/workspaces/${this.config.workspaceId}/history?${query}`,
1346
+ { method: "GET", headers: { authorization: `Bearer ${token}` } }
1347
+ );
1348
+ const body = await response.json().catch(() => null);
1349
+ if (!response.ok || !body?.ok || !Array.isArray(body.data)) {
1350
+ const error = readServerError(body);
1351
+ throw new ServerError(error?.code ?? "http_error", error?.message ?? `History failed with HTTP ${response.status}.`, response.status);
1352
+ }
1353
+ return body.data;
1354
+ }
1355
+ async *exportRecords() {
1356
+ const problem = this.configProblem();
1357
+ if (problem) throw new Error(problem);
1358
+ const token = await this.requireToken();
1359
+ const response = await this.fetchImpl(
1360
+ `${this.config.apiUrl}/engine/workspaces/${this.config.workspaceId}/export`,
1361
+ { method: "GET", headers: { authorization: `Bearer ${token}` } }
1362
+ );
1363
+ const body = response.body;
1364
+ if (!response.ok || !body) {
1365
+ const payload = await response.json().catch(() => null);
1366
+ const error = readServerError(payload);
1367
+ throw new ServerError(
1368
+ error?.code ?? "http_error",
1369
+ error?.message ?? `Export failed with HTTP ${response.status}.`,
1370
+ response.status
1371
+ );
1372
+ }
1373
+ const reader = body.getReader();
1374
+ const decoder = new TextDecoder();
1375
+ let buffered = "";
1376
+ try {
1377
+ for (; ; ) {
1378
+ const { value, done } = await reader.read();
1379
+ buffered += done ? decoder.decode() : decoder.decode(value, { stream: true });
1380
+ let newline = buffered.indexOf("\n");
1381
+ while (newline !== -1) {
1382
+ const line = buffered.slice(0, newline);
1383
+ buffered = buffered.slice(newline + 1);
1384
+ if (line.trim()) yield JSON.parse(line);
1385
+ newline = buffered.indexOf("\n");
1386
+ }
1387
+ if (done) break;
1388
+ }
1389
+ if (buffered.trim()) yield JSON.parse(buffered);
1390
+ } finally {
1391
+ reader.releaseLock();
1392
+ }
1393
+ }
1394
+ /** One-shot read over HTTP: no socket, no cache, no live updates. */
1395
+ async queryOnce(query) {
1396
+ const problem = this.configProblem();
1397
+ if (problem) throw new Error(problem);
1398
+ const token = await this.requireToken();
1399
+ const response = await this.fetchImpl(
1400
+ `${this.config.apiUrl}/engine/workspaces/${this.config.workspaceId}/query`,
1401
+ {
1402
+ method: "POST",
1403
+ headers: {
1404
+ "content-type": "application/json",
1405
+ authorization: `Bearer ${token}`
1406
+ },
1407
+ body: JSON.stringify({ query })
1408
+ }
1409
+ );
1410
+ const payload = await response.json().catch(() => null);
1411
+ if (!response.ok || payload?.ok !== true || payload.data === void 0) {
1412
+ const error = readServerError(payload);
1413
+ throw new ServerError(
1414
+ error?.code ?? "http_error",
1415
+ error?.message ?? `Query failed with HTTP ${response.status}.`,
1416
+ response.status
1417
+ );
1418
+ }
1419
+ return { data: payload.data, pageInfo: payload.pageInfo ?? {} };
1420
+ }
1421
+ /** The workspace's file index. */
1422
+ async listFiles() {
1423
+ const token = await this.requireToken();
1424
+ const response = await this.fetchImpl(
1425
+ `${this.config.apiUrl}/engine/workspaces/${this.config.workspaceId}/files`,
1426
+ { method: "GET", headers: { authorization: `Bearer ${token}` } }
1427
+ );
1428
+ const payload = await response.json().catch(() => null);
1429
+ if (!response.ok || payload?.ok !== true || !Array.isArray(payload.data)) {
1430
+ const error = readServerError(payload);
1431
+ throw new ServerError(
1432
+ error?.code ?? "http_error",
1433
+ error?.message ?? `Listing files failed with HTTP ${response.status}.`,
1434
+ response.status
1435
+ );
1436
+ }
1437
+ return payload.data;
1438
+ }
1439
+ subscribeQuery(query, listener) {
1440
+ const entry = this.entry(query);
1441
+ entry.listeners.add(listener);
1442
+ if (entry.listeners.size === 1) {
1443
+ this.ensureSocket();
1444
+ this.sendSubscribe(entry);
1445
+ }
1446
+ return () => {
1447
+ entry.listeners.delete(listener);
1448
+ if (entry.listeners.size === 0) {
1449
+ this.socket?.send({ type: "query:unsubscribe", id: entry.subId });
1450
+ }
1451
+ };
1452
+ }
1453
+ getQueryState(query) {
1454
+ return this.entry(query).state;
1455
+ }
1456
+ /**
1457
+ * Requests the next page for the cached query and appends it.
1458
+ *
1459
+ * The cursor comes from the engine (`pageInfo[namespace].nextCursor`), never
1460
+ * from a client-side offset: keyset pagination stays correct when rows are
1461
+ * inserted or deleted between pages. One request covers every top-level
1462
+ * namespace that reported a cursor; nested link results ride along with the
1463
+ * page instead of being paginated.
1464
+ */
1465
+ loadMore(query) {
1466
+ const problem = this.configProblem();
1467
+ if (problem) {
1468
+ return Promise.reject(new Error(problem));
1469
+ }
1470
+ const entry = this.entry(query);
1471
+ const inFlight = this.pagesInFlight.get(entry.key);
1472
+ if (inFlight) return inFlight;
1473
+ const document = this.nextPageDocument(entry);
1474
+ if (!document) return Promise.resolve(false);
1475
+ const tracked = this.requestPage(entry, document).finally(() => {
1476
+ this.pagesInFlight.delete(entry.key);
1477
+ });
1478
+ this.pagesInFlight.set(entry.key, tracked);
1479
+ return tracked;
1480
+ }
1481
+ publishPresence(target, presence) {
1482
+ const entry = this.localPresence.get(target) ?? {};
1483
+ entry.presence = presence;
1484
+ this.localPresence.set(target, entry);
1485
+ this.ensureSocket();
1486
+ this.socket?.send({ type: "presence:set", target, presence });
1487
+ if (entry.cursor !== void 0) {
1488
+ this.socket?.send({ type: "cursor:set", target, cursor: entry.cursor });
1489
+ }
1490
+ if (entry.drag !== void 0) {
1491
+ this.socket?.send({ type: "drag:set", target, drag: entry.drag });
1492
+ }
1493
+ }
1494
+ publishCursor(target, cursor) {
1495
+ const entry = this.localPresence.get(target) ?? {};
1496
+ entry.cursor = cursor;
1497
+ this.localPresence.set(target, entry);
1498
+ this.ensureSocket();
1499
+ this.socket?.send({ type: "cursor:set", target, cursor });
1500
+ }
1501
+ publishDrag(target, drag) {
1502
+ const entry = this.localPresence.get(target) ?? {};
1503
+ entry.drag = drag;
1504
+ this.localPresence.set(target, entry);
1505
+ this.ensureSocket();
1506
+ this.socket?.send({ type: "drag:set", target, drag });
1507
+ }
1508
+ clearDrag(target) {
1509
+ const entry = this.localPresence.get(target);
1510
+ if (entry) delete entry.drag;
1511
+ this.socket?.send({ type: "drag:clear", target });
1512
+ }
1513
+ clearPresence(target) {
1514
+ this.localPresence.delete(target);
1515
+ this.socket?.send({ type: "presence:clear", target });
1516
+ this.presencePeers.delete(target);
1517
+ this.notifyPresence(target);
1518
+ }
1519
+ subscribePresence(target, listener) {
1520
+ let listeners = this.presenceListeners.get(target);
1521
+ if (!listeners) {
1522
+ listeners = /* @__PURE__ */ new Set();
1523
+ this.presenceListeners.set(target, listeners);
1524
+ }
1525
+ listeners.add(listener);
1526
+ this.ensureSocket();
1527
+ listener(this.presencePeers.get(target) ?? []);
1528
+ return () => {
1529
+ listeners?.delete(listener);
1530
+ if (listeners?.size === 0) this.presenceListeners.delete(target);
1531
+ };
1532
+ }
1533
+ /**
1534
+ * Listens on a broadcast topic. The socket joins the topic with the first
1535
+ * listener and leaves it with the last, and rejoins after a reconnect.
1536
+ */
1537
+ subscribeTopic(topic, listener) {
1538
+ let listeners = this.topicListeners.get(topic);
1539
+ if (!listeners) {
1540
+ listeners = /* @__PURE__ */ new Set();
1541
+ this.topicListeners.set(topic, listeners);
1542
+ }
1543
+ listeners.add(listener);
1544
+ this.ensureSocket();
1545
+ if (listeners.size === 1) this.socket?.send({ type: "topic:join", topic });
1546
+ return () => {
1547
+ const current = this.topicListeners.get(topic);
1548
+ if (!current?.delete(listener) || current.size > 0) return;
1549
+ this.topicListeners.delete(topic);
1550
+ this.topicSeq.delete(topic);
1551
+ this.socket?.send({ type: "topic:leave", topic });
1552
+ };
1553
+ }
1554
+ /**
1555
+ * Sends to everyone else joined to `topic`. While the socket is down the
1556
+ * message waits (up to `TOPIC_QUEUE_MESSAGES` per topic, for
1557
+ * `TOPIC_QUEUE_MS`) and goes out after reconnecting: `"queued"`. False
1558
+ * only when that queue is full.
1559
+ */
1560
+ sendTopic(topic, message) {
1561
+ const encoded = JSON.stringify({ type: "topic:send", topic, message, origin: this.topicOrigin });
1562
+ if (encoded.length > MAX_SOCKET_MESSAGE_BYTES || new TextEncoder().encode(encoded).byteLength > MAX_SOCKET_MESSAGE_BYTES) return false;
1563
+ message = JSON.parse(encoded).message;
1564
+ this.ensureSocket();
1565
+ if (this.socket?.send({ type: "topic:send", topic, message, origin: this.topicOrigin })) return true;
1566
+ const queue = (this.topicQueue.get(topic) ?? []).filter((item) => Date.now() - item.at < TOPIC_QUEUE_MS);
1567
+ if (queue.length >= TOPIC_QUEUE_MESSAGES) {
1568
+ this.topicQueue.set(topic, queue);
1569
+ return false;
1570
+ }
1571
+ queue.push({ message, at: Date.now() });
1572
+ this.topicQueue.set(topic, queue);
1573
+ return "queued";
1574
+ }
1575
+ flushTopicQueue() {
1576
+ const now = Date.now();
1577
+ for (const [topic, queue] of [...this.topicQueue]) {
1578
+ const fresh = queue.filter((item) => now - item.at < TOPIC_QUEUE_MS);
1579
+ while (fresh.length > 0) {
1580
+ if (!this.socket?.send({ type: "topic:send", topic, message: fresh[0].message, origin: this.topicOrigin })) break;
1581
+ fresh.shift();
1582
+ }
1583
+ if (fresh.length > 0) this.topicQueue.set(topic, fresh);
1584
+ else this.topicQueue.delete(topic);
1585
+ }
1586
+ }
1587
+ async connect() {
1588
+ const problem = this.configProblem();
1589
+ if (problem) {
1590
+ this.failActiveQueries("invalid_config", problem);
1591
+ throw new Error(problem);
1592
+ }
1593
+ this.authFailures = 0;
1594
+ this.ensureSocket();
1595
+ if (!this.socket) {
1596
+ throw new Error("tapedb: WebSocket is not available.");
1597
+ }
1598
+ await this.socket.connect();
1599
+ }
1600
+ async flushOutbox() {
1601
+ if (this.closed) return;
1602
+ if (this.configProblem()) return;
1603
+ if (this.flushing) return this.flushing;
1604
+ this.flushing = this.doFlush().finally(() => {
1605
+ this.flushing = null;
1606
+ });
1607
+ return this.flushing;
1608
+ }
1609
+ async clearOutbox() {
1610
+ await this.outbox.clear(this.config.workspaceId);
1611
+ this.retryAttempt = 0;
1612
+ this.clearRetryTimer();
1613
+ }
1614
+ close() {
1615
+ this.closed = true;
1616
+ this.clearRetryTimer();
1617
+ for (const id2 of [...this.pages.keys()]) {
1618
+ this.failPage(
1619
+ id2,
1620
+ new Error(
1621
+ "tapedb: client closed while waiting for the next page."
1622
+ )
1623
+ );
1624
+ }
1625
+ if (this.onlineHandler && typeof window !== "undefined" && typeof window.removeEventListener === "function") {
1626
+ window.removeEventListener("online", this.onlineHandler);
1627
+ this.onlineHandler = null;
1628
+ }
1629
+ this.socket?.close();
1630
+ this.socket = null;
1631
+ }
1632
+ configProblem() {
1633
+ if (this.missingUserScope) return "tapedb: pass userId (the claim subject) to scope persistent authenticated browser writes.";
1634
+ if (!this.config.workspaceId) {
1635
+ return "tapedb: missing workspace. Pass createClient({ workspace }).";
1636
+ }
1637
+ if (!this.config.getToken) {
1638
+ return "tapedb: missing getToken. Pass createClient({ getToken: () => Promise<string> }).";
1639
+ }
1640
+ return null;
1641
+ }
1642
+ entry(query) {
1643
+ const key = stableStringify(query);
1644
+ const existing = this.cache.get(key);
1645
+ if (existing) {
1646
+ existing.query = query;
1647
+ return existing;
1648
+ }
1649
+ const subId = `q${this.nextSubId += 1}`;
1650
+ const created = {
1651
+ key,
1652
+ query,
1653
+ state: { data: null, isLoading: true, error: null },
1654
+ seq: 0,
1655
+ subId,
1656
+ listeners: /* @__PURE__ */ new Set()
1657
+ };
1658
+ this.cache.set(key, created);
1659
+ this.subIdToKey.set(subId, key);
1660
+ return created;
1661
+ }
1662
+ entryBySubId(subId) {
1663
+ const key = this.subIdToKey.get(subId);
1664
+ return key === void 0 ? void 0 : this.cache.get(key);
1665
+ }
1666
+ sendSubscribe(entry) {
1667
+ this.socket?.send({
1668
+ type: "query:subscribe",
1669
+ id: entry.subId,
1670
+ query: this.liveDocument(entry)
1671
+ });
1672
+ }
1673
+ /**
1674
+ * The query the live subscription actually runs: the caller's query, with
1675
+ * each paged namespace's limit widened to the rows already loaded. The cache
1676
+ * key stays the caller's query, so `useQuery` callers are unaffected.
1677
+ */
1678
+ liveDocument(entry) {
1679
+ if (!entry.window) return entry.query;
1680
+ const document = { ...entry.query };
1681
+ for (const [namespace, rows] of Object.entries(entry.window)) {
1682
+ const node = entry.query[namespace];
1683
+ if (!isRecord2(node)) continue;
1684
+ const options = isRecord2(node.$) ? node.$ : {};
1685
+ const limit = Math.max(rows, typeof options.limit === "number" ? options.limit : 0);
1686
+ document[namespace] = { ...node, $: { ...options, limit } };
1687
+ }
1688
+ return document;
1689
+ }
1690
+ resubscribeAll() {
1691
+ for (const entry of this.cache.values()) {
1692
+ if (entry.listeners.size > 0) this.sendSubscribe(entry);
1693
+ }
1694
+ }
1695
+ /**
1696
+ * The request for the next page: every top-level namespace with a cursor,
1697
+ * each carrying its own `after` on top of the options the caller already
1698
+ * passed. Returns null when nothing is left to fetch.
1699
+ */
1700
+ nextPageDocument(entry) {
1701
+ if (entry.state.data === null) return null;
1702
+ const document = {};
1703
+ let hasCursor = false;
1704
+ for (const namespace of Object.keys(entry.query)) {
1705
+ const cursor = entry.state.pageInfo?.[namespace]?.nextCursor;
1706
+ if (typeof cursor !== "string" || cursor.length === 0) continue;
1707
+ const node = entry.query[namespace];
1708
+ const options = isRecord2(node) && isRecord2(node.$) ? node.$ : {};
1709
+ document[namespace] = {
1710
+ ...isRecord2(node) ? node : {},
1711
+ $: { ...options, after: cursor }
1712
+ };
1713
+ hasCursor = true;
1714
+ }
1715
+ return hasCursor ? document : null;
1716
+ }
1717
+ /**
1718
+ * Sends one page request and waits for its `query:data`.
1719
+ *
1720
+ * It is a subscription rather than an HTTP call because the paginated rows
1721
+ * must come from the same authenticated socket and the same view rules as the
1722
+ * first page. The id is ephemeral and unsubscribed as soon as the page lands,
1723
+ * so it never joins the live-query cache.
1724
+ */
1725
+ async requestPage(entry, document) {
1726
+ this.ensureSocket();
1727
+ const socket = this.socket;
1728
+ if (!socket) {
1729
+ throw new Error("tapedb: WebSocket is not available.");
1730
+ }
1731
+ await socket.connect();
1732
+ const id2 = `lm${this.nextPageId += 1}`;
1733
+ const response = new Promise((resolve, reject) => {
1734
+ const timer = setTimeout(() => {
1735
+ this.failPage(
1736
+ id2,
1737
+ new Error(
1738
+ "tapedb: loadMore() timed out waiting for the next page."
1739
+ )
1740
+ );
1741
+ }, LOAD_MORE_TIMEOUT_MS);
1742
+ this.pages.set(id2, { timer, resolve, reject });
1743
+ });
1744
+ if (!socket.send({ type: "query:subscribe", id: id2, query: document })) {
1745
+ this.failPage(
1746
+ id2,
1747
+ new Error("tapedb: loadMore() could not send on the socket.")
1748
+ );
1749
+ }
1750
+ try {
1751
+ const message = await response;
1752
+ return this.appendPage(entry, message);
1753
+ } finally {
1754
+ socket.send({ type: "query:unsubscribe", id: id2 });
1755
+ }
1756
+ }
1757
+ /** Settles a pending page request with its reply. */
1758
+ resolvePage(id2, message) {
1759
+ const pending = this.pages.get(id2);
1760
+ if (!pending) return false;
1761
+ this.pages.delete(id2);
1762
+ clearTimeout(pending.timer);
1763
+ pending.resolve(message);
1764
+ return true;
1765
+ }
1766
+ /** Settles a pending page request with an error, at most once. */
1767
+ failPage(id2, error) {
1768
+ const pending = this.pages.get(id2);
1769
+ if (!pending) return false;
1770
+ this.pages.delete(id2);
1771
+ clearTimeout(pending.timer);
1772
+ pending.reject(error);
1773
+ return true;
1774
+ }
1775
+ /**
1776
+ * Appends a page to the cached result.
1777
+ *
1778
+ * Rows are deduped by id, so the same page delivered twice (a retried cursor,
1779
+ * a server that repeats a boundary row) cannot duplicate entities. `pageInfo`
1780
+ * is replaced with the page's own metadata; a namespace the engine no longer
1781
+ * caps loses its entry, which is what makes the next `loadMore()` return
1782
+ * false.
1783
+ */
1784
+ appendPage(entry, message) {
1785
+ if (entry.state.data === null) return false;
1786
+ const data = { ...entry.state.data };
1787
+ const pageInfo = { ...entry.state.pageInfo ?? {} };
1788
+ for (const [namespace, rows] of Object.entries(message.data)) {
1789
+ if (!Array.isArray(rows)) continue;
1790
+ data[namespace] = mergeRows(data[namespace] ?? [], rows);
1791
+ const info = message.pageInfo?.[namespace];
1792
+ if (info) pageInfo[namespace] = info;
1793
+ else delete pageInfo[namespace];
1794
+ }
1795
+ const next = { data, isLoading: false, error: null };
1796
+ if (Object.keys(pageInfo).length > 0) next.pageInfo = pageInfo;
1797
+ entry.state = next;
1798
+ this.notify(entry);
1799
+ const window2 = { ...entry.window ?? {} };
1800
+ for (const namespace of Object.keys(message.data)) {
1801
+ const rows = data[namespace];
1802
+ if (Array.isArray(rows)) window2[namespace] = rows.length;
1803
+ }
1804
+ entry.window = window2;
1805
+ if (entry.listeners.size > 0) this.sendSubscribe(entry);
1806
+ return true;
1807
+ }
1808
+ ensureSocket() {
1809
+ if (this.closed) return;
1810
+ const problem = this.configProblem();
1811
+ if (problem) {
1812
+ this.failActiveQueries("invalid_config", problem);
1813
+ return;
1814
+ }
1815
+ if (this.socket) {
1816
+ void this.socket.connect().catch(() => void 0);
1817
+ return;
1818
+ }
1819
+ this.socket = new QuerySocket({
1820
+ baseUrl: this.config.websocketUrl,
1821
+ getToken: this.config.getToken,
1822
+ createWebSocket: this.createWebSocket,
1823
+ onSessionReady: () => {
1824
+ this.authFailures = 0;
1825
+ this.resubscribeAll();
1826
+ this.republishPresence();
1827
+ for (const topic of this.topicListeners.keys()) {
1828
+ const since = this.topicSeq.get(topic);
1829
+ this.socket?.send({ type: "topic:join", topic, ...since !== void 0 ? { since } : {} });
1830
+ }
1831
+ this.flushTopicQueue();
1832
+ void this.flushOutbox();
1833
+ },
1834
+ onMessage: (message) => this.handleServerMessage(message)
1835
+ });
1836
+ void this.socket.connect().catch(() => {
1837
+ });
1838
+ }
1839
+ republishPresence() {
1840
+ for (const [target, entry] of this.localPresence) {
1841
+ if (entry.presence !== void 0) {
1842
+ this.socket?.send({
1843
+ type: "presence:set",
1844
+ target,
1845
+ presence: entry.presence
1846
+ });
1847
+ }
1848
+ if (entry.cursor !== void 0) {
1849
+ this.socket?.send({ type: "cursor:set", target, cursor: entry.cursor });
1850
+ }
1851
+ if (entry.drag !== void 0) {
1852
+ this.socket?.send({ type: "drag:set", target, drag: entry.drag });
1853
+ }
1854
+ }
1855
+ }
1856
+ patchPeer(target, clientId, patch) {
1857
+ const peers = this.presencePeers.get(target);
1858
+ if (!peers) return;
1859
+ const index = peers.findIndex((peer) => peer.clientId === clientId);
1860
+ if (index === -1) return;
1861
+ const next = [...peers];
1862
+ next[index] = { ...next[index], ...patch };
1863
+ this.presencePeers.set(target, next);
1864
+ this.notifyPresence(target);
1865
+ }
1866
+ notifyPresence(target) {
1867
+ const peers = this.presencePeers.get(target) ?? [];
1868
+ const listeners = this.presenceListeners.get(target);
1869
+ if (!listeners) return;
1870
+ for (const listener of listeners) listener(peers);
1871
+ }
1872
+ handleServerMessage(message) {
1873
+ switch (message.type) {
1874
+ case "topic:joined": {
1875
+ const seen = this.topicSeq.get(message.topic);
1876
+ if (seen === void 0 || message.seq < seen) this.topicSeq.set(message.topic, message.seq);
1877
+ return;
1878
+ }
1879
+ case "topic:message": {
1880
+ if ("part" in message) return;
1881
+ if (message.seq !== void 0) {
1882
+ const seen = this.topicSeq.get(message.topic);
1883
+ if (seen !== void 0 && message.seq <= seen) return;
1884
+ this.topicSeq.set(message.topic, message.seq);
1885
+ }
1886
+ if (message.origin === this.topicOrigin) return;
1887
+ const from = { clientId: message.from.clientId, userId: message.from.sub };
1888
+ for (const listener of [...this.topicListeners.get(message.topic) ?? []]) {
1889
+ try {
1890
+ listener.message(message.message, from);
1891
+ } catch {
1892
+ }
1893
+ }
1894
+ return;
1895
+ }
1896
+ case "topic:error": {
1897
+ const targets = message.topic === null ? [...this.topicListeners.values()].flatMap((set) => [...set]) : [...this.topicListeners.get(message.topic) ?? []];
1898
+ for (const listener of targets) {
1899
+ listener.error?.({ code: message.code, message: message.message });
1900
+ }
1901
+ return;
1902
+ }
1903
+ case "presence:update": {
1904
+ this.presencePeers.set(message.target, message.peers);
1905
+ this.notifyPresence(message.target);
1906
+ return;
1907
+ }
1908
+ case "cursor:update": {
1909
+ this.patchPeer(message.target, message.clientId, {
1910
+ cursor: message.cursor
1911
+ });
1912
+ return;
1913
+ }
1914
+ case "drag:update": {
1915
+ this.patchPeer(message.target, message.clientId, {
1916
+ drag: message.drag
1917
+ });
1918
+ return;
1919
+ }
1920
+ case "query:data": {
1921
+ if (this.resolvePage(message.id, message)) return;
1922
+ const entry = this.entryBySubId(message.id);
1923
+ if (!entry) return;
1924
+ entry.seq = message.seq;
1925
+ entry.state = {
1926
+ // A reconnect re-sends full results; without the overlay the user
1927
+ // watches their queued edit revert until the flush lands.
1928
+ data: this.overlayPending(message.data),
1929
+ isLoading: false,
1930
+ error: null,
1931
+ ...message.pageInfo === void 0 ? {} : { pageInfo: message.pageInfo }
1932
+ };
1933
+ this.notify(entry);
1934
+ return;
1935
+ }
1936
+ case "query:diff": {
1937
+ const entry = this.entryBySubId(message.id);
1938
+ if (!entry || entry.state.data === null) return;
1939
+ entry.seq = message.seq;
1940
+ const pageInfo = message.pageInfo ?? entry.state.pageInfo;
1941
+ entry.state = {
1942
+ data: applyQueryDiff(entry.state.data, message),
1943
+ isLoading: false,
1944
+ error: null,
1945
+ ...pageInfo === void 0 ? {} : { pageInfo }
1946
+ };
1947
+ this.notify(entry);
1948
+ return;
1949
+ }
1950
+ case "query:error": {
1951
+ if (message.id !== null && this.failPage(
1952
+ message.id,
1953
+ new ServerError(message.code, message.message)
1954
+ )) {
1955
+ return;
1956
+ }
1957
+ if (message.id === null) return;
1958
+ const entry = this.entryBySubId(message.id);
1959
+ if (!entry) return;
1960
+ entry.state = {
1961
+ ...entry.state,
1962
+ isLoading: false,
1963
+ error: { code: message.code, message: message.message }
1964
+ };
1965
+ this.notify(entry);
1966
+ return;
1967
+ }
1968
+ case "session:error": {
1969
+ if (TERMINAL_AUTH_CODES.has(message.code)) {
1970
+ this.authFailures += 1;
1971
+ if (this.authFailures >= MAX_AUTH_ATTEMPTS) {
1972
+ this.socket?.suspend();
1973
+ this.failActiveQueries(
1974
+ "unauthenticated",
1975
+ message.message || "The engine rejected the role claim; sign in again to resume."
1976
+ );
1977
+ return;
1978
+ }
1979
+ }
1980
+ this.socket?.reconnectNow();
1981
+ return;
1982
+ }
1983
+ default:
1984
+ return;
1985
+ }
1986
+ }
1987
+ /** Re-applies every unacked optimistic write over freshly received data. */
1988
+ overlayPending(data) {
1989
+ if (this.pendingOps.size === 0) return data;
1990
+ let next = data;
1991
+ for (const ops of this.pendingOps.values()) {
1992
+ next = applyOptimisticOps(next, ops, this.config.schema);
1993
+ }
1994
+ return next;
1995
+ }
1996
+ notify(entry) {
1997
+ for (const listener of entry.listeners) listener();
1998
+ }
1999
+ failActiveQueries(code, message) {
2000
+ const error = { code, message };
2001
+ for (const entry of this.cache.values()) {
2002
+ if (entry.listeners.size === 0) continue;
2003
+ if (entry.state.error?.message === message) continue;
2004
+ entry.state = { ...entry.state, isLoading: false, error };
2005
+ this.notify(entry);
2006
+ }
2007
+ }
2008
+ snapshot() {
2009
+ const snapshots2 = [];
2010
+ for (const entry of this.cache.values()) {
2011
+ if (entry.state.data === null) continue;
2012
+ snapshots2.push({
2013
+ key: entry.key,
2014
+ seq: entry.seq,
2015
+ data: entry.state.data
2016
+ });
2017
+ }
2018
+ return snapshots2;
2019
+ }
2020
+ restore(snapshots2) {
2021
+ for (const snapshot of snapshots2) {
2022
+ const entry = this.cache.get(snapshot.key);
2023
+ if (!entry) continue;
2024
+ if (entry.seq !== snapshot.seq) continue;
2025
+ entry.state = { ...entry.state, data: snapshot.data };
2026
+ this.notify(entry);
2027
+ }
2028
+ }
2029
+ applyOptimistic(ops) {
2030
+ for (const entry of this.cache.values()) {
2031
+ if (entry.state.data === null) continue;
2032
+ entry.state = {
2033
+ ...entry.state,
2034
+ data: applyOptimisticOps(entry.state.data, ops, this.config.schema)
2035
+ };
2036
+ this.notify(entry);
2037
+ }
2038
+ }
2039
+ reportRejection(entry, error) {
2040
+ const listener = this.config.onWriteRejected;
2041
+ if (!listener) return;
2042
+ try {
2043
+ listener({
2044
+ clientTxId: entry.clientTxId,
2045
+ ops: entry.ops,
2046
+ code: error.code,
2047
+ message: error.message
2048
+ });
2049
+ } catch {
2050
+ }
2051
+ }
2052
+ async sendTransaction(entry) {
2053
+ const token = await this.requireToken();
2054
+ const response = await this.fetchImpl(
2055
+ `${this.config.apiUrl}/engine/workspaces/${this.config.workspaceId}/transact`,
2056
+ {
2057
+ method: "POST",
2058
+ headers: {
2059
+ "content-type": "application/json",
2060
+ authorization: `Bearer ${token}`
2061
+ },
2062
+ body: JSON.stringify({
2063
+ txId: entry.txId,
2064
+ clientTxId: entry.clientTxId,
2065
+ // The first attempt's time, on every retry: the engine refuses a
2066
+ // retry older than a legacy receipt boundary.
2067
+ issuedAt: entry.createdAt,
2068
+ ops: entry.ops
2069
+ })
2070
+ }
2071
+ );
2072
+ let payload = null;
2073
+ try {
2074
+ payload = await response.json();
2075
+ } catch {
2076
+ payload = null;
2077
+ }
2078
+ if (!response.ok || !isOkPayload(payload)) {
2079
+ const serverError = readServerError(payload);
2080
+ if (serverError) {
2081
+ throw new ServerError(
2082
+ serverError.code,
2083
+ serverError.message,
2084
+ response.status
2085
+ );
2086
+ }
2087
+ throw new ServerError(
2088
+ "http_error",
2089
+ `Transact failed with HTTP ${response.status}.`,
2090
+ response.status
2091
+ );
2092
+ }
2093
+ const result = payload.result;
2094
+ if (!isRecord2(result)) return null;
2095
+ return result;
2096
+ }
2097
+ async requireToken() {
2098
+ if (!this.config.getToken) {
2099
+ throw new Error("tapedb: missing getToken.");
2100
+ }
2101
+ return this.config.getToken();
2102
+ }
2103
+ async doFlush() {
2104
+ const entries = await this.outbox.list(this.config.workspaceId);
2105
+ for (const entry of entries) {
2106
+ if (this.inFlight.has(entry.clientTxId)) continue;
2107
+ this.inFlight.add(entry.clientTxId);
2108
+ this.pendingOps.set(entry.clientTxId, entry.ops);
2109
+ const attempt = {
2110
+ ...entry,
2111
+ attempts: (entry.attempts ?? 1) + 1
2112
+ };
2113
+ try {
2114
+ await this.outbox.add(attempt).catch(() => void 0);
2115
+ await this.sendTransaction(attempt);
2116
+ await this.outbox.remove(entry.clientTxId);
2117
+ this.pendingOps.delete(entry.clientTxId);
2118
+ this.retryAttempt = 0;
2119
+ } catch (error) {
2120
+ if (error instanceof AuthScopeError) {
2121
+ this.clearRetryTimer();
2122
+ return;
2123
+ }
2124
+ if (isServerError(error) && !isRetryableServerError(error)) {
2125
+ await this.outbox.remove(entry.clientTxId).catch(() => void 0);
2126
+ this.pendingOps.delete(entry.clientTxId);
2127
+ this.resubscribeAll();
2128
+ this.reportRejection(entry, error);
2129
+ continue;
2130
+ }
2131
+ this.scheduleRetry();
2132
+ return;
2133
+ } finally {
2134
+ this.inFlight.delete(entry.clientTxId);
2135
+ }
2136
+ }
2137
+ this.clearRetryTimer();
2138
+ }
2139
+ scheduleRetry() {
2140
+ if (this.closed || this.retryTimer !== null) return;
2141
+ const delay = Math.min(
2142
+ MAX_RETRY_DELAY_MS,
2143
+ BASE_RETRY_DELAY_MS * 2 ** this.retryAttempt
2144
+ );
2145
+ this.retryAttempt += 1;
2146
+ this.retryTimer = setTimeout(() => {
2147
+ this.retryTimer = null;
2148
+ void this.flushOutbox();
2149
+ }, delay);
2150
+ }
2151
+ clearRetryTimer() {
2152
+ if (this.retryTimer === null) return;
2153
+ clearTimeout(this.retryTimer);
2154
+ this.retryTimer = null;
2155
+ }
2156
+ };
2157
+ function createClientParts(config, deps = {}) {
2158
+ const impl = new DataClientImpl(config, deps);
2159
+ const resolved = resolveConfig(config);
2160
+ const client = {
2161
+ transact: (input) => impl.transact(input),
2162
+ get files() {
2163
+ return createStorageClient({
2164
+ apiUrl: resolved.apiUrl,
2165
+ workspaceId: resolved.workspaceId,
2166
+ // The resolved provider, not config.getToken: without it uploads were
2167
+ // the one part of the client that could not run under `tapedb dev`.
2168
+ getToken: () => {
2169
+ const provider = resolved.getToken;
2170
+ if (!provider) throw new Error("tapedb: storage needs a workspace and an API URL.");
2171
+ return provider();
2172
+ },
2173
+ fetch: deps.storageFetch,
2174
+ ...deps.recoveringRetry ? { recoveringRetry: deps.recoveringRetry } : {}
2175
+ });
2176
+ },
2177
+ room: (target) => {
2178
+ if (!target.trim()) throw new Error("Room target must not be empty.");
2179
+ return {
2180
+ publishPresence: (presence) => impl.publishPresence(target, presence),
2181
+ publishCursor: (cursor) => impl.publishCursor(target, cursor),
2182
+ publishDrag: (drag) => impl.publishDrag(target, drag),
2183
+ clearDrag: () => impl.clearDrag(target),
2184
+ subscribePresence: (listener) => impl.subscribePresence(target, listener),
2185
+ leave: () => impl.clearPresence(target)
2186
+ };
2187
+ },
2188
+ clearOutbox: () => impl.clearOutbox(),
2189
+ flushOutbox: () => impl.flushOutbox(),
2190
+ subscribeQuery: (query, listener) => impl.subscribeQuery(query, listener),
2191
+ getQueryState: (query) => impl.getQueryState(query),
2192
+ loadMore: (query) => impl.loadMore(query),
2193
+ publishPresence: (target, presence) => impl.publishPresence(target, presence),
2194
+ publishCursor: (target, cursor) => impl.publishCursor(target, cursor),
2195
+ publishDrag: (target, drag) => impl.publishDrag(target, drag),
2196
+ clearDrag: (target) => impl.clearDrag(target),
2197
+ clearPresence: (target) => impl.clearPresence(target),
2198
+ subscribePresence: (target, listener) => impl.subscribePresence(target, listener),
2199
+ connect: () => impl.connect(),
2200
+ close: () => impl.close()
2201
+ };
2202
+ return { client, impl };
2203
+ }
2204
+
2205
+ // src/model/across.ts
2206
+ var AcrossError = class extends Error {
2207
+ constructor(errors, partial) {
2208
+ super(
2209
+ `${Object.keys(errors).length} of the workspaces failed: ` + Object.entries(errors).map(([workspaceId, error]) => `${workspaceId}: ${error instanceof Error ? error.message : String(error)}`).join("; ")
2210
+ );
2211
+ this.errors = errors;
2212
+ this.partial = partial;
2213
+ this.name = "AcrossError";
2214
+ }
2215
+ errors;
2216
+ partial;
2217
+ };
2218
+ function orderOf(orderBy) {
2219
+ if (orderBy === void 0) return [];
2220
+ const list = Array.isArray(orderBy) ? orderBy : [orderBy];
2221
+ const order2 = [];
2222
+ for (const entry of list) {
2223
+ for (const [field2, direction] of Object.entries(entry)) order2.push([field2, direction]);
2224
+ }
2225
+ return order2;
2226
+ }
2227
+ var utf8 = new TextEncoder();
2228
+ function compareValues(a, b) {
2229
+ const rank = (value) => value === null || value === void 0 ? 0 : typeof value === "string" ? 2 : 1;
2230
+ const scalar = (value) => value instanceof Date ? value.getTime() : typeof value === "boolean" ? Number(value) : value;
2231
+ const left = scalar(a);
2232
+ const right = scalar(b);
2233
+ const byRank = rank(left) - rank(right);
2234
+ if (byRank !== 0) return byRank;
2235
+ if (rank(left) === 0) return 0;
2236
+ if (typeof left === "number" && typeof right === "number") return left - right;
2237
+ const x = utf8.encode(String(left));
2238
+ const y = utf8.encode(String(right));
2239
+ for (let i = 0; i < Math.min(x.length, y.length); i += 1) if (x[i] !== y[i]) return x[i] - y[i];
2240
+ return x.length - y.length;
2241
+ }
2242
+ function comparator(order2) {
2243
+ return (a, b) => {
2244
+ for (const [field2, direction] of order2) {
2245
+ const compared = compareValues(a[field2], b[field2]);
2246
+ if (compared !== 0) return direction === "asc" ? compared : -compared;
2247
+ }
2248
+ return 0;
2249
+ };
2250
+ }
2251
+ function merge(lists, order2, take) {
2252
+ const compare = comparator(order2);
2253
+ const used = lists.map(() => 0);
2254
+ const rows = [];
2255
+ for (; ; ) {
2256
+ if (take !== void 0 && rows.length >= take) break;
2257
+ let best = -1;
2258
+ for (let index = 0; index < lists.length; index += 1) {
2259
+ if (used[index] >= lists[index].rows.length) continue;
2260
+ if (best === -1) {
2261
+ best = index;
2262
+ continue;
2263
+ }
2264
+ if (order2.length > 0 && compare(lists[index].rows[used[index]], lists[best].rows[used[best]]) < 0) best = index;
2265
+ }
2266
+ if (best === -1) break;
2267
+ rows.push({ ...lists[best].rows[used[best]], workspaceId: lists[best].workspaceId });
2268
+ used[best] += 1;
2269
+ }
2270
+ return { rows, used };
2271
+ }
2272
+ function withOrderFields(args, order2) {
2273
+ if (args.select === void 0 || args.select === null || typeof args.select !== "object") return { args, extra: [] };
2274
+ const select = args.select;
2275
+ const extra = order2.map(([field2]) => field2).filter((field2) => !select[field2]);
2276
+ if (extra.length === 0) return { args, extra };
2277
+ return { args: { ...args, select: { ...select, ...Object.fromEntries(extra.map((field2) => [field2, true])) } }, extra };
2278
+ }
2279
+ function strip(rows, extra) {
2280
+ if (extra.length === 0) return rows;
2281
+ return rows.map((row) => {
2282
+ const copy = { ...row };
2283
+ for (const field2 of extra) delete copy[field2];
2284
+ return copy;
2285
+ });
2286
+ }
2287
+ async function settle(clients, read) {
2288
+ const settled = await Promise.allSettled(clients.map(({ model: model2 }, index) => Promise.resolve(read(model2, index))));
2289
+ const errors = {};
2290
+ const values = settled.map((result, index) => {
2291
+ if (result.status === "fulfilled") return result.value;
2292
+ errors[clients[index].workspaceId] = result.reason;
2293
+ return void 0;
2294
+ });
2295
+ return { values, errors };
2296
+ }
2297
+ var snapshots = /* @__PURE__ */ new Map();
2298
+ var SNAPSHOTS_KEPT = 1e3;
2299
+ function acrossQuery(clients, open, combine) {
2300
+ const queries = clients.map(({ model: model2 }) => open(model2));
2301
+ const key = `across:${JSON.stringify(clients.map(({ workspaceId }, index) => [workspaceId, queries[index].key]))}`;
2302
+ const snapshot = () => {
2303
+ const states = queries.map((query) => query.snapshot());
2304
+ const cached = snapshots.get(key);
2305
+ if (cached && cached.states.length === states.length && cached.states.every((state, index) => state === states[index])) {
2306
+ return cached.view;
2307
+ }
2308
+ const errors = {};
2309
+ states.forEach((state, index) => {
2310
+ if (state.error) errors[clients[index].workspaceId] = state.error;
2311
+ });
2312
+ const loading = states.some((state) => state.isLoading && !state.error);
2313
+ const anyData = states.some((state) => state.data !== void 0);
2314
+ const view = {
2315
+ data: anyData || !loading ? combine(states.map((state) => state.data)) : void 0,
2316
+ isLoading: loading,
2317
+ error: Object.values(errors)[0] ?? null,
2318
+ errors
2319
+ };
2320
+ snapshots.delete(key);
2321
+ snapshots.set(key, { states, view });
2322
+ if (snapshots.size > SNAPSHOTS_KEPT) snapshots.delete(snapshots.keys().next().value);
2323
+ return view;
2324
+ };
2325
+ return {
2326
+ key,
2327
+ then(onFulfilled, onRejected) {
2328
+ return settle(clients, (_model, index) => queries[index]).then(({ values, errors }) => {
2329
+ const result = combine(values);
2330
+ if (Object.keys(errors).length > 0) throw new AcrossError(errors, result);
2331
+ return result;
2332
+ }).then(onFulfilled, onRejected);
2333
+ },
2334
+ subscribe(listener) {
2335
+ let ready = false;
2336
+ const stops = queries.map(
2337
+ (query) => query.subscribe(() => {
2338
+ if (ready) listener(snapshot());
2339
+ })
2340
+ );
2341
+ ready = true;
2342
+ listener(snapshot());
2343
+ return () => {
2344
+ for (const stop of stops) stop();
2345
+ };
2346
+ },
2347
+ snapshot
2348
+ };
2349
+ }
2350
+ function encodePositions(positions) {
2351
+ const json = JSON.stringify(positions);
2352
+ const bytes = utf8.encode(json);
2353
+ let binary = "";
2354
+ for (const byte of bytes) binary += String.fromCharCode(byte);
2355
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2356
+ }
2357
+ function decodePositions(cursor) {
2358
+ try {
2359
+ const base64 = cursor.replace(/-/g, "+").replace(/_/g, "/");
2360
+ const binary = atob(base64 + "=".repeat((4 - base64.length % 4) % 4));
2361
+ const parsed = JSON.parse(new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0))));
2362
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error();
2363
+ return parsed;
2364
+ } catch {
2365
+ throw new Error("This cursor is not from $across(...).findPage.");
2366
+ }
2367
+ }
2368
+ function acrossModel(clients) {
2369
+ const findMany = (args = {}) => {
2370
+ const order2 = orderOf(args.orderBy);
2371
+ const { args: read, extra } = withOrderFields(args, order2);
2372
+ return acrossQuery(
2373
+ clients,
2374
+ (model2) => model2.findMany(read),
2375
+ (parts) => strip(
2376
+ merge(
2377
+ parts.map((rows, index) => ({ workspaceId: clients[index].workspaceId, rows: rows ?? [] })),
2378
+ order2,
2379
+ args.take
2380
+ ).rows,
2381
+ extra
2382
+ )
2383
+ );
2384
+ };
2385
+ return {
2386
+ findMany,
2387
+ findFirst(args = {}) {
2388
+ const many = findMany({ ...args, take: 1 });
2389
+ const first = () => {
2390
+ const from = many.snapshot();
2391
+ const key = `first:${many.key}`;
2392
+ const cached = snapshots.get(key);
2393
+ if (cached?.states[0] === from) return cached.view;
2394
+ const view = { ...from, data: from.data === void 0 ? void 0 : from.data[0] ?? null };
2395
+ snapshots.delete(key);
2396
+ snapshots.set(key, { states: [from], view });
2397
+ return view;
2398
+ };
2399
+ return {
2400
+ then: (onFulfilled, onRejected) => many.then(
2401
+ (rows) => rows[0] ?? null,
2402
+ (error) => {
2403
+ if (error instanceof AcrossError) throw new AcrossError(error.errors, error.partial[0] ?? null);
2404
+ throw error;
2405
+ }
2406
+ ).then(onFulfilled, onRejected),
2407
+ key: `first:${many.key}`,
2408
+ subscribe: (listener) => many.subscribe(() => listener(first())),
2409
+ snapshot: () => first()
2410
+ };
2411
+ },
2412
+ findPage(args = {}) {
2413
+ const { after, ...rest } = args;
2414
+ const take = rest.take ?? 50;
2415
+ const orderBy = rest.orderBy ?? { id: "asc" };
2416
+ const order2 = orderOf(orderBy);
2417
+ const { args: read, extra } = withOrderFields({ ...rest, orderBy, take }, order2);
2418
+ return {
2419
+ then(onFulfilled, onRejected) {
2420
+ const run = async () => {
2421
+ const positions = after ? decodePositions(after) : {};
2422
+ const open = clients.filter(({ workspaceId }) => positions[workspaceId] !== true);
2423
+ const fetched = await settle(open, (model2, index) => {
2424
+ const position = positions[open[index].workspaceId];
2425
+ return model2.findPage({ ...read, ...typeof position === "string" ? { after: position } : {} });
2426
+ });
2427
+ const pages = fetched.values;
2428
+ const merged = merge(
2429
+ open.map(({ workspaceId }, index) => ({ workspaceId, rows: pages[index]?.rows ?? [] })),
2430
+ order2,
2431
+ take
2432
+ );
2433
+ const next = { ...positions };
2434
+ await Promise.all(
2435
+ open.map(async ({ workspaceId, model: model2 }, index) => {
2436
+ const page2 = pages[index];
2437
+ if (page2 === void 0) return;
2438
+ const used = merged.used[index];
2439
+ if (used === page2.rows.length) {
2440
+ next[workspaceId] = page2.hasMore && page2.cursor !== null ? page2.cursor : true;
2441
+ } else if (used > 0) {
2442
+ const position = positions[workspaceId];
2443
+ const partial = await model2.findPage({
2444
+ ...read,
2445
+ take: used,
2446
+ ...typeof position === "string" ? { after: position } : {}
2447
+ });
2448
+ next[workspaceId] = partial.cursor ?? true;
2449
+ }
2450
+ })
2451
+ );
2452
+ const hasMore = clients.some(({ workspaceId }) => next[workspaceId] !== true);
2453
+ const page = {
2454
+ rows: strip(merged.rows, extra),
2455
+ hasMore,
2456
+ cursor: hasMore ? encodePositions(next) : null
2457
+ };
2458
+ if (Object.keys(fetched.errors).length > 0) throw new AcrossError(fetched.errors, page);
2459
+ return page;
2460
+ };
2461
+ return run().then(onFulfilled, onRejected);
2462
+ }
2463
+ };
2464
+ },
2465
+ count(args = {}) {
2466
+ return acrossQuery(
2467
+ clients,
2468
+ (model2) => model2.count(args),
2469
+ (parts) => parts.reduce((sum, part) => sum + (part ?? 0), 0)
2470
+ );
2471
+ }
2472
+ };
2473
+ }
2474
+
2475
+ // src/model/client.ts
2476
+ var Query = class {
2477
+ constructor(runtime, document, project, kind) {
2478
+ this.runtime = runtime;
2479
+ this.document = document;
2480
+ this.project = project;
2481
+ this.key = `${kind}:${stableStringify(document)}`;
2482
+ }
2483
+ runtime;
2484
+ document;
2485
+ project;
2486
+ /** Identifies the query: equal keys share one live subscription. */
2487
+ key;
2488
+ then(onFulfilled, onRejected) {
2489
+ return this.runtime.impl.queryOnce(this.document).then(({ data, pageInfo }) => this.project(data, pageInfo)).then(onFulfilled, onRejected);
2490
+ }
2491
+ catch(onRejected) {
2492
+ return this.then(void 0, onRejected);
2493
+ }
2494
+ finally(onFinally) {
2495
+ return this.then().finally(onFinally);
2496
+ }
2497
+ /** Live results. The listener runs now with the current state, then on every change. */
2498
+ subscribe(listener) {
2499
+ const stop = this.runtime.impl.subscribeQuery(this.document, () => listener(this.snapshot()));
2500
+ listener(this.snapshot());
2501
+ return stop;
2502
+ }
2503
+ /**
2504
+ * The current live state. Referentially stable while nothing changed, so it
2505
+ * can back `useSyncExternalStore`.
2506
+ */
2507
+ snapshot() {
2508
+ const state = this.runtime.impl.getQueryState(this.document);
2509
+ const cached = this.runtime.snapshots.get(this.key);
2510
+ if (cached && cached.state === state) return cached.view;
2511
+ const view = {
2512
+ data: state.data === null ? void 0 : this.project(state.data, state.pageInfo ?? {}),
2513
+ isLoading: state.isLoading,
2514
+ error: state.error
2515
+ };
2516
+ this.runtime.snapshots.set(this.key, { state, view });
2517
+ return view;
2518
+ }
2519
+ };
2520
+ var PageQuery = class extends Query {
2521
+ /** Live only: appends the next page to this subscription. False when there is none. */
2522
+ loadMore() {
2523
+ return this.runtime.impl.loadMore(this.document);
2524
+ }
2525
+ };
2526
+ var Write = class {
2527
+ constructor(runtime, ops, id2) {
2528
+ this.runtime = runtime;
2529
+ this.ops = ops;
2530
+ this.id = id2;
2531
+ }
2532
+ runtime;
2533
+ ops;
2534
+ id;
2535
+ sent = null;
2536
+ then(onFulfilled, onRejected) {
2537
+ this.sent ??= this.runtime.impl.transact(this.ops).then((status) => ({ id: this.id, status }));
2538
+ return this.sent.then(onFulfilled, onRejected);
2539
+ }
2540
+ catch(onRejected) {
2541
+ return this.then(void 0, onRejected);
2542
+ }
2543
+ finally(onFinally) {
2544
+ return this.then().finally(onFinally);
2545
+ }
2546
+ };
2547
+ function inputValue(model2, field2, value) {
2548
+ return model2.scalars[field2]?.kind === "date" && value instanceof Date ? value.getTime() : value;
2549
+ }
2550
+ function isRecord3(value) {
2551
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2552
+ }
2553
+ function splitData(graph, model2, rowId, data, allowLinks) {
2554
+ const values = {};
2555
+ const before = [];
2556
+ const after = [];
2557
+ const nested = (relation, input) => {
2558
+ const target = graph[relation.target];
2559
+ const id2 = typeof input.id === "string" ? input.id : id();
2560
+ const child = splitData(graph, target, id2, input, true);
2561
+ const childValues = withDefaults(target, child.values);
2562
+ before.push(...child.before);
2563
+ before.push({ op: "insert", namespace: target.key, id: id2, values: childValues });
2564
+ after.push(...child.after);
2565
+ return id2;
2566
+ };
2567
+ for (const [key, value] of Object.entries(data)) {
2568
+ if (value === void 0 || key === "id") continue;
2569
+ if (key in model2.scalars) {
2570
+ values[key] = inputValue(model2, key, value);
2571
+ continue;
2572
+ }
2573
+ if (model2.filterable.has(key)) {
2574
+ values[key] = value;
2575
+ continue;
2576
+ }
2577
+ const relation = model2.relations[key];
2578
+ if (!relation) {
2579
+ throw new Error(`"${model2.key}" has no field "${key}".`);
2580
+ }
2581
+ if (relation.kind === "belongsTo") {
2582
+ const create2 = value?.create;
2583
+ if (value === null || value.disconnect === true) {
2584
+ values[relation.foreignKey] = null;
2585
+ } else if (typeof value.connect === "string") {
2586
+ values[relation.foreignKey] = value.connect;
2587
+ } else if (isRecord3(create2)) {
2588
+ if (!allowLinks) {
2589
+ throw new Error(`"${model2.key}.${key}": upsert cannot create related rows.`);
2590
+ }
2591
+ values[relation.foreignKey] = nested(relation, create2);
2592
+ } else {
2593
+ throw new Error(
2594
+ `"${model2.key}.${key}" takes { connect: id }, { create: {...} }, { disconnect: true } or null.`
2595
+ );
2596
+ }
2597
+ continue;
2598
+ }
2599
+ if (!allowLinks) {
2600
+ throw new Error(`"${model2.key}.${key}": connect children with create or update, not upsert.`);
2601
+ }
2602
+ const {
2603
+ connect = [],
2604
+ disconnect = [],
2605
+ create = []
2606
+ } = value;
2607
+ for (const child of Array.isArray(create) ? create : [create]) {
2608
+ if (!isRecord3(child)) {
2609
+ throw new Error(`"${model2.key}.${key}.create" takes a row, or an array of rows.`);
2610
+ }
2611
+ const childOps = [];
2612
+ const target = graph[relation.target];
2613
+ const id2 = typeof child.id === "string" ? child.id : id();
2614
+ const split = splitData(graph, target, id2, child, true);
2615
+ const childValues = withDefaults(target, split.values);
2616
+ childValues[relation.foreignKey] = rowId;
2617
+ childOps.push(...split.before, { op: "insert", namespace: target.key, id: id2, values: childValues }, ...split.after);
2618
+ after.push(...childOps);
2619
+ }
2620
+ for (const targetId of connect) {
2621
+ after.push({ op: "link", namespace: model2.key, id: rowId, link: relation.link, targetId });
2622
+ }
2623
+ for (const targetId of disconnect) {
2624
+ after.push({ op: "unlink", namespace: model2.key, id: rowId, link: relation.link, targetId });
2625
+ }
2626
+ }
2627
+ return { values, before, after };
2628
+ }
2629
+ function withDefaults(model2, values) {
2630
+ const filled = { ...values };
2631
+ for (const [field2, scalar] of Object.entries(model2.scalars)) {
2632
+ if (!(field2 in filled) && scalar.hasDefault) {
2633
+ filled[field2] = inputValue(model2, field2, scalar.defaultValue);
2634
+ }
2635
+ }
2636
+ return filled;
2637
+ }
2638
+ function requireId(model2, where) {
2639
+ if (typeof where?.id !== "string" || where.id.length === 0) {
2640
+ throw new Error(`"${model2.key}" writes address one row: pass where: { id }.`);
2641
+ }
2642
+ return where.id;
2643
+ }
2644
+ function requireGroupKey(model2, field2) {
2645
+ if (typeof field2 !== "string" || !(model2.filterable.has(field2) || field2 === "createdAt" || field2 === "updatedAt")) {
2646
+ throw new Error(`"${model2.key}" cannot be grouped by "${String(field2)}".`);
2647
+ }
2648
+ return field2;
2649
+ }
2650
+ function measureFields(model2, measure, value, accepts) {
2651
+ if (value === void 0) return [];
2652
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
2653
+ throw new Error(`"${model2.key}.${measure}" takes an object of fields.`);
2654
+ }
2655
+ const fields = [];
2656
+ for (const [field2, on] of Object.entries(value)) {
2657
+ if (on === void 0 || on === false) continue;
2658
+ if (!accepts(field2)) {
2659
+ throw new Error(`"${model2.key}.${measure}" cannot measure "${field2}".`);
2660
+ }
2661
+ fields.push(field2);
2662
+ }
2663
+ return fields;
2664
+ }
2665
+ function aggregateMeasures(model2, args) {
2666
+ const kind = (field2) => model2.scalars[field2]?.kind;
2667
+ const isRowField = (field2) => field2 === "id" || field2 === "createdAt" || field2 === "updatedAt" || field2 in model2.scalars || model2.filterable.has(field2);
2668
+ const isNumber = (field2) => kind(field2) === "number";
2669
+ const isOrdered = (field2) => isRowField(field2) && kind(field2) !== "boolean" && kind(field2) !== "json";
2670
+ const countArg = args._count;
2671
+ const countAll = countArg === true || typeof countArg === "object" && countArg !== null && countArg._all === true;
2672
+ const countOf = countArg === true || countArg === void 0 || countArg === false ? [] : measureFields(
2673
+ model2,
2674
+ "_count",
2675
+ Object.fromEntries(Object.entries(countArg).filter(([field2]) => field2 !== "_all")),
2676
+ isRowField
2677
+ );
2678
+ const sum = measureFields(model2, "_sum", args._sum, isNumber);
2679
+ const avg = measureFields(model2, "_avg", args._avg, isNumber);
2680
+ const min = measureFields(model2, "_min", args._min, isOrdered);
2681
+ const max = measureFields(model2, "_max", args._max, isOrdered);
2682
+ const engine = {};
2683
+ if (countAll) engine.count = true;
2684
+ if (countOf.length > 0) engine.countOf = countOf;
2685
+ if (sum.length > 0) engine.sum = sum;
2686
+ if (avg.length > 0) engine.avg = avg;
2687
+ if (min.length > 0) engine.min = min;
2688
+ if (max.length > 0) engine.max = max;
2689
+ const output = (group) => {
2690
+ const out = {};
2691
+ if (countArg === true) {
2692
+ out._count = group.count ?? 0;
2693
+ } else if (typeof countArg === "object" && countArg !== null) {
2694
+ const counts = {};
2695
+ if (countAll) counts._all = group.count ?? 0;
2696
+ for (const field2 of countOf) counts[field2] = group.countOf?.[field2] ?? 0;
2697
+ out._count = counts;
2698
+ }
2699
+ if (args._sum !== void 0) out._sum = pick(sum, group.sum);
2700
+ if (args._avg !== void 0) out._avg = pick(avg, group.avg);
2701
+ if (args._min !== void 0) out._min = pick(min, group.min);
2702
+ if (args._max !== void 0) out._max = pick(max, group.max);
2703
+ return out;
2704
+ };
2705
+ return { engine, output };
2706
+ }
2707
+ function pick(fields, values) {
2708
+ const out = {};
2709
+ for (const field2 of fields) out[field2] = values?.[field2] ?? null;
2710
+ return out;
2711
+ }
2712
+ function modelClient(runtime, model2) {
2713
+ const document = (args, extra = {}) => ({
2714
+ [model2.key]: toEngineNode(runtime.graph, model2, args, extra)
2715
+ });
2716
+ const reader = (args) => {
2717
+ const shape = shapeFor(runtime.graph, model2, args ?? {});
2718
+ return (data) => {
2719
+ const list = data[model2.key] ?? [];
2720
+ return shape === null ? list : list.map(shape);
2721
+ };
2722
+ };
2723
+ return {
2724
+ findMany: (args) => new Query(runtime, document(args ?? {}), reader(args), "many"),
2725
+ findFirst: (args) => {
2726
+ const rows = reader(args);
2727
+ return new Query(runtime, document({ ...args, take: 1 }), (data) => rows(data)[0] ?? null, "first");
2728
+ },
2729
+ findUnique: (args) => {
2730
+ const rows = reader(args);
2731
+ return new Query(
2732
+ runtime,
2733
+ document({
2734
+ where: { id: requireId(model2, args.where) },
2735
+ include: args.include,
2736
+ select: args.select,
2737
+ take: 1
2738
+ }),
2739
+ (data) => rows(data)[0] ?? null,
2740
+ "first"
2741
+ );
2742
+ },
2743
+ findPage: (args) => {
2744
+ const { after, ...rest } = args ?? {};
2745
+ const rows = reader(rest);
2746
+ return new PageQuery(
2747
+ runtime,
2748
+ document({
2749
+ ...rest,
2750
+ orderBy: rest.orderBy ?? { id: "asc" },
2751
+ take: rest.take ?? 50,
2752
+ ...after ? { after } : {}
2753
+ }),
2754
+ (data, pageInfo) => ({
2755
+ rows: rows(data),
2756
+ hasMore: pageInfo[model2.key]?.hasMore ?? false,
2757
+ cursor: pageInfo[model2.key]?.nextCursor ?? null
2758
+ }),
2759
+ "page"
2760
+ );
2761
+ },
2762
+ count: (args) => new Query(
2763
+ runtime,
2764
+ document({ where: args?.where }, { count: true, limit: 0 }),
2765
+ (_data, pageInfo) => pageInfo[model2.key]?.count ?? 0,
2766
+ "count"
2767
+ ),
2768
+ aggregate: (args) => {
2769
+ const measures = aggregateMeasures(model2, args);
2770
+ return new Query(
2771
+ runtime,
2772
+ document({ where: args.where }, { limit: 0, aggregate: measures.engine }),
2773
+ (_data, pageInfo) => {
2774
+ const group = pageInfo[model2.key]?.aggregate?.[0];
2775
+ return group === void 0 ? null : measures.output(group);
2776
+ },
2777
+ "aggregate"
2778
+ );
2779
+ },
2780
+ groupBy: (args) => {
2781
+ const measures = aggregateMeasures(model2, args);
2782
+ const by = args.by;
2783
+ if (!Array.isArray(by) || by.length === 0) {
2784
+ throw new Error(`"${model2.key}.groupBy" needs a non-empty "by" array.`);
2785
+ }
2786
+ for (const field2 of by) requireGroupKey(model2, field2);
2787
+ const order2 = {};
2788
+ for (const [field2, direction] of Object.entries(args.orderBy ?? {})) {
2789
+ if (!by.includes(field2)) {
2790
+ throw new Error(`"${model2.key}.groupBy" can only order by a "by" field; "${field2}" is not one.`);
2791
+ }
2792
+ if (direction !== "asc" && direction !== "desc") {
2793
+ throw new Error(`Order for "${model2.key}.${field2}" must be "asc" or "desc".`);
2794
+ }
2795
+ order2[field2] = direction;
2796
+ }
2797
+ const engine = {
2798
+ ...measures.engine,
2799
+ groupBy: by,
2800
+ ...Object.keys(order2).length > 0 ? { order: order2 } : {},
2801
+ ...args.take !== void 0 ? { limit: args.take } : {}
2802
+ };
2803
+ return new Query(
2804
+ runtime,
2805
+ document({ where: args.where }, { limit: 0, aggregate: engine }),
2806
+ (_data, pageInfo) => (pageInfo[model2.key]?.aggregate ?? []).map((group) => ({
2807
+ ...group.key,
2808
+ ...measures.output(group)
2809
+ })),
2810
+ "groupBy"
2811
+ );
2812
+ },
2813
+ create: ({ data }) => {
2814
+ const rowId = typeof data.id === "string" ? data.id : id();
2815
+ const { values, before, after } = splitData(
2816
+ runtime.graph,
2817
+ model2,
2818
+ rowId,
2819
+ data,
2820
+ true
2821
+ );
2822
+ return new Write(
2823
+ runtime,
2824
+ [
2825
+ ...before,
2826
+ { op: "insert", namespace: model2.key, id: rowId, values: withDefaults(model2, values) },
2827
+ ...after
2828
+ ],
2829
+ rowId
2830
+ );
2831
+ },
2832
+ update: ({ where, data }) => {
2833
+ const rowId = requireId(model2, where);
2834
+ const { values, before, after } = splitData(
2835
+ runtime.graph,
2836
+ model2,
2837
+ rowId,
2838
+ data,
2839
+ true
2840
+ );
2841
+ return new Write(
2842
+ runtime,
2843
+ [...before, { op: "patch", namespace: model2.key, id: rowId, values }, ...after],
2844
+ rowId
2845
+ );
2846
+ },
2847
+ upsert: ({ where, create, update }) => {
2848
+ const rowId = requireId(model2, where);
2849
+ const created = splitData(runtime.graph, model2, rowId, create, false);
2850
+ const updated = splitData(runtime.graph, model2, rowId, update, false);
2851
+ return new Write(
2852
+ runtime,
2853
+ [
2854
+ {
2855
+ op: "upsert",
2856
+ namespace: model2.key,
2857
+ id: rowId,
2858
+ values: updated.values,
2859
+ create: withDefaults(model2, created.values)
2860
+ }
2861
+ ],
2862
+ rowId
2863
+ );
2864
+ },
2865
+ delete: ({ where }) => {
2866
+ const rowId = requireId(model2, where);
2867
+ return new Write(runtime, [{ op: "delete", namespace: model2.key, id: rowId }], rowId);
2868
+ },
2869
+ updateMany: async ({ where, data }) => {
2870
+ const { values, after } = splitData(runtime.graph, model2, "", data, false);
2871
+ if (after.length > 0) {
2872
+ throw new Error(`"${model2.key}.updateMany" cannot connect or disconnect relations.`);
2873
+ }
2874
+ return runtime.impl.bulk({
2875
+ op: "patchMany",
2876
+ namespace: model2.key,
2877
+ where: toEngineWhere(model2, where, runtime.graph),
2878
+ values
2879
+ });
2880
+ },
2881
+ deleteMany: async ({ where }) => runtime.impl.bulk({
2882
+ op: "deleteMany",
2883
+ namespace: model2.key,
2884
+ where: toEngineWhere(model2, where, runtime.graph)
2885
+ })
2886
+ };
2887
+ }
2888
+ function createClient(config, deps = {}) {
2889
+ const { client: parts, impl } = createClientParts(
2890
+ {
2891
+ workspaceId: config.workspace,
2892
+ userId: config.userId,
2893
+ apiUrl: config.url,
2894
+ getToken: config.getToken,
2895
+ schema: config.schema.clientSchema,
2896
+ onWriteRejected: config.onWriteRejected
2897
+ },
2898
+ deps
2899
+ );
2900
+ const runtime = { impl, parts, graph: config.schema.graph, snapshots: /* @__PURE__ */ new Map() };
2901
+ const extras = {
2902
+ async $transaction(writes) {
2903
+ if (writes.length === 0) return [];
2904
+ const status = await impl.transact(writes.flatMap((write) => write.ops));
2905
+ return writes.map((write) => ({ id: write.id, status }));
2906
+ },
2907
+ $files: {
2908
+ upload: (file, { path }) => parts.files.upload(path, file),
2909
+ download: (path) => parts.files.download(path),
2910
+ delete: (path) => parts.files.delete(path),
2911
+ list: async ({ prefix } = {}) => {
2912
+ const files = await impl.listFiles();
2913
+ return prefix === void 0 ? files : files.filter((file) => file.path.startsWith(prefix));
2914
+ }
2915
+ },
2916
+ $presence: (room) => ({
2917
+ set: (presence) => impl.publishPresence(room, presence),
2918
+ cursor: (cursor) => impl.publishCursor(room, cursor),
2919
+ drag: (drag) => impl.publishDrag(room, drag),
2920
+ clearDrag: () => impl.clearDrag(room),
2921
+ subscribe: (listener) => impl.subscribePresence(room, listener),
2922
+ leave: () => impl.clearPresence(room)
2923
+ }),
2924
+ $broadcast: (topic) => {
2925
+ if (!/^[A-Za-z0-9:_.-]{1,128}$/.test(topic)) {
2926
+ throw new Error(`"${topic}" is not a topic name: use 1-128 of A-Z a-z 0-9 : _ . -`);
2927
+ }
2928
+ return {
2929
+ send: (message) => impl.sendTopic(topic, message),
2930
+ subscribe: (listener, options) => impl.subscribeTopic(topic, {
2931
+ message: (message, from) => listener(message, from),
2932
+ error: options?.onError
2933
+ })
2934
+ };
2935
+ },
2936
+ $erasePerson: (subject) => impl.erasePerson(subject),
2937
+ $history: ({ model: model2, id: id2 }) => impl.history(model2, id2),
2938
+ $export: () => impl.exportRecords(),
2939
+ $flush: () => impl.flushOutbox(),
2940
+ $close: () => {
2941
+ impl.close();
2942
+ for (const other of acrossClients.values()) other.$close();
2943
+ acrossClients.clear();
2944
+ }
2945
+ };
2946
+ const acrossClients = /* @__PURE__ */ new Map();
2947
+ const acrossTokens = /* @__PURE__ */ new Map();
2948
+ const across = (workspaceIds, options = {}) => {
2949
+ if (!Array.isArray(workspaceIds) || workspaceIds.length === 0) {
2950
+ throw new Error("$across needs at least one workspace id.");
2951
+ }
2952
+ const ids = [...new Set(workspaceIds)];
2953
+ if (config.getToken && !options.getToken) {
2954
+ throw new Error("$across needs getToken(workspaceId): each workspace has its own claim.");
2955
+ }
2956
+ const clients = ids.map((workspaceId) => {
2957
+ if (workspaceId === config.workspace) return { workspaceId, client };
2958
+ if (options.getToken) acrossTokens.set(workspaceId, options.getToken);
2959
+ let other = acrossClients.get(workspaceId);
2960
+ if (!other) {
2961
+ other = createClient(
2962
+ {
2963
+ ...config,
2964
+ workspace: workspaceId,
2965
+ ...options.getToken ? { getToken: () => acrossTokens.get(workspaceId)(workspaceId) } : {}
2966
+ },
2967
+ deps
2968
+ );
2969
+ acrossClients.set(workspaceId, other);
2970
+ }
2971
+ return { workspaceId, client: other };
2972
+ });
2973
+ const out = {};
2974
+ for (const key of Object.keys(config.schema.graph)) {
2975
+ out[key] = acrossModel(
2976
+ clients.map(({ workspaceId, client: one }) => ({
2977
+ workspaceId,
2978
+ model: one[key]
2979
+ }))
2980
+ );
2981
+ }
2982
+ return out;
2983
+ };
2984
+ const client = { ...extras, $across: across };
2985
+ for (const [key, info] of Object.entries(config.schema.graph)) {
2986
+ client[key] = modelClient(runtime, info);
2987
+ }
2988
+ return client;
2989
+ }
2990
+ export {
2991
+ AcrossError,
2992
+ PageQuery,
2993
+ Query,
2994
+ WORKSPACE_ROLE_LEVELS,
2995
+ Write,
2996
+ check,
2997
+ createClient,
2998
+ filter,
2999
+ hasRole,
3000
+ hasRoleLevel,
3001
+ id,
3002
+ model,
3003
+ role,
3004
+ schema,
3005
+ t
3006
+ };
3007
+ //# sourceMappingURL=index.js.map