@cf-sync/client 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/LICENSE +21 -0
- package/README.md +32 -0
- package/dist/client-tvsT_ixa.d.ts +714 -0
- package/dist/index.d.ts +139 -0
- package/dist/index.js +2051 -0
- package/dist/react.d.ts +49 -0
- package/dist/react.js +53 -0
- package/package.json +76 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,2051 @@
|
|
|
1
|
+
import { AppError, AppError as AppError$1, CLOSE_AUTH_CONTEXT_INVALID, CLOSE_PERMANENT_MAX, CLOSE_PERMANENT_MIN, CLOSE_REFRESH, CLOSE_REFRESH as CLOSE_REFRESH$1, CLOSE_SUPERSEDED, CLOSE_UNAUTHORIZED, CLOSE_VERSION_NOT_SUPPORTED, MAX_PRESENCE_BYTES, crudMutators, defineApp, defineMutators, defineSchema, isPermanentCloseCode, isPermanentCloseCode as isPermanentCloseCode$1 } from "@cf-sync/protocol";
|
|
2
|
+
import { KEEPALIVE_PING, PROTOCOL_VERSION, cursorEquals, formatIssues, jsonByteSize, serverMsgSchema } from "@cf-sync/protocol/internal";
|
|
3
|
+
import { createCollection, createTransaction } from "@tanstack/db";
|
|
4
|
+
//#region src/idb-store.ts
|
|
5
|
+
const ROWS = "rows";
|
|
6
|
+
const META = "meta";
|
|
7
|
+
const OUTBOX = "outbox";
|
|
8
|
+
function request(req) {
|
|
9
|
+
return new Promise((resolve, reject) => {
|
|
10
|
+
req.onsuccess = () => resolve(req.result);
|
|
11
|
+
req.onerror = () => reject(req.error ?? /* @__PURE__ */ new Error("IndexedDB request failed"));
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
function txnDone(txn) {
|
|
15
|
+
return new Promise((resolve, reject) => {
|
|
16
|
+
txn.oncomplete = () => resolve();
|
|
17
|
+
txn.onabort = () => reject(txn.error ?? /* @__PURE__ */ new Error("IndexedDB transaction aborted"));
|
|
18
|
+
txn.onerror = () => reject(txn.error ?? /* @__PURE__ */ new Error("IndexedDB transaction failed"));
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* SyncStore over IndexedDB. Rows, cursor, and outbox commit in a single
|
|
23
|
+
* IndexedDB transaction spanning all three object stores, which is what
|
|
24
|
+
* upholds the cursor-never-newer-than-rows contract.
|
|
25
|
+
*
|
|
26
|
+
* The rows and meta stores are shared by every tab on the workspace; a
|
|
27
|
+
* subsumption guard makes concurrent writers safe: a poke whose cursor does
|
|
28
|
+
* not advance past the stored one is skipped, because catch-up patches carry
|
|
29
|
+
* current row state (not historical deltas), so the newer writer's rows
|
|
30
|
+
* already cover it. Outbox records are per-clientId, so tabs never touch
|
|
31
|
+
* each other's pending mutations.
|
|
32
|
+
*
|
|
33
|
+
* All operations run through an internal queue, preserving call order even
|
|
34
|
+
* though callers fire-and-forget.
|
|
35
|
+
*/
|
|
36
|
+
var IndexedDBSyncStore = class {
|
|
37
|
+
#dbName;
|
|
38
|
+
#clientId;
|
|
39
|
+
#outboxMaxAgeMs;
|
|
40
|
+
#factory;
|
|
41
|
+
#db = null;
|
|
42
|
+
#queue = Promise.resolve();
|
|
43
|
+
constructor(opts) {
|
|
44
|
+
this.#dbName = `${opts.dbNamePrefix ?? "cf-sync"}:${opts.workspaceId}`;
|
|
45
|
+
this.#clientId = opts.clientId;
|
|
46
|
+
this.#outboxMaxAgeMs = opts.outboxMaxAgeMs ?? 720 * 60 * 60 * 1e3;
|
|
47
|
+
this.#factory = opts.indexedDB ?? globalThis.indexedDB;
|
|
48
|
+
if (!this.#factory) throw new Error("IndexedDB is not available in this environment");
|
|
49
|
+
}
|
|
50
|
+
#open() {
|
|
51
|
+
if (this.#db) return this.#db;
|
|
52
|
+
this.#db = new Promise((resolve, reject) => {
|
|
53
|
+
const req = this.#factory.open(this.#dbName, 1);
|
|
54
|
+
req.onupgradeneeded = () => {
|
|
55
|
+
const db = req.result;
|
|
56
|
+
if (!db.objectStoreNames.contains(ROWS)) db.createObjectStore(ROWS);
|
|
57
|
+
if (!db.objectStoreNames.contains(META)) db.createObjectStore(META);
|
|
58
|
+
if (!db.objectStoreNames.contains(OUTBOX)) db.createObjectStore(OUTBOX);
|
|
59
|
+
};
|
|
60
|
+
req.onsuccess = () => resolve(req.result);
|
|
61
|
+
req.onerror = () => reject(req.error ?? /* @__PURE__ */ new Error("failed to open IndexedDB"));
|
|
62
|
+
req.onblocked = () => reject(/* @__PURE__ */ new Error("IndexedDB open blocked by another connection"));
|
|
63
|
+
});
|
|
64
|
+
return this.#db;
|
|
65
|
+
}
|
|
66
|
+
#enqueue(op) {
|
|
67
|
+
const result = this.#queue.then(op);
|
|
68
|
+
this.#queue = result.catch(() => {});
|
|
69
|
+
return result;
|
|
70
|
+
}
|
|
71
|
+
load() {
|
|
72
|
+
return this.#enqueue(async () => {
|
|
73
|
+
const txn = (await this.#open()).transaction([
|
|
74
|
+
ROWS,
|
|
75
|
+
META,
|
|
76
|
+
OUTBOX
|
|
77
|
+
], "readwrite");
|
|
78
|
+
const meta = await request(txn.objectStore(META).get("state"));
|
|
79
|
+
const outboxStore = txn.objectStore(OUTBOX);
|
|
80
|
+
const mine = await request(outboxStore.get(this.#clientId));
|
|
81
|
+
const staleBefore = Date.now() - this.#outboxMaxAgeMs;
|
|
82
|
+
const keys = await request(outboxStore.getAllKeys());
|
|
83
|
+
for (const key of keys) {
|
|
84
|
+
if (key === this.#clientId) continue;
|
|
85
|
+
const record = await request(outboxStore.get(key));
|
|
86
|
+
if (record && record.updatedAt < staleBefore) outboxStore.delete(key);
|
|
87
|
+
}
|
|
88
|
+
let rows = [];
|
|
89
|
+
if (meta) {
|
|
90
|
+
const rowStore = txn.objectStore(ROWS);
|
|
91
|
+
const values = await request(rowStore.getAll());
|
|
92
|
+
rows = (await request(rowStore.getAllKeys())).map((key, i) => ({
|
|
93
|
+
tbl: key[0],
|
|
94
|
+
id: key[1],
|
|
95
|
+
value: values[i]
|
|
96
|
+
}));
|
|
97
|
+
}
|
|
98
|
+
await txnDone(txn);
|
|
99
|
+
if (!meta && !mine) return null;
|
|
100
|
+
return {
|
|
101
|
+
schemaVersion: meta?.schemaVersion ?? null,
|
|
102
|
+
cursor: meta?.cursor ?? null,
|
|
103
|
+
confirmedLmid: mine?.confirmedLmid ?? 0,
|
|
104
|
+
rows,
|
|
105
|
+
outbox: mine?.entries ?? []
|
|
106
|
+
};
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
applyPoke(update) {
|
|
110
|
+
return this.#enqueue(async () => {
|
|
111
|
+
const txn = (await this.#open()).transaction([
|
|
112
|
+
ROWS,
|
|
113
|
+
META,
|
|
114
|
+
OUTBOX
|
|
115
|
+
], "readwrite");
|
|
116
|
+
const metaStore = txn.objectStore(META);
|
|
117
|
+
const stored = await request(metaStore.get("state"));
|
|
118
|
+
if (!(!update.clear && stored !== void 0 && stored.cursor.backendId === update.cursor.backendId && stored.cursor.version >= update.cursor.version)) {
|
|
119
|
+
const rowStore = txn.objectStore(ROWS);
|
|
120
|
+
if (update.clear) rowStore.clear();
|
|
121
|
+
for (const op of update.ops) if (op.op === "put") rowStore.put(op.value, [op.tbl, op.id]);
|
|
122
|
+
else rowStore.delete([op.tbl, op.id]);
|
|
123
|
+
metaStore.put({
|
|
124
|
+
schemaVersion: update.schemaVersion,
|
|
125
|
+
cursor: update.cursor
|
|
126
|
+
}, "state");
|
|
127
|
+
}
|
|
128
|
+
txn.objectStore(OUTBOX).put({
|
|
129
|
+
entries: update.outbox,
|
|
130
|
+
confirmedLmid: update.confirmedLmid,
|
|
131
|
+
updatedAt: Date.now()
|
|
132
|
+
}, this.#clientId);
|
|
133
|
+
await txnDone(txn);
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
saveOutbox(outbox, confirmedLmid) {
|
|
137
|
+
return this.#enqueue(async () => {
|
|
138
|
+
const txn = (await this.#open()).transaction(OUTBOX, "readwrite");
|
|
139
|
+
txn.objectStore(OUTBOX).put({
|
|
140
|
+
entries: outbox,
|
|
141
|
+
confirmedLmid,
|
|
142
|
+
updatedAt: Date.now()
|
|
143
|
+
}, this.#clientId);
|
|
144
|
+
await txnDone(txn);
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
reset() {
|
|
148
|
+
return this.#enqueue(async () => {
|
|
149
|
+
const txn = (await this.#open()).transaction([
|
|
150
|
+
ROWS,
|
|
151
|
+
META,
|
|
152
|
+
OUTBOX
|
|
153
|
+
], "readwrite");
|
|
154
|
+
txn.objectStore(ROWS).clear();
|
|
155
|
+
txn.objectStore(META).clear();
|
|
156
|
+
txn.objectStore(OUTBOX).clear();
|
|
157
|
+
await txnDone(txn);
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
/** Closes the database connection (tests and teardown). */
|
|
161
|
+
async close() {
|
|
162
|
+
if (!this.#db) return;
|
|
163
|
+
(await this.#db).close();
|
|
164
|
+
this.#db = null;
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
//#endregion
|
|
168
|
+
//#region src/defaults.ts
|
|
169
|
+
const consoleLogger = (level, message, ...detail) => console[level](message, ...detail);
|
|
170
|
+
/**
|
|
171
|
+
* `<base><prefix>/<workspaceId>?clientId=<id>` — the shape createSyncFetch
|
|
172
|
+
* routes. `http(s)` is mapped to `ws(s)`; a trailing slash on the base is
|
|
173
|
+
* tolerated so `location.origin`-derived URLs compose cleanly. A query or
|
|
174
|
+
* fragment on the base is rejected at construction: the sync path is
|
|
175
|
+
* appended after it, so the URL would come out malformed — credentials
|
|
176
|
+
* belong in the `authToken` option, which appends per connection attempt.
|
|
177
|
+
*/
|
|
178
|
+
function buildSyncUrl(base, prefix, workspaceId, clientId) {
|
|
179
|
+
if (base.includes("?") || base.includes("#")) throw new Error(`SyncClient: url must not carry a query or fragment (got "${base}") — the sync path is appended to it. To send a credential, use the authToken option; it rides the URL as ?token=… on every connection attempt.`);
|
|
180
|
+
return `${base.replace(/^http/, "ws").replace(/\/+$/, "")}${prefix}/${encodeURIComponent(workspaceId)}?clientId=${encodeURIComponent(clientId)}`;
|
|
181
|
+
}
|
|
182
|
+
/** The sync URL always ends in `?clientId=…`, so the token appends with `&`. */
|
|
183
|
+
function withToken(url, token) {
|
|
184
|
+
return `${url}&token=${encodeURIComponent(token)}`;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* One clientId per tab/session, per workspace: the clientId names a
|
|
188
|
+
* contiguous mutation sequence, so concurrent tabs must never share one.
|
|
189
|
+
* sessionStorage gives reload continuity without cross-tab sharing; where it
|
|
190
|
+
* is unavailable (SSR, workers, blocked storage), a fresh random id per
|
|
191
|
+
* instance is always safe — it just forfeits reload continuity.
|
|
192
|
+
*/
|
|
193
|
+
function defaultClientId(workspaceId) {
|
|
194
|
+
const key = `cf-sync:client-id:${encodeURIComponent(workspaceId)}`;
|
|
195
|
+
try {
|
|
196
|
+
const stored = sessionStorage.getItem(key);
|
|
197
|
+
if (stored) return stored;
|
|
198
|
+
const id = crypto.randomUUID();
|
|
199
|
+
sessionStorage.setItem(key, id);
|
|
200
|
+
return id;
|
|
201
|
+
} catch {
|
|
202
|
+
return crypto.randomUUID();
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
const FATAL_RELOAD_MIN_INTERVAL_MS = 6e4;
|
|
206
|
+
/**
|
|
207
|
+
* Default fatal handling: reload into the (presumably newer) bundle — the
|
|
208
|
+
* protocol's designed recovery for VersionNotSupported — throttled per
|
|
209
|
+
* workspace so a bad deploy window (stale web assets, a rollback that left
|
|
210
|
+
* the client ahead of the server) degrades to one reload per minute instead
|
|
211
|
+
* of a reload loop. Outside the browser there is nothing to reload; the
|
|
212
|
+
* client just stays stopped in 'fatal'.
|
|
213
|
+
*/
|
|
214
|
+
function defaultFatalRecovery(workspaceId, error, log) {
|
|
215
|
+
if (typeof location === "undefined") {
|
|
216
|
+
log("warn", "[cf-sync] fatal, and no onFatal handler to recover:", error);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
const key = `cf-sync:fatal-reload:${encodeURIComponent(workspaceId)}`;
|
|
220
|
+
let lastReloadAt = 0;
|
|
221
|
+
try {
|
|
222
|
+
lastReloadAt = Number(sessionStorage.getItem(key)) || 0;
|
|
223
|
+
} catch {}
|
|
224
|
+
if (Date.now() - lastReloadAt < FATAL_RELOAD_MIN_INTERVAL_MS) {
|
|
225
|
+
log("warn", "[cf-sync] fatal again within a minute of reloading — waiting instead of looping (deploy skew?):", error);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
try {
|
|
229
|
+
sessionStorage.setItem(key, String(Date.now()));
|
|
230
|
+
} catch {}
|
|
231
|
+
log("warn", "[cf-sync] fatal; reloading to pick up the current bundle:", error);
|
|
232
|
+
location.reload();
|
|
233
|
+
}
|
|
234
|
+
function createDefaultStore(workspaceId, clientId, log) {
|
|
235
|
+
try {
|
|
236
|
+
return new IndexedDBSyncStore({
|
|
237
|
+
workspaceId,
|
|
238
|
+
clientId
|
|
239
|
+
});
|
|
240
|
+
} catch (err) {
|
|
241
|
+
log("warn", "[cf-sync] persist: true, but IndexedDB is unavailable — continuing without local persistence", err);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
//#endregion
|
|
246
|
+
//#region src/errors.ts
|
|
247
|
+
/**
|
|
248
|
+
* The error a refused mutation settles with — what an awaited `mutate` call
|
|
249
|
+
* rejects with and what `onMutationRejected` receives. `code` is the
|
|
250
|
+
* branchable identity, drawn from three groups: the engine's built-in
|
|
251
|
+
* rejections ({@link EngineErrorCode}, e.g. `InvalidArgs`,
|
|
252
|
+
* `UnknownMutator`), the client-local outcomes (`Timeout`, `Stopped`,
|
|
253
|
+
* `Fatal`, `LocalApplyFailed`), and app-defined `AppError` codes passed
|
|
254
|
+
* through verbatim — {@link MutationErrorCode} is the full vocabulary.
|
|
255
|
+
* `message` is diagnostic prose; branch on `code`, not on it. `mutation`
|
|
256
|
+
* carries the rejected mutation's name and args when the client knows them —
|
|
257
|
+
* an awaiting `catch` gets the same context `onMutationRejected` receives.
|
|
258
|
+
*/
|
|
259
|
+
var MutationError = class extends Error {
|
|
260
|
+
code;
|
|
261
|
+
mutation;
|
|
262
|
+
constructor(code, message, mutation) {
|
|
263
|
+
super(message);
|
|
264
|
+
this.code = code;
|
|
265
|
+
this.mutation = mutation;
|
|
266
|
+
this.name = "MutationError";
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
/**
|
|
270
|
+
* What `onFatal` receives when the server permanently rejects this client.
|
|
271
|
+
* `reason` is the close frame's slug (`membership-revoked`,
|
|
272
|
+
* `project-deleted`) — stable strings apps can branch on.
|
|
273
|
+
*/
|
|
274
|
+
var SyncFatalError = class extends Error {
|
|
275
|
+
code;
|
|
276
|
+
reason;
|
|
277
|
+
constructor(code, reason) {
|
|
278
|
+
super(`sync connection permanently rejected (${code}): ${reason}`);
|
|
279
|
+
this.code = code;
|
|
280
|
+
this.reason = reason;
|
|
281
|
+
this.name = "SyncFatalError";
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
/** Signals the speculative run touched a table with no attached collection (degrade, not error). */
|
|
285
|
+
var MissingApplierError = class extends Error {
|
|
286
|
+
tbl;
|
|
287
|
+
constructor(tbl) {
|
|
288
|
+
super(`no collection attached for table "${tbl}"`);
|
|
289
|
+
this.tbl = tbl;
|
|
290
|
+
this.name = "MissingApplierError";
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
//#endregion
|
|
294
|
+
//#region src/local-writes.ts
|
|
295
|
+
/**
|
|
296
|
+
* Buffers a single intent's local writes — the client mirror of the server's
|
|
297
|
+
* WriteSet (ARCHITECTURE.md#mutation-processing). Reads see the mutation's own buffer first, then
|
|
298
|
+
* fall through to the table's collection (whose view already includes earlier
|
|
299
|
+
* pending intents' overlays, so overlapping intents read each other). Any
|
|
300
|
+
* touched table without an attached collection aborts the speculative run via
|
|
301
|
+
* `MissingApplierError` — a partial overlay would be worse than none.
|
|
302
|
+
*/
|
|
303
|
+
var LocalWriteSet = class {
|
|
304
|
+
schema;
|
|
305
|
+
appliers;
|
|
306
|
+
#puts = /* @__PURE__ */ new Map();
|
|
307
|
+
#dels = /* @__PURE__ */ new Map();
|
|
308
|
+
constructor(schema, appliers) {
|
|
309
|
+
this.schema = schema;
|
|
310
|
+
this.appliers = appliers;
|
|
311
|
+
}
|
|
312
|
+
#applier(tbl) {
|
|
313
|
+
const applier = this.appliers.get(tbl);
|
|
314
|
+
if (!applier) throw new MissingApplierError(tbl);
|
|
315
|
+
return applier;
|
|
316
|
+
}
|
|
317
|
+
tx = {
|
|
318
|
+
get: (tbl, id) => {
|
|
319
|
+
const applier = this.#applier(tbl);
|
|
320
|
+
const k = rowKey(tbl, id);
|
|
321
|
+
if (this.#dels.has(k)) return null;
|
|
322
|
+
const buffered = this.#puts.get(k);
|
|
323
|
+
if (buffered) return structuredClone(buffered.data);
|
|
324
|
+
const row = applier.get(id);
|
|
325
|
+
return row ? structuredClone(row) : null;
|
|
326
|
+
},
|
|
327
|
+
list: (tbl) => {
|
|
328
|
+
const applier = this.#applier(tbl);
|
|
329
|
+
const merged = /* @__PURE__ */ new Map();
|
|
330
|
+
for (const { id, data } of applier.list()) merged.set(id, structuredClone(data));
|
|
331
|
+
for (const del of this.#dels.values()) if (del.tbl === tbl) merged.delete(del.id);
|
|
332
|
+
for (const put of this.#puts.values()) if (put.tbl === tbl) merged.set(put.id, structuredClone(put.data));
|
|
333
|
+
return [...merged].map(([id, data]) => ({
|
|
334
|
+
id,
|
|
335
|
+
data
|
|
336
|
+
}));
|
|
337
|
+
},
|
|
338
|
+
put: (tbl, id, data) => {
|
|
339
|
+
const stored = validateLocalRow(this.schema, tbl, id, data);
|
|
340
|
+
this.#applier(tbl);
|
|
341
|
+
const k = rowKey(tbl, id);
|
|
342
|
+
this.#dels.delete(k);
|
|
343
|
+
this.#puts.set(k, {
|
|
344
|
+
tbl,
|
|
345
|
+
id,
|
|
346
|
+
data: stored
|
|
347
|
+
});
|
|
348
|
+
},
|
|
349
|
+
del: (tbl, id) => {
|
|
350
|
+
this.#applier(tbl);
|
|
351
|
+
const k = rowKey(tbl, id);
|
|
352
|
+
this.#puts.delete(k);
|
|
353
|
+
this.#dels.set(k, {
|
|
354
|
+
tbl,
|
|
355
|
+
id
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
isEmpty() {
|
|
360
|
+
return this.#puts.size === 0 && this.#dels.size === 0;
|
|
361
|
+
}
|
|
362
|
+
puts() {
|
|
363
|
+
return this.#puts.values();
|
|
364
|
+
}
|
|
365
|
+
dels() {
|
|
366
|
+
return this.#dels.values();
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
function rowKey(tbl, id) {
|
|
370
|
+
return `${tbl}\u0000${id}`;
|
|
371
|
+
}
|
|
372
|
+
/** The client mirror of the server's `validateRow`: parsed output in the overlay, or a permanent AppError. */
|
|
373
|
+
function validateLocalRow(schema, tbl, id, data) {
|
|
374
|
+
const tableSchema = schema.tables[tbl];
|
|
375
|
+
if (!tableSchema) throw new AppError$1("InvalidArgs", `table "${tbl}" is not defined in the schema`);
|
|
376
|
+
const result = tableSchema["~standard"].validate(data);
|
|
377
|
+
if (result instanceof Promise) {
|
|
378
|
+
result.catch(() => {});
|
|
379
|
+
throw new AppError$1("InvalidArgs", `table "${tbl}": async validation is not supported`);
|
|
380
|
+
}
|
|
381
|
+
if (result.issues) throw new AppError$1("InvalidArgs", `invalid row ${tbl}/${id}: ${formatIssues(result.issues)}`);
|
|
382
|
+
return result.value;
|
|
383
|
+
}
|
|
384
|
+
//#endregion
|
|
385
|
+
//#region src/mutate.ts
|
|
386
|
+
/**
|
|
387
|
+
* Builds the callable namespace tree from the registry's names. The root is a
|
|
388
|
+
* function (the string-name form), so leaves and namespaces are attached with
|
|
389
|
+
* defineProperty — plain assignment would throw for names that shadow
|
|
390
|
+
* non-writable function properties like "name" or "length".
|
|
391
|
+
*/
|
|
392
|
+
function buildMutate(names, invoke) {
|
|
393
|
+
const define = (node, key, value) => {
|
|
394
|
+
Object.defineProperty(node, key, {
|
|
395
|
+
value,
|
|
396
|
+
enumerable: true,
|
|
397
|
+
configurable: true,
|
|
398
|
+
writable: true
|
|
399
|
+
});
|
|
400
|
+
};
|
|
401
|
+
const root = (name, ...rest) => invoke(name, rest[0]);
|
|
402
|
+
for (const name of names) {
|
|
403
|
+
const segments = name.split(".");
|
|
404
|
+
let node = root;
|
|
405
|
+
for (const segment of segments.slice(0, -1)) {
|
|
406
|
+
if (!Object.prototype.hasOwnProperty.call(node, segment)) define(node, segment, {});
|
|
407
|
+
node = node[segment];
|
|
408
|
+
}
|
|
409
|
+
const leaf = segments[segments.length - 1];
|
|
410
|
+
const call = (...rest) => invoke(name, rest[0]);
|
|
411
|
+
const existing = Object.prototype.hasOwnProperty.call(node, leaf) ? node[leaf] : void 0;
|
|
412
|
+
if (existing !== void 0 && typeof existing === "object") Object.assign(call, existing);
|
|
413
|
+
define(node, leaf, call);
|
|
414
|
+
}
|
|
415
|
+
return root;
|
|
416
|
+
}
|
|
417
|
+
//#endregion
|
|
418
|
+
//#region src/types.ts
|
|
419
|
+
/**
|
|
420
|
+
* Internal seam for the collection adapter: enqueue a mutation *without* the
|
|
421
|
+
* speculative local run. Collection mutation handlers (`onInsert` etc.) must
|
|
422
|
+
* use this — their optimistic effect already happened via the collection
|
|
423
|
+
* write itself, and routing them through `mutate` would recursively spawn a
|
|
424
|
+
* second transaction re-applying it. Not part of the public API.
|
|
425
|
+
*/
|
|
426
|
+
const RAW_MUTATE = Symbol("cf-sync.rawMutate");
|
|
427
|
+
//#endregion
|
|
428
|
+
//#region src/client.ts
|
|
429
|
+
/**
|
|
430
|
+
* The per-workspace sync client: it owns the WebSocket to the workspace's
|
|
431
|
+
* Durable Object, the outbox of unconfirmed mutations, optimistic application
|
|
432
|
+
* and rollback, presence, and reconnection with cursor catch-up. Construct
|
|
433
|
+
* one instance per workspace per tab — the clientId names one contiguous
|
|
434
|
+
* mutation sequence, so concurrent tabs must never share one (the managed
|
|
435
|
+
* default handles this) — and it connects on construction unless
|
|
436
|
+
* `autoStart: false`. The shared `defineApp` value passed in
|
|
437
|
+
* {@link SyncClientOptions} types `mutate` and the collections;
|
|
438
|
+
* `persist: true` adds the IndexedDB row mirror and a reload-surviving
|
|
439
|
+
* outbox.
|
|
440
|
+
*
|
|
441
|
+
* Attach TanStack DB collections with `createCollections` (or per-table
|
|
442
|
+
* `workspaceCollectionOptions`) for reads and optimistic writes; drive
|
|
443
|
+
* domain logic through {@link mutate}, which runs the shared mutator locally
|
|
444
|
+
* for an instant overlay and settles on the server's verdict. To switch
|
|
445
|
+
* workspaces, {@link destroy} this client and construct a fresh one.
|
|
446
|
+
*
|
|
447
|
+
* @example
|
|
448
|
+
* ```ts
|
|
449
|
+
* import { SyncClient, createCollections } from '@cf-sync/client'
|
|
450
|
+
* import { app } from './schema' // the shared defineApp value
|
|
451
|
+
*
|
|
452
|
+
* const client = new SyncClient({
|
|
453
|
+
* url: 'wss://sync.example.com', // ws://localhost:8787 in dev
|
|
454
|
+
* workspaceId: 'my-first-workspace',
|
|
455
|
+
* app,
|
|
456
|
+
* persist: true, // IndexedDB mirror + durable offline outbox
|
|
457
|
+
* })
|
|
458
|
+
*
|
|
459
|
+
* const { todos } = createCollections(client)
|
|
460
|
+
*
|
|
461
|
+
* // Optimistic local write, synced as a full-row mutation:
|
|
462
|
+
* todos.insert({ id: crypto.randomUUID(), title: 'ship it' })
|
|
463
|
+
*
|
|
464
|
+
* // Typed intent mutation — instant locally, authoritative on the server:
|
|
465
|
+
* await client.mutate.todo.toggle({ id })
|
|
466
|
+
* ```
|
|
467
|
+
*/
|
|
468
|
+
var SyncClient = class {
|
|
469
|
+
#opts;
|
|
470
|
+
#clientId;
|
|
471
|
+
#url;
|
|
472
|
+
#store;
|
|
473
|
+
#tables = /* @__PURE__ */ new Map();
|
|
474
|
+
#appliers = /* @__PURE__ */ new Map();
|
|
475
|
+
#warnedTables = /* @__PURE__ */ new Set();
|
|
476
|
+
#warnedNoApplier = /* @__PURE__ */ new Set();
|
|
477
|
+
#statusListeners = /* @__PURE__ */ new Set();
|
|
478
|
+
#binaryListeners = /* @__PURE__ */ new Set();
|
|
479
|
+
#rejectionListeners = /* @__PURE__ */ new Set();
|
|
480
|
+
#log(level, message, ...detail) {
|
|
481
|
+
(this.#opts.logger ?? consoleLogger)(level, message, ...detail);
|
|
482
|
+
}
|
|
483
|
+
#warnedBinaryType = false;
|
|
484
|
+
#intentRunner = null;
|
|
485
|
+
#socket = null;
|
|
486
|
+
#status = "idle";
|
|
487
|
+
#auth;
|
|
488
|
+
/** Bumped on every #connect entry; an async authToken resolution from a superseded attempt is dropped. */
|
|
489
|
+
#connectEpoch = 0;
|
|
490
|
+
/**
|
|
491
|
+
* Consecutive 4300 (refresh) closes with no intervening ready connection.
|
|
492
|
+
* Only the first reconnects immediately; a streak means something is
|
|
493
|
+
* refreshing on every connect (a bug, or a stuck webhook), and pacing the
|
|
494
|
+
* retries keeps that from becoming a zero-delay authorize storm (ARCHITECTURE.md#session-control).
|
|
495
|
+
*/
|
|
496
|
+
#refreshStreak = 0;
|
|
497
|
+
#cursor = null;
|
|
498
|
+
#confirmedLmid = 0;
|
|
499
|
+
#outbox = [];
|
|
500
|
+
#poke = null;
|
|
501
|
+
#syncedThisConnection = false;
|
|
502
|
+
#awaitingCatchUp = false;
|
|
503
|
+
#needsRebase = false;
|
|
504
|
+
#started = false;
|
|
505
|
+
#stopped = false;
|
|
506
|
+
#destroyed = false;
|
|
507
|
+
#teardown = /* @__PURE__ */ new Set();
|
|
508
|
+
#attempt = 0;
|
|
509
|
+
#reconnectTimer = null;
|
|
510
|
+
#retryPushTimer = null;
|
|
511
|
+
#flushScheduled = false;
|
|
512
|
+
#persistScheduled = false;
|
|
513
|
+
#hydrating = false;
|
|
514
|
+
/**
|
|
515
|
+
* The cache-ready latch (ARCHITECTURE.md#offline-first-render). True once hydration restored a
|
|
516
|
+
* cached snapshot and marked collections ready — the signal an offline
|
|
517
|
+
* launch renders on, since `status` is `connecting` on both sides of that
|
|
518
|
+
* edge and an empty collection can't be told from an unhydrated one.
|
|
519
|
+
*/
|
|
520
|
+
#hydrated = false;
|
|
521
|
+
#settleHydration = null;
|
|
522
|
+
#hydratedListeners = /* @__PURE__ */ new Set();
|
|
523
|
+
#whenHydrated = new Promise((resolve) => {
|
|
524
|
+
this.#settleHydration = resolve;
|
|
525
|
+
});
|
|
526
|
+
#heartbeatTimer = null;
|
|
527
|
+
#startNudgeTimer = null;
|
|
528
|
+
#lastFrameAt = 0;
|
|
529
|
+
#presencePeers = /* @__PURE__ */ new Map();
|
|
530
|
+
#presenceListeners = /* @__PURE__ */ new Set();
|
|
531
|
+
#presenceState = void 0;
|
|
532
|
+
#presenceSnapshot = null;
|
|
533
|
+
#presenceLive = false;
|
|
534
|
+
#presenceTimer = null;
|
|
535
|
+
/** One-time guard: the presence schema must parse its own output (ARCHITECTURE.md#presence). */
|
|
536
|
+
#presenceRoundTripChecked = false;
|
|
537
|
+
#presenceLastSentAt = 0;
|
|
538
|
+
/**
|
|
539
|
+
* Applies a named mutation optimistically and queues it for the server.
|
|
540
|
+
* Callable two ways — `mutate.todos.clearCompleted(args)` (dots in mutator
|
|
541
|
+
* names are namespaces; names and args are typed from the app's registry)
|
|
542
|
+
* or `mutate('todos.clearCompleted', args)` — both identical at runtime.
|
|
543
|
+
* Resolves when the server confirms the mutation (the client's LMID reaches
|
|
544
|
+
* the mutation's id), rejects on permanent app error or timeout. Args are
|
|
545
|
+
* validated locally before queueing (the wire still carries the original
|
|
546
|
+
* args — the server's parse is authoritative).
|
|
547
|
+
*
|
|
548
|
+
* When collections are attached (`createCollections` /
|
|
549
|
+
* `workspaceCollectionOptions`), the shared mutator's `apply` runs locally
|
|
550
|
+
* first against the collections' current view, and its writes land as one
|
|
551
|
+
* atomic optimistic overlay: visible immediately, swapped for the server's
|
|
552
|
+
* authoritative patch on confirm, rolled back together on rejection. The
|
|
553
|
+
* overlay is a frozen prediction — a remote change arriving mid-flight
|
|
554
|
+
* rebases the *originally computed* writes, and the confirm patch replaces
|
|
555
|
+
* them with the server's authoritative result (which ran against current
|
|
556
|
+
* state). A mutator that throws `AppError` locally rejects immediately and
|
|
557
|
+
* queues nothing; one that touches a table without an attached collection
|
|
558
|
+
* skips the overlay (warns once) but still reaches the server.
|
|
559
|
+
*
|
|
560
|
+
* Settlement is honest about durability: with a durable store
|
|
561
|
+
* (`persist`/`store`) the promise stays *pending* while offline — the
|
|
562
|
+
* mutation is queued durably and applies when connectivity returns, so a
|
|
563
|
+
* rejection always means the mutation will not apply (permanent app error,
|
|
564
|
+
* `destroy()`, or fatal). Only memory-only clients reject with `Timeout` after
|
|
565
|
+
* `confirmTimeoutMs`, discarding the mutation along with its overlay.
|
|
566
|
+
*/
|
|
567
|
+
mutate;
|
|
568
|
+
/** Ephemeral peer state on the sync socket — see {@link PresenceApi}. */
|
|
569
|
+
presence;
|
|
570
|
+
constructor(opts) {
|
|
571
|
+
if (!opts.workspaceId) throw new Error("SyncClient: workspaceId is required");
|
|
572
|
+
if (opts.store && opts.persist) throw new Error("SyncClient: pass either `store` or `persist`, not both");
|
|
573
|
+
this.#opts = opts;
|
|
574
|
+
this.#auth = opts.authContext;
|
|
575
|
+
if (opts.authContext !== void 0 && opts.app.authContext) {
|
|
576
|
+
const result = opts.app.authContext["~standard"].validate(opts.authContext);
|
|
577
|
+
if (result instanceof Promise) {
|
|
578
|
+
result.catch(() => {});
|
|
579
|
+
throw new Error("SyncClient: async authContext validation is not supported");
|
|
580
|
+
}
|
|
581
|
+
if (result.issues) throw new Error(`SyncClient: authContext fails the app's authContext schema: ${formatIssues(result.issues)}`);
|
|
582
|
+
this.#auth = result.value;
|
|
583
|
+
}
|
|
584
|
+
this.#clientId = opts.clientId ?? defaultClientId(opts.workspaceId);
|
|
585
|
+
this.#url = buildSyncUrl(opts.url, opts.pathPrefix ?? "/sync", opts.workspaceId, this.#clientId);
|
|
586
|
+
this.#store = opts.store ?? (opts.persist ? createDefaultStore(opts.workspaceId, this.#clientId, opts.logger ?? consoleLogger) : void 0);
|
|
587
|
+
this.mutate = buildMutate(Object.keys(opts.app.mutators), (name, args) => this.#guardMutation(name, args, this.#mutateByName(name, args)));
|
|
588
|
+
const self = this;
|
|
589
|
+
this.presence = {
|
|
590
|
+
set: (state) => this.#presenceSet(state),
|
|
591
|
+
update: (partial) => this.#presenceUpdate(partial),
|
|
592
|
+
clear: () => this.#presenceSet(null),
|
|
593
|
+
get self() {
|
|
594
|
+
return self.#presenceState === void 0 ? null : self.#presenceState;
|
|
595
|
+
},
|
|
596
|
+
get peers() {
|
|
597
|
+
return self.#presencePeersList();
|
|
598
|
+
},
|
|
599
|
+
subscribe: (listener) => {
|
|
600
|
+
self.#presenceListeners.add(listener);
|
|
601
|
+
return () => {
|
|
602
|
+
self.#presenceListeners.delete(listener);
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
};
|
|
606
|
+
if (opts.initialPresence !== void 0) this.#presenceSet(opts.initialPresence);
|
|
607
|
+
if (opts.autoStart !== false) this.start();
|
|
608
|
+
}
|
|
609
|
+
/** The current connection status — see {@link SyncStatus}; subscribe to changes via {@link subscribeStatus}. */
|
|
610
|
+
get status() {
|
|
611
|
+
return this.#status;
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* Whether locally cached data has been restored and collections are ready
|
|
615
|
+
* to render — the signal offline-first UIs gate their first paint on.
|
|
616
|
+
*
|
|
617
|
+
* `status` cannot answer this: it reads `connecting` both before and after
|
|
618
|
+
* hydration, so an offline launch holding a full cache looks exactly like
|
|
619
|
+
* one holding nothing. Nor can collection contents — an empty collection
|
|
620
|
+
* mid-hydration is indistinguishable from a genuinely empty workspace.
|
|
621
|
+
*
|
|
622
|
+
* True only when there was a cached snapshot to restore. It stays false
|
|
623
|
+
* when no store is configured, when the store is empty (a first launch),
|
|
624
|
+
* when the cache was discarded because it targets a different app version,
|
|
625
|
+
* and when the store failed to load — in each of those cases there is
|
|
626
|
+
* nothing cached to paint, and the UI should wait for the first sync:
|
|
627
|
+
*
|
|
628
|
+
* ```tsx
|
|
629
|
+
* // Render cached rows immediately when offline, otherwise wait for sync.
|
|
630
|
+
* const status = useSyncStatus(client)
|
|
631
|
+
* const hydrated = useHydrated(client)
|
|
632
|
+
* if (status !== 'synced' && !hydrated) return <Spinner />
|
|
633
|
+
* ```
|
|
634
|
+
*
|
|
635
|
+
* Subscribe to the transition via {@link subscribeHydrated}, or await
|
|
636
|
+
* {@link whenHydrated} outside React.
|
|
637
|
+
*/
|
|
638
|
+
get hydrated() {
|
|
639
|
+
return this.#hydrated;
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Resolves when hydration settles, with the value {@link hydrated} takes —
|
|
643
|
+
* true if a cached snapshot was restored, false if there was nothing to
|
|
644
|
+
* restore. The imperative form of the same signal, for gating a first
|
|
645
|
+
* render outside React:
|
|
646
|
+
*
|
|
647
|
+
* ```ts
|
|
648
|
+
* if (await client.whenHydrated) renderFromCache()
|
|
649
|
+
* ```
|
|
650
|
+
*
|
|
651
|
+
* A client constructed with `autoStart: false` settles this when `start()`
|
|
652
|
+
* runs, or with false if it is destroyed first — it never hangs past the
|
|
653
|
+
* client's life.
|
|
654
|
+
*/
|
|
655
|
+
get whenHydrated() {
|
|
656
|
+
return this.#whenHydrated;
|
|
657
|
+
}
|
|
658
|
+
/** The last server cursor this client applied, or null before the first sync. */
|
|
659
|
+
get cursor() {
|
|
660
|
+
return this.#cursor;
|
|
661
|
+
}
|
|
662
|
+
/** The workspace this client syncs, as passed at construction. */
|
|
663
|
+
get workspaceId() {
|
|
664
|
+
return this.#opts.workspaceId;
|
|
665
|
+
}
|
|
666
|
+
/** The resolved clientId — the configured one, or the library-managed default. */
|
|
667
|
+
get clientId() {
|
|
668
|
+
return this.#clientId;
|
|
669
|
+
}
|
|
670
|
+
/** The app definition this client was constructed with. */
|
|
671
|
+
get app() {
|
|
672
|
+
return this.#opts.app;
|
|
673
|
+
}
|
|
674
|
+
/** The table schema from the app definition (used by collections). */
|
|
675
|
+
get schema() {
|
|
676
|
+
return this.#opts.app.schema;
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* Subscribes to status changes; returns an unsubscribe function. An arrow
|
|
680
|
+
* property, so it can be passed around unbound — it plugs directly into
|
|
681
|
+
* React: `useSyncExternalStore(client.subscribeStatus, () => client.status)`.
|
|
682
|
+
*/
|
|
683
|
+
subscribeStatus = (listener) => {
|
|
684
|
+
this.#statusListeners.add(listener);
|
|
685
|
+
return () => {
|
|
686
|
+
this.#statusListeners.delete(listener);
|
|
687
|
+
};
|
|
688
|
+
};
|
|
689
|
+
/**
|
|
690
|
+
* Subscribes to {@link hydrated} changes; returns an unsubscribe function.
|
|
691
|
+
* Fires at most once per client — hydration settles one way and stays
|
|
692
|
+
* settled. An arrow property, so it plugs straight into React:
|
|
693
|
+
* `useSyncExternalStore(client.subscribeHydrated, () => client.hydrated)`.
|
|
694
|
+
*/
|
|
695
|
+
subscribeHydrated = (listener) => {
|
|
696
|
+
this.#hydratedListeners.add(listener);
|
|
697
|
+
return () => {
|
|
698
|
+
this.#hydratedListeners.delete(listener);
|
|
699
|
+
};
|
|
700
|
+
};
|
|
701
|
+
/**
|
|
702
|
+
* Registers a table's hooks. Returns an unregister function. Registering
|
|
703
|
+
* after the first sync completes forces a full resync, since the engine
|
|
704
|
+
* keeps no mirror of already-applied data — register all collections
|
|
705
|
+
* before meaningful traffic to avoid the extra round-trip.
|
|
706
|
+
*/
|
|
707
|
+
registerTable(tbl, hooks) {
|
|
708
|
+
if (this.#tables.has(tbl)) throw new Error(`table "${tbl}" is already registered`);
|
|
709
|
+
this.#tables.set(tbl, hooks);
|
|
710
|
+
if (this.#syncedThisConnection) this.#requestFullResync();
|
|
711
|
+
if (!this.#started && this.#startNudgeTimer === null) this.#startNudgeTimer = setTimeout(() => {
|
|
712
|
+
this.#startNudgeTimer = null;
|
|
713
|
+
if (!this.#started && !this.#stopped) this.#log("warn", "[cf-sync] tables are registered but start() was never called — nothing will sync");
|
|
714
|
+
}, 5e3);
|
|
715
|
+
return () => {
|
|
716
|
+
if (this.#tables.get(tbl) === hooks) this.#tables.delete(tbl);
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
/**
|
|
720
|
+
* Attaches a table's collection applier so `mutate` can run the shared
|
|
721
|
+
* mutator locally for an instant optimistic effect (adapter-facing, like
|
|
722
|
+
* `registerTable`; `workspaceCollectionOptions` and `createCollections`
|
|
723
|
+
* call it for you). Re-registering a table replaces its applier. The
|
|
724
|
+
* runner supplies the atomic-transaction primitive; every adapter passes
|
|
725
|
+
* an equivalent one, so the last registration wins.
|
|
726
|
+
*/
|
|
727
|
+
registerApplier(tbl, applier, runner) {
|
|
728
|
+
this.#appliers.set(tbl, applier);
|
|
729
|
+
this.#intentRunner = runner;
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Sends one binary-lane frame — the client half of the extension seam,
|
|
733
|
+
* used by add-ons like `createYjsFields`. Fire-and-forget
|
|
734
|
+
* like every frame on this socket: a broken socket surfaces through the
|
|
735
|
+
* close event, and binary-lane consumers re-sync on the next ready
|
|
736
|
+
* transition (`subscribeStatus` reaching 'synced'), so nothing is lost.
|
|
737
|
+
* The server only accepts binary frames once the connection is ready.
|
|
738
|
+
*/
|
|
739
|
+
sendBinary(bytes) {
|
|
740
|
+
try {
|
|
741
|
+
this.#socket?.send(bytes);
|
|
742
|
+
} catch {}
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* Subscribes to inbound binary-lane frames; returns an unsubscribe
|
|
746
|
+
* function. Frames are delivered as-received — framing and dispatch belong
|
|
747
|
+
* to the add-on (see `@cf-sync/protocol`'s field-frame helpers).
|
|
748
|
+
*/
|
|
749
|
+
onBinary(listener) {
|
|
750
|
+
this.#binaryListeners.add(listener);
|
|
751
|
+
return () => {
|
|
752
|
+
this.#binaryListeners.delete(listener);
|
|
753
|
+
};
|
|
754
|
+
}
|
|
755
|
+
/** Begins hydration and connection. Called from the constructor unless `autoStart: false`; idempotent. */
|
|
756
|
+
start() {
|
|
757
|
+
if (this.#destroyed) throw new Error("SyncClient: destroyed — construct a new SyncClient to reconnect this workspace");
|
|
758
|
+
if (this.#started) return;
|
|
759
|
+
this.#started = true;
|
|
760
|
+
this.#clearStartNudge();
|
|
761
|
+
this.#listenForWake(true);
|
|
762
|
+
this.#setStatus("connecting");
|
|
763
|
+
const store = this.#store;
|
|
764
|
+
if (store) {
|
|
765
|
+
this.#hydrating = true;
|
|
766
|
+
this.#hydrate(store).catch(() => false).then((restored) => {
|
|
767
|
+
this.#hydrating = false;
|
|
768
|
+
if (this.#outbox.length > 0) this.#persistOutbox();
|
|
769
|
+
this.#settleHydrated(restored);
|
|
770
|
+
if (!this.#stopped) this.#connect();
|
|
771
|
+
});
|
|
772
|
+
} else {
|
|
773
|
+
this.#settleHydrated(false);
|
|
774
|
+
this.#connect();
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* Closes the hydration latch exactly once, at whichever of the three ends
|
|
779
|
+
* comes first: hydration settling, a storeless start, or teardown.
|
|
780
|
+
*/
|
|
781
|
+
#settleHydrated(restored) {
|
|
782
|
+
const settle = this.#settleHydration;
|
|
783
|
+
if (!settle) return;
|
|
784
|
+
this.#settleHydration = null;
|
|
785
|
+
this.#hydrated = restored;
|
|
786
|
+
settle(restored);
|
|
787
|
+
if (restored) for (const listener of [...this.#hydratedListeners]) listener(true);
|
|
788
|
+
}
|
|
789
|
+
/**
|
|
790
|
+
* The synchronous half of {@link destroy}: closes the socket, cancels
|
|
791
|
+
* timers, and rejects every unconfirmed `mutate` promise with `Stopped`.
|
|
792
|
+
* The durable outbox is NOT discarded — queued mutations survive and
|
|
793
|
+
* replay when a future client for this workspace hydrates the same store.
|
|
794
|
+
*/
|
|
795
|
+
#shutdown() {
|
|
796
|
+
this.#stopped = true;
|
|
797
|
+
this.#clearStartNudge();
|
|
798
|
+
this.#listenForWake(false);
|
|
799
|
+
if (this.#reconnectTimer) clearTimeout(this.#reconnectTimer);
|
|
800
|
+
if (this.#retryPushTimer) clearTimeout(this.#retryPushTimer);
|
|
801
|
+
this.#stopHeartbeat();
|
|
802
|
+
this.#presenceDisconnected();
|
|
803
|
+
const socket = this.#socket;
|
|
804
|
+
this.#socket = null;
|
|
805
|
+
try {
|
|
806
|
+
socket?.close(1e3, "client stopped");
|
|
807
|
+
} catch {}
|
|
808
|
+
for (const entry of [...this.#outbox]) this.#settleEntry(entry, new MutationError("Stopped", "sync client stopped", {
|
|
809
|
+
name: entry.name,
|
|
810
|
+
args: entry.args
|
|
811
|
+
}));
|
|
812
|
+
this.#outbox = [];
|
|
813
|
+
this.#settleHydrated(false);
|
|
814
|
+
this.#setStatus("idle");
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* Reconnect the moment the environment says connectivity is back: without
|
|
818
|
+
* this, a capped-backoff timer can sit out ~30s on a fine network after a
|
|
819
|
+
* laptop reopens. Listens to `online` and `visibilitychange` where a
|
|
820
|
+
* browser environment provides them; a no-op elsewhere.
|
|
821
|
+
*/
|
|
822
|
+
#wake = () => {
|
|
823
|
+
if (this.#stopped || this.#status !== "reconnecting") return;
|
|
824
|
+
if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
|
|
825
|
+
if (typeof navigator !== "undefined" && "onLine" in navigator && navigator.onLine === false) return;
|
|
826
|
+
if (this.#reconnectTimer) clearTimeout(this.#reconnectTimer);
|
|
827
|
+
this.#reconnectTimer = null;
|
|
828
|
+
this.#connect();
|
|
829
|
+
};
|
|
830
|
+
#listenForWake(on) {
|
|
831
|
+
const g = globalThis;
|
|
832
|
+
if (on) {
|
|
833
|
+
g.addEventListener?.("online", this.#wake);
|
|
834
|
+
if (typeof document !== "undefined") document.addEventListener?.("visibilitychange", this.#wake);
|
|
835
|
+
} else {
|
|
836
|
+
g.removeEventListener?.("online", this.#wake);
|
|
837
|
+
if (typeof document !== "undefined") document.removeEventListener?.("visibilitychange", this.#wake);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Registers a teardown callback run (and awaited) by {@link destroy} —
|
|
842
|
+
* how resources created against this client tie their lifetime to it
|
|
843
|
+
* (`createCollections` registers each collection's cleanup here). Returns
|
|
844
|
+
* an unregister function. Apps rarely call this directly.
|
|
845
|
+
*/
|
|
846
|
+
onDestroy(callback) {
|
|
847
|
+
this.#teardown.add(callback);
|
|
848
|
+
return () => {
|
|
849
|
+
this.#teardown.delete(callback);
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
/**
|
|
853
|
+
* The one teardown, idempotent. Synchronously: closes the socket, cancels
|
|
854
|
+
* timers, and rejects every unconfirmed `mutate` promise with `Stopped`
|
|
855
|
+
* (all before the first await, so fire-and-forget `void client.destroy()`
|
|
856
|
+
* is safe in unload paths). Then: runs every {@link onDestroy} callback
|
|
857
|
+
* (collections from `createCollections` clean up here) and closes the
|
|
858
|
+
* store's connection when it has a `close`. The instance is inert
|
|
859
|
+
* afterwards — `start()` throws, `mutate` rejects with `Stopped` — and
|
|
860
|
+
* constructing a fresh SyncClient (plus fresh collections) for the same or
|
|
861
|
+
* another workspace is the supported way to (re)connect: the pattern for
|
|
862
|
+
* workspace-per-project apps switching projects. State is not lost: the
|
|
863
|
+
* durable store keeps its rows and outbox for the next client, and this
|
|
864
|
+
* tab's managed clientId is reused, so mutations queued offline still
|
|
865
|
+
* replay exactly once.
|
|
866
|
+
*/
|
|
867
|
+
async destroy() {
|
|
868
|
+
if (this.#destroyed) return;
|
|
869
|
+
this.#destroyed = true;
|
|
870
|
+
this.#shutdown();
|
|
871
|
+
for (const callback of [...this.#teardown]) try {
|
|
872
|
+
await callback();
|
|
873
|
+
} catch (err) {
|
|
874
|
+
this.#log("warn", "[cf-sync] a destroy callback failed", err);
|
|
875
|
+
}
|
|
876
|
+
this.#teardown.clear();
|
|
877
|
+
try {
|
|
878
|
+
await this.#store?.close?.();
|
|
879
|
+
} catch (err) {
|
|
880
|
+
this.#log("warn", "[cf-sync] failed to close the sync store", err);
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Restores persisted state before the first connection: outbox entries
|
|
885
|
+
* re-queue under their original ids (LMID makes replay exactly-once), and
|
|
886
|
+
* cached rows feed registered tables so collections are ready with data
|
|
887
|
+
* before any network I/O. Restored entries then replay locally — their
|
|
888
|
+
* mutators re-run against the hydrated base and their writes land as
|
|
889
|
+
* optimistic overlays (ARCHITECTURE.md#optimistic-intents), so the reloaded UI matches the
|
|
890
|
+
* pre-reload optimistic view. Restored mutations have no awaiting caller,
|
|
891
|
+
* so they carry no confirm timeout — they stay queued until the server
|
|
892
|
+
* settles them.
|
|
893
|
+
*
|
|
894
|
+
* Resolves true when a cached snapshot was restored and collections were
|
|
895
|
+
* marked ready — false on every path that leaves nothing to paint (no
|
|
896
|
+
* cache, a discarded one, a load failure, teardown mid-hydration). That
|
|
897
|
+
* answer is what `hydrated` reports (ARCHITECTURE.md#offline-first-render).
|
|
898
|
+
*/
|
|
899
|
+
async #hydrate(store) {
|
|
900
|
+
let state = null;
|
|
901
|
+
try {
|
|
902
|
+
state = await store.load();
|
|
903
|
+
} catch (err) {
|
|
904
|
+
this.#log("warn", "[cf-sync] failed to load persisted state; bootstrapping fresh", err);
|
|
905
|
+
return false;
|
|
906
|
+
}
|
|
907
|
+
if (!state || this.#stopped) return false;
|
|
908
|
+
if (state.schemaVersion !== null && state.schemaVersion !== this.#opts.app.version) {
|
|
909
|
+
try {
|
|
910
|
+
await store.reset();
|
|
911
|
+
} catch (err) {
|
|
912
|
+
this.#log("warn", "[cf-sync] failed to reset persisted state", err);
|
|
913
|
+
}
|
|
914
|
+
return false;
|
|
915
|
+
}
|
|
916
|
+
this.#cursor = state.cursor;
|
|
917
|
+
this.#confirmedLmid = state.confirmedLmid;
|
|
918
|
+
const noop = () => {};
|
|
919
|
+
const restored = state.outbox.map((e) => ({
|
|
920
|
+
id: e.id,
|
|
921
|
+
name: e.name,
|
|
922
|
+
args: e.args,
|
|
923
|
+
resolve: noop,
|
|
924
|
+
reject: (err) => this.#notifyRejected(err, e.name, e.args),
|
|
925
|
+
timer: null,
|
|
926
|
+
settled: false
|
|
927
|
+
}));
|
|
928
|
+
this.#outbox = [...restored, ...this.#outbox];
|
|
929
|
+
if (state.cursor !== null) {
|
|
930
|
+
const byTable = /* @__PURE__ */ new Map();
|
|
931
|
+
for (const row of state.rows) {
|
|
932
|
+
let rows = byTable.get(row.tbl);
|
|
933
|
+
if (!rows) byTable.set(row.tbl, rows = []);
|
|
934
|
+
rows.push(row);
|
|
935
|
+
}
|
|
936
|
+
for (const [tbl, hooks] of this.#tables) {
|
|
937
|
+
hooks.begin();
|
|
938
|
+
for (const row of byTable.get(tbl) ?? []) hooks.write({
|
|
939
|
+
type: "put",
|
|
940
|
+
id: row.id,
|
|
941
|
+
value: row.value
|
|
942
|
+
});
|
|
943
|
+
hooks.commit();
|
|
944
|
+
byTable.delete(tbl);
|
|
945
|
+
}
|
|
946
|
+
for (const tbl of byTable.keys()) this.#warnUnregistered(tbl);
|
|
947
|
+
}
|
|
948
|
+
for (const entry of restored) this.#replayEntry(entry);
|
|
949
|
+
if (state.cursor === null) return false;
|
|
950
|
+
for (const hooks of this.#tables.values()) hooks.markReady();
|
|
951
|
+
return true;
|
|
952
|
+
}
|
|
953
|
+
/**
|
|
954
|
+
* Re-lays one restored outbox entry's optimistic overlay at hydration
|
|
955
|
+
* (ARCHITECTURE.md#optimistic-intents): re-runs the mutator's `apply` against the hydrated
|
|
956
|
+
* collections and flushes the writes through the intent runner, with the
|
|
957
|
+
* persist step tied to the entry's existing settlement — confirm swaps
|
|
958
|
+
* the overlay for the authoritative patch, rejection rolls it back (and
|
|
959
|
+
* still reaches `onMutationRejected` through the entry's reject). The
|
|
960
|
+
* error policy inverts the live fail-fast: degrade, never drop. A local
|
|
961
|
+
* throw here proves nothing about the server's verdict, so any failure
|
|
962
|
+
* skips the overlay and leaves the entry queued.
|
|
963
|
+
*/
|
|
964
|
+
#replayEntry(entry) {
|
|
965
|
+
const runner = this.#intentRunner;
|
|
966
|
+
if (!runner || this.#appliers.size === 0) return;
|
|
967
|
+
const def = this.#opts.app.mutators[entry.name];
|
|
968
|
+
if (!def) return;
|
|
969
|
+
let applyArgs = entry.args;
|
|
970
|
+
if (def.args) {
|
|
971
|
+
const result = def.args["~standard"].validate(entry.args);
|
|
972
|
+
if (result instanceof Promise) {
|
|
973
|
+
result.catch(() => {});
|
|
974
|
+
return;
|
|
975
|
+
}
|
|
976
|
+
if (result.issues) return;
|
|
977
|
+
applyArgs = result.value;
|
|
978
|
+
}
|
|
979
|
+
const writes = new LocalWriteSet(this.schema, this.#appliers);
|
|
980
|
+
try {
|
|
981
|
+
def.apply(writes.tx, applyArgs, {
|
|
982
|
+
clientId: this.#clientId,
|
|
983
|
+
auth: this.#auth,
|
|
984
|
+
authoritative: false
|
|
985
|
+
});
|
|
986
|
+
} catch (err) {
|
|
987
|
+
if (err instanceof MissingApplierError) this.#warnNoApplier(entry.name, err.tbl);
|
|
988
|
+
else this.#log("warn", `[cf-sync] startup replay of "${entry.name}" threw locally — it stays queued without an optimistic overlay`, err);
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
991
|
+
if (writes.isEmpty()) return;
|
|
992
|
+
const notify = entry.reject;
|
|
993
|
+
const settled = new Promise((resolve, reject) => {
|
|
994
|
+
entry.resolve = resolve;
|
|
995
|
+
entry.reject = (err) => {
|
|
996
|
+
reject(err);
|
|
997
|
+
notify(err);
|
|
998
|
+
};
|
|
999
|
+
});
|
|
1000
|
+
try {
|
|
1001
|
+
runner(entry.name, () => this.#flushLocalWrites(writes), () => settled).catch(() => {});
|
|
1002
|
+
} catch (err) {
|
|
1003
|
+
entry.resolve = () => {};
|
|
1004
|
+
entry.reject = notify;
|
|
1005
|
+
this.#log("warn", `[cf-sync] failed to lay the replay overlay for "${entry.name}"`, err);
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
/**
|
|
1009
|
+
* Routes a mutation promise's rejection into `onMutationRejected` (and
|
|
1010
|
+
* thereby marks it handled, so fire-and-forget call sites don't trip
|
|
1011
|
+
* unhandled-rejection reporting). Returns the original promise: awaiting
|
|
1012
|
+
* callers observe the identical rejection.
|
|
1013
|
+
*/
|
|
1014
|
+
#guardMutation(name, args, promise) {
|
|
1015
|
+
if (this.#opts.onMutationRejected || this.#rejectionListeners.size > 0) promise.catch((err) => this.#notifyRejected(err, name, args));
|
|
1016
|
+
return promise;
|
|
1017
|
+
}
|
|
1018
|
+
/**
|
|
1019
|
+
* Subscribes to permanent mutation rejections — the attach-later
|
|
1020
|
+
* counterpart to the `onMutationRejected` constructor option, for layers
|
|
1021
|
+
* that mount after the client exists (a toast system, an error boundary).
|
|
1022
|
+
* Same payload and same "considered handled" semantics: a mutation issued
|
|
1023
|
+
* while at least one listener (or the constructor option) is attached has
|
|
1024
|
+
* its rejection routed here instead of tripping unhandled-rejection
|
|
1025
|
+
* reporting. Both surfaces fire when both are set. Returns an unsubscribe
|
|
1026
|
+
* function.
|
|
1027
|
+
*/
|
|
1028
|
+
onMutationRejected(listener) {
|
|
1029
|
+
this.#rejectionListeners.add(listener);
|
|
1030
|
+
return () => {
|
|
1031
|
+
this.#rejectionListeners.delete(listener);
|
|
1032
|
+
};
|
|
1033
|
+
}
|
|
1034
|
+
#notifyRejected(err, name, args) {
|
|
1035
|
+
if (!(err instanceof MutationError)) return;
|
|
1036
|
+
const mutation = {
|
|
1037
|
+
name,
|
|
1038
|
+
args
|
|
1039
|
+
};
|
|
1040
|
+
const option = this.#opts.onMutationRejected;
|
|
1041
|
+
for (const hook of option ? [option, ...this.#rejectionListeners] : [...this.#rejectionListeners]) try {
|
|
1042
|
+
hook(err, mutation);
|
|
1043
|
+
} catch (hookErr) {
|
|
1044
|
+
this.#log("error", "[cf-sync] onMutationRejected threw", hookErr);
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
/** The runtime behind both forms of `mutate` (see the property's docs). */
|
|
1048
|
+
#mutateByName(name, args) {
|
|
1049
|
+
if (this.#status === "fatal") return Promise.reject(new MutationError("Fatal", "sync client is in a fatal state", {
|
|
1050
|
+
name,
|
|
1051
|
+
args
|
|
1052
|
+
}));
|
|
1053
|
+
const def = this.#opts.app.mutators[name];
|
|
1054
|
+
if (!def) return Promise.reject(new MutationError("UnknownMutator", `no mutator named "${name}" in the app passed to SyncClient`, {
|
|
1055
|
+
name,
|
|
1056
|
+
args
|
|
1057
|
+
}));
|
|
1058
|
+
let applyArgs = args;
|
|
1059
|
+
if (def.args) {
|
|
1060
|
+
const result = def.args["~standard"].validate(args);
|
|
1061
|
+
if (result instanceof Promise) {
|
|
1062
|
+
result.catch(() => {});
|
|
1063
|
+
return this.#enqueue(name, args);
|
|
1064
|
+
}
|
|
1065
|
+
if (result.issues) return Promise.reject(new MutationError("InvalidArgs", `invalid args for "${name}": ${formatIssues(result.issues)}`, {
|
|
1066
|
+
name,
|
|
1067
|
+
args
|
|
1068
|
+
}));
|
|
1069
|
+
applyArgs = result.value;
|
|
1070
|
+
}
|
|
1071
|
+
const runner = this.#intentRunner;
|
|
1072
|
+
if (!runner || this.#appliers.size === 0) return this.#enqueue(name, args);
|
|
1073
|
+
const writes = new LocalWriteSet(this.schema, this.#appliers);
|
|
1074
|
+
try {
|
|
1075
|
+
def.apply(writes.tx, applyArgs, {
|
|
1076
|
+
clientId: this.#clientId,
|
|
1077
|
+
auth: this.#auth,
|
|
1078
|
+
authoritative: false
|
|
1079
|
+
});
|
|
1080
|
+
} catch (err) {
|
|
1081
|
+
if (err instanceof MissingApplierError) {
|
|
1082
|
+
this.#warnNoApplier(name, err.tbl);
|
|
1083
|
+
return this.#enqueue(name, args);
|
|
1084
|
+
}
|
|
1085
|
+
if (err instanceof AppError$1) return Promise.reject(new MutationError(err.code, err.message, {
|
|
1086
|
+
name,
|
|
1087
|
+
args
|
|
1088
|
+
}));
|
|
1089
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
1090
|
+
return Promise.reject(new MutationError("LocalApplyFailed", `mutator "${name}" threw during local apply: ${detail}`, {
|
|
1091
|
+
name,
|
|
1092
|
+
args
|
|
1093
|
+
}));
|
|
1094
|
+
}
|
|
1095
|
+
if (writes.isEmpty()) return this.#enqueue(name, args);
|
|
1096
|
+
return runner(name, () => this.#flushLocalWrites(writes), () => this.#enqueue(name, args));
|
|
1097
|
+
}
|
|
1098
|
+
/**
|
|
1099
|
+
* The adapter's raw path (see `RAW_MUTATE`): validate and enqueue, no
|
|
1100
|
+
* speculative local run — collection mutation handlers already *are* the
|
|
1101
|
+
* optimistic effect.
|
|
1102
|
+
*/
|
|
1103
|
+
[RAW_MUTATE](name, args) {
|
|
1104
|
+
return this.#guardMutation(name, args, this.#rawMutate(name, args));
|
|
1105
|
+
}
|
|
1106
|
+
#rawMutate(name, args) {
|
|
1107
|
+
if (this.#status === "fatal") return Promise.reject(new MutationError("Fatal", "sync client is in a fatal state", {
|
|
1108
|
+
name,
|
|
1109
|
+
args
|
|
1110
|
+
}));
|
|
1111
|
+
const def = this.#opts.app.mutators[name];
|
|
1112
|
+
if (!def) return Promise.reject(new MutationError("UnknownMutator", `no mutator named "${name}" in the app passed to SyncClient`, {
|
|
1113
|
+
name,
|
|
1114
|
+
args
|
|
1115
|
+
}));
|
|
1116
|
+
if (def.args) {
|
|
1117
|
+
const result = def.args["~standard"].validate(args);
|
|
1118
|
+
if (result instanceof Promise) result.catch(() => {});
|
|
1119
|
+
else if (result.issues) return Promise.reject(new MutationError("InvalidArgs", `invalid args for "${name}": ${formatIssues(result.issues)}`, {
|
|
1120
|
+
name,
|
|
1121
|
+
args
|
|
1122
|
+
}));
|
|
1123
|
+
}
|
|
1124
|
+
return this.#enqueue(name, args);
|
|
1125
|
+
}
|
|
1126
|
+
/** Translates an intent's net writes to collection ops (inside the runner's atomic scope). */
|
|
1127
|
+
#flushLocalWrites(writes) {
|
|
1128
|
+
for (const { tbl, id, data } of writes.puts()) {
|
|
1129
|
+
const applier = this.#appliers.get(tbl);
|
|
1130
|
+
if (!applier) continue;
|
|
1131
|
+
if (applier.has(id)) applier.update(id, data);
|
|
1132
|
+
else applier.insert(data);
|
|
1133
|
+
}
|
|
1134
|
+
for (const { tbl, id } of writes.dels()) {
|
|
1135
|
+
const applier = this.#appliers.get(tbl);
|
|
1136
|
+
if (applier?.has(id)) applier.delete(id);
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
#warnNoApplier(mutator, tbl) {
|
|
1140
|
+
if (this.#warnedNoApplier.has(tbl)) return;
|
|
1141
|
+
this.#warnedNoApplier.add(tbl);
|
|
1142
|
+
this.#log("warn", `[cf-sync] mutator "${mutator}" touched table "${tbl}" which has no attached collection — the mutation still applies on the server, but without a local optimistic effect. Create the table's collection (createCollections covers every schema table) to restore it.`);
|
|
1143
|
+
}
|
|
1144
|
+
/** Queues a validated mutation; resolves/rejects on server confirm (the LMID contract). */
|
|
1145
|
+
#enqueue(name, args) {
|
|
1146
|
+
if (this.#status === "fatal") return Promise.reject(new MutationError("Fatal", "sync client is in a fatal state", {
|
|
1147
|
+
name,
|
|
1148
|
+
args
|
|
1149
|
+
}));
|
|
1150
|
+
if (this.#stopped) return Promise.reject(new MutationError("Stopped", "sync client stopped", {
|
|
1151
|
+
name,
|
|
1152
|
+
args
|
|
1153
|
+
}));
|
|
1154
|
+
return new Promise((resolve, reject) => {
|
|
1155
|
+
const entry = {
|
|
1156
|
+
id: null,
|
|
1157
|
+
name,
|
|
1158
|
+
args,
|
|
1159
|
+
resolve,
|
|
1160
|
+
reject,
|
|
1161
|
+
timer: null,
|
|
1162
|
+
settled: false
|
|
1163
|
+
};
|
|
1164
|
+
if (this.#store === void 0) {
|
|
1165
|
+
const timeoutMs = this.#opts.confirmTimeoutMs ?? 3e4;
|
|
1166
|
+
entry.timer = setTimeout(() => {
|
|
1167
|
+
this.#settleEntry(entry, new MutationError("Timeout", `mutation "${name}" unconfirmed after ${timeoutMs}ms`, {
|
|
1168
|
+
name,
|
|
1169
|
+
args
|
|
1170
|
+
}));
|
|
1171
|
+
}, timeoutMs);
|
|
1172
|
+
}
|
|
1173
|
+
this.#outbox.push(entry);
|
|
1174
|
+
if (this.#syncedThisConnection) {
|
|
1175
|
+
entry.id = this.#nextMutationId();
|
|
1176
|
+
this.#schedulePush();
|
|
1177
|
+
}
|
|
1178
|
+
this.#persistOutbox();
|
|
1179
|
+
});
|
|
1180
|
+
}
|
|
1181
|
+
#connect() {
|
|
1182
|
+
if (this.#stopped) return;
|
|
1183
|
+
const epoch = ++this.#connectEpoch;
|
|
1184
|
+
const token = this.#opts.authToken;
|
|
1185
|
+
if (token === void 0) {
|
|
1186
|
+
this.#openSocket(this.#url);
|
|
1187
|
+
return;
|
|
1188
|
+
}
|
|
1189
|
+
if (typeof token === "string") {
|
|
1190
|
+
this.#openSocket(withToken(this.#url, token));
|
|
1191
|
+
return;
|
|
1192
|
+
}
|
|
1193
|
+
Promise.resolve().then(token).then((value) => {
|
|
1194
|
+
if (this.#stopped || epoch !== this.#connectEpoch) return;
|
|
1195
|
+
this.#openSocket(withToken(this.#url, value));
|
|
1196
|
+
}, (err) => {
|
|
1197
|
+
if (this.#stopped || epoch !== this.#connectEpoch) return;
|
|
1198
|
+
this.#log("warn", "[cf-sync] authToken provider failed; retrying", err);
|
|
1199
|
+
this.#socket = null;
|
|
1200
|
+
this.#scheduleReconnect();
|
|
1201
|
+
});
|
|
1202
|
+
}
|
|
1203
|
+
#openSocket(url) {
|
|
1204
|
+
const createSocket = this.#opts.createSocket ?? ((socketUrl) => {
|
|
1205
|
+
const ws = new WebSocket(socketUrl);
|
|
1206
|
+
ws.binaryType = "arraybuffer";
|
|
1207
|
+
return ws;
|
|
1208
|
+
});
|
|
1209
|
+
let socket;
|
|
1210
|
+
try {
|
|
1211
|
+
socket = createSocket(url);
|
|
1212
|
+
} catch (err) {
|
|
1213
|
+
this.#log("warn", "[cf-sync] failed to create socket; retrying", err);
|
|
1214
|
+
this.#socket = null;
|
|
1215
|
+
this.#scheduleReconnect();
|
|
1216
|
+
return;
|
|
1217
|
+
}
|
|
1218
|
+
this.#socket = socket;
|
|
1219
|
+
this.#syncedThisConnection = false;
|
|
1220
|
+
socket.addEventListener("open", () => {
|
|
1221
|
+
if (socket !== this.#socket) return;
|
|
1222
|
+
this.#lastFrameAt = Date.now();
|
|
1223
|
+
this.#startHeartbeat();
|
|
1224
|
+
this.#setStatus("syncing");
|
|
1225
|
+
this.#sendHello();
|
|
1226
|
+
});
|
|
1227
|
+
socket.addEventListener("message", (event) => {
|
|
1228
|
+
if (socket !== this.#socket) return;
|
|
1229
|
+
this.#lastFrameAt = Date.now();
|
|
1230
|
+
if (typeof event.data === "string") this.#onMessage(event.data);
|
|
1231
|
+
else this.#onBinaryFrame(event.data);
|
|
1232
|
+
});
|
|
1233
|
+
socket.addEventListener("close", (event) => {
|
|
1234
|
+
if (socket !== this.#socket) return;
|
|
1235
|
+
this.#onDisconnect(event?.code, event?.reason);
|
|
1236
|
+
});
|
|
1237
|
+
socket.addEventListener("error", () => {});
|
|
1238
|
+
}
|
|
1239
|
+
#onDisconnect(code, reason) {
|
|
1240
|
+
this.#socket = null;
|
|
1241
|
+
this.#poke = null;
|
|
1242
|
+
this.#awaitingCatchUp = false;
|
|
1243
|
+
this.#stopHeartbeat();
|
|
1244
|
+
this.#presenceDisconnected();
|
|
1245
|
+
if (code !== void 0 && isPermanentCloseCode$1(code)) {
|
|
1246
|
+
this.#fatal(new SyncFatalError(code, reason || "connection rejected"));
|
|
1247
|
+
return;
|
|
1248
|
+
}
|
|
1249
|
+
if (code === CLOSE_REFRESH$1) {
|
|
1250
|
+
this.#refreshStreak++;
|
|
1251
|
+
if (this.#refreshStreak === 1) {
|
|
1252
|
+
this.#setStatus("reconnecting");
|
|
1253
|
+
this.#connect();
|
|
1254
|
+
return;
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
this.#scheduleReconnect();
|
|
1258
|
+
}
|
|
1259
|
+
#scheduleReconnect() {
|
|
1260
|
+
if (this.#stopped || this.#status === "fatal") return;
|
|
1261
|
+
this.#setStatus("reconnecting");
|
|
1262
|
+
const cap = this.#opts.maxBackoffMs ?? 3e4;
|
|
1263
|
+
const delay = Math.min(cap, 500 * 2 ** this.#attempt) * (.5 + Math.random() * .5);
|
|
1264
|
+
this.#attempt++;
|
|
1265
|
+
this.#reconnectTimer = setTimeout(() => this.#connect(), delay);
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* Idle edge connections die unpredictably (NAT/edge timeouts, observed
|
|
1269
|
+
* live anywhere from ~75s to >130s), and a half-open socket never emits a
|
|
1270
|
+
* close event — send() just vanishes. Pings keep the path warm (the server
|
|
1271
|
+
* runtime answers them without waking the DO), and a missed idle deadline
|
|
1272
|
+
* is the only reliable dead-socket signal: declare it dead locally and
|
|
1273
|
+
* run the normal reconnect + cursor catch-up.
|
|
1274
|
+
*/
|
|
1275
|
+
#startHeartbeat() {
|
|
1276
|
+
this.#stopHeartbeat();
|
|
1277
|
+
const interval = this.#opts.pingIntervalMs ?? 25e3;
|
|
1278
|
+
if (interval <= 0) return;
|
|
1279
|
+
const deadline = this.#opts.idleTimeoutMs ?? interval * 2 + 5e3;
|
|
1280
|
+
this.#heartbeatTimer = setInterval(() => {
|
|
1281
|
+
const socket = this.#socket;
|
|
1282
|
+
if (!socket) return;
|
|
1283
|
+
if (Date.now() - this.#lastFrameAt > deadline) {
|
|
1284
|
+
this.#socket = null;
|
|
1285
|
+
try {
|
|
1286
|
+
socket.close(4408, "heartbeat timeout");
|
|
1287
|
+
} catch {}
|
|
1288
|
+
this.#poke = null;
|
|
1289
|
+
this.#awaitingCatchUp = false;
|
|
1290
|
+
this.#stopHeartbeat();
|
|
1291
|
+
this.#presenceDisconnected();
|
|
1292
|
+
this.#scheduleReconnect();
|
|
1293
|
+
return;
|
|
1294
|
+
}
|
|
1295
|
+
try {
|
|
1296
|
+
socket.send(KEEPALIVE_PING);
|
|
1297
|
+
} catch {}
|
|
1298
|
+
}, interval);
|
|
1299
|
+
}
|
|
1300
|
+
#stopHeartbeat() {
|
|
1301
|
+
if (this.#heartbeatTimer) {
|
|
1302
|
+
clearInterval(this.#heartbeatTimer);
|
|
1303
|
+
this.#heartbeatTimer = null;
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
#clearStartNudge() {
|
|
1307
|
+
if (this.#startNudgeTimer) {
|
|
1308
|
+
clearTimeout(this.#startNudgeTimer);
|
|
1309
|
+
this.#startNudgeTimer = null;
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
#sendHello() {
|
|
1313
|
+
this.#awaitingCatchUp = true;
|
|
1314
|
+
this.#send({
|
|
1315
|
+
type: "hello",
|
|
1316
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
1317
|
+
schemaVersion: this.#opts.app.version,
|
|
1318
|
+
cursor: this.#cursor
|
|
1319
|
+
});
|
|
1320
|
+
}
|
|
1321
|
+
#requestResync() {
|
|
1322
|
+
if (this.#awaitingCatchUp || !this.#socket) return;
|
|
1323
|
+
this.#sendHello();
|
|
1324
|
+
}
|
|
1325
|
+
#requestFullResync() {
|
|
1326
|
+
this.#cursor = null;
|
|
1327
|
+
this.#awaitingCatchUp = false;
|
|
1328
|
+
if (this.#socket && this.#status !== "connecting") this.#sendHello();
|
|
1329
|
+
}
|
|
1330
|
+
/** Fans a binary-lane frame out to `onBinary` subscribers (ARCHITECTURE.md#yjs-fields). */
|
|
1331
|
+
#onBinaryFrame(data) {
|
|
1332
|
+
let bytes;
|
|
1333
|
+
if (data instanceof ArrayBuffer) bytes = new Uint8Array(data);
|
|
1334
|
+
else if (ArrayBuffer.isView(data)) bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
1335
|
+
else {
|
|
1336
|
+
if (!this.#warnedBinaryType) {
|
|
1337
|
+
this.#warnedBinaryType = true;
|
|
1338
|
+
this.#log("warn", "[cf-sync] dropped a binary frame that was not an ArrayBuffer — set binaryType = 'arraybuffer' on the socket your createSocket returns");
|
|
1339
|
+
}
|
|
1340
|
+
return;
|
|
1341
|
+
}
|
|
1342
|
+
for (const listener of this.#binaryListeners) try {
|
|
1343
|
+
listener(bytes);
|
|
1344
|
+
} catch (err) {
|
|
1345
|
+
this.#log("error", "[cf-sync] onBinary listener threw", err);
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
#onMessage(raw) {
|
|
1349
|
+
let json;
|
|
1350
|
+
try {
|
|
1351
|
+
json = JSON.parse(raw);
|
|
1352
|
+
} catch {
|
|
1353
|
+
return;
|
|
1354
|
+
}
|
|
1355
|
+
const parsed = serverMsgSchema.safeParse(json);
|
|
1356
|
+
if (!parsed.success) return;
|
|
1357
|
+
const msg = parsed.data;
|
|
1358
|
+
switch (msg.type) {
|
|
1359
|
+
case "pokeStart":
|
|
1360
|
+
this.#poke = {
|
|
1361
|
+
pokeId: msg.pokeId,
|
|
1362
|
+
baseMismatch: !cursorEquals(msg.baseCursor, this.#cursor),
|
|
1363
|
+
patch: [],
|
|
1364
|
+
lastMutationIdChanges: {},
|
|
1365
|
+
mutationResults: []
|
|
1366
|
+
};
|
|
1367
|
+
break;
|
|
1368
|
+
case "pokePart": {
|
|
1369
|
+
const poke = this.#poke;
|
|
1370
|
+
if (!poke || poke.pokeId !== msg.pokeId) {
|
|
1371
|
+
this.#poke = null;
|
|
1372
|
+
this.#requestResync();
|
|
1373
|
+
break;
|
|
1374
|
+
}
|
|
1375
|
+
poke.patch.push(...msg.patch);
|
|
1376
|
+
Object.assign(poke.lastMutationIdChanges, msg.lastMutationIdChanges);
|
|
1377
|
+
if (msg.mutationResults) poke.mutationResults.push(...msg.mutationResults);
|
|
1378
|
+
if (msg.remaining !== void 0 && !poke.baseMismatch) this.#opts.onSyncProgress?.({
|
|
1379
|
+
receivedOps: poke.patch.length,
|
|
1380
|
+
remainingOps: msg.remaining
|
|
1381
|
+
});
|
|
1382
|
+
break;
|
|
1383
|
+
}
|
|
1384
|
+
case "pokeEnd": {
|
|
1385
|
+
const poke = this.#poke;
|
|
1386
|
+
this.#poke = null;
|
|
1387
|
+
if (!poke || poke.pokeId !== msg.pokeId) {
|
|
1388
|
+
this.#requestResync();
|
|
1389
|
+
break;
|
|
1390
|
+
}
|
|
1391
|
+
const isReset = poke.patch.some((op) => op.op === "clear");
|
|
1392
|
+
if (poke.baseMismatch && !isReset) {
|
|
1393
|
+
this.#requestResync();
|
|
1394
|
+
break;
|
|
1395
|
+
}
|
|
1396
|
+
this.#applyPoke(poke, msg);
|
|
1397
|
+
break;
|
|
1398
|
+
}
|
|
1399
|
+
case "presence":
|
|
1400
|
+
this.#applyPeerUpdate(msg.clientId, msg.principal, msg.state);
|
|
1401
|
+
break;
|
|
1402
|
+
case "presencePeers":
|
|
1403
|
+
this.#presenceLive = true;
|
|
1404
|
+
this.#presencePeers.clear();
|
|
1405
|
+
for (const peer of msg.peers) {
|
|
1406
|
+
if (peer.clientId === this.#clientId) continue;
|
|
1407
|
+
const entry = {
|
|
1408
|
+
clientId: peer.clientId,
|
|
1409
|
+
state: peer.state,
|
|
1410
|
+
receivedAt: Date.now()
|
|
1411
|
+
};
|
|
1412
|
+
if (peer.principal !== void 0) entry.principal = peer.principal;
|
|
1413
|
+
this.#presencePeers.set(peer.clientId, entry);
|
|
1414
|
+
}
|
|
1415
|
+
this.#notifyPresence();
|
|
1416
|
+
if (this.#presenceState !== void 0 && this.#presenceState !== null) this.#sendPresence();
|
|
1417
|
+
break;
|
|
1418
|
+
case "presencePoll":
|
|
1419
|
+
if (this.#presenceState !== void 0 && this.#presenceState !== null) this.#sendPresence();
|
|
1420
|
+
break;
|
|
1421
|
+
case "error":
|
|
1422
|
+
this.#onServerError(msg);
|
|
1423
|
+
break;
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
#applyPoke(poke, end) {
|
|
1427
|
+
const hasClear = poke.patch.some((op) => op.op === "clear");
|
|
1428
|
+
const byTable = /* @__PURE__ */ new Map();
|
|
1429
|
+
for (const op of poke.patch) {
|
|
1430
|
+
if (op.op === "clear") continue;
|
|
1431
|
+
let ops = byTable.get(op.tbl);
|
|
1432
|
+
if (!ops) byTable.set(op.tbl, ops = []);
|
|
1433
|
+
ops.push(op);
|
|
1434
|
+
}
|
|
1435
|
+
const applyOps = (hooks, ops) => {
|
|
1436
|
+
for (const op of ops) hooks.write(op.op === "put" ? {
|
|
1437
|
+
type: "put",
|
|
1438
|
+
id: op.id,
|
|
1439
|
+
value: op.value
|
|
1440
|
+
} : {
|
|
1441
|
+
type: "del",
|
|
1442
|
+
id: op.id
|
|
1443
|
+
});
|
|
1444
|
+
};
|
|
1445
|
+
if (hasClear) {
|
|
1446
|
+
for (const [tbl, hooks] of this.#tables) {
|
|
1447
|
+
hooks.begin();
|
|
1448
|
+
hooks.truncate();
|
|
1449
|
+
applyOps(hooks, byTable.get(tbl) ?? []);
|
|
1450
|
+
hooks.commit();
|
|
1451
|
+
byTable.delete(tbl);
|
|
1452
|
+
}
|
|
1453
|
+
for (const tbl of byTable.keys()) this.#warnUnregistered(tbl);
|
|
1454
|
+
} else for (const [tbl, ops] of byTable) {
|
|
1455
|
+
const hooks = this.#tables.get(tbl);
|
|
1456
|
+
if (!hooks) {
|
|
1457
|
+
this.#warnUnregistered(tbl);
|
|
1458
|
+
continue;
|
|
1459
|
+
}
|
|
1460
|
+
hooks.begin();
|
|
1461
|
+
applyOps(hooks, ops);
|
|
1462
|
+
hooks.commit();
|
|
1463
|
+
}
|
|
1464
|
+
const backendChanged = this.#cursor !== null && this.#cursor.backendId !== end.cursor.backendId;
|
|
1465
|
+
this.#cursor = end.cursor;
|
|
1466
|
+
this.#awaitingCatchUp = false;
|
|
1467
|
+
if (backendChanged) {
|
|
1468
|
+
this.#confirmedLmid = poke.lastMutationIdChanges[this.#clientId] ?? 0;
|
|
1469
|
+
this.#rebaseOutboxIds();
|
|
1470
|
+
} else {
|
|
1471
|
+
const confirmed = poke.lastMutationIdChanges[this.#clientId];
|
|
1472
|
+
if (confirmed !== void 0 && confirmed > this.#confirmedLmid) this.#confirmedLmid = confirmed;
|
|
1473
|
+
}
|
|
1474
|
+
this.#settleOutbox(poke.mutationResults);
|
|
1475
|
+
if (this.#needsRebase) {
|
|
1476
|
+
this.#needsRebase = false;
|
|
1477
|
+
this.#rebaseOutboxIds();
|
|
1478
|
+
}
|
|
1479
|
+
if (!this.#syncedThisConnection) {
|
|
1480
|
+
this.#syncedThisConnection = true;
|
|
1481
|
+
this.#attempt = 0;
|
|
1482
|
+
this.#refreshStreak = 0;
|
|
1483
|
+
this.#setStatus("synced");
|
|
1484
|
+
for (const hooks of this.#tables.values()) hooks.markReady();
|
|
1485
|
+
this.#assignPendingIds();
|
|
1486
|
+
}
|
|
1487
|
+
this.#schedulePush();
|
|
1488
|
+
const store = this.#store;
|
|
1489
|
+
if (store) {
|
|
1490
|
+
const ops = [];
|
|
1491
|
+
for (const op of poke.patch) if (op.op === "put") ops.push({
|
|
1492
|
+
op: "put",
|
|
1493
|
+
tbl: op.tbl,
|
|
1494
|
+
id: op.id,
|
|
1495
|
+
value: op.value
|
|
1496
|
+
});
|
|
1497
|
+
else if (op.op === "del") ops.push({
|
|
1498
|
+
op: "del",
|
|
1499
|
+
tbl: op.tbl,
|
|
1500
|
+
id: op.id
|
|
1501
|
+
});
|
|
1502
|
+
store.applyPoke({
|
|
1503
|
+
ops,
|
|
1504
|
+
clear: hasClear,
|
|
1505
|
+
cursor: end.cursor,
|
|
1506
|
+
schemaVersion: this.#opts.app.version,
|
|
1507
|
+
confirmedLmid: this.#confirmedLmid,
|
|
1508
|
+
outbox: this.#outboxSnapshot()
|
|
1509
|
+
}).catch((err) => this.#log("warn", "[cf-sync] failed to persist poke", err));
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
#onServerError(msg) {
|
|
1513
|
+
switch (msg.code) {
|
|
1514
|
+
case "VersionNotSupported":
|
|
1515
|
+
case "Unauthorized":
|
|
1516
|
+
this.#fatal(new SyncFatalError(msg.code, msg.message ?? msg.code));
|
|
1517
|
+
break;
|
|
1518
|
+
case "CursorInvalid":
|
|
1519
|
+
this.#requestFullResync();
|
|
1520
|
+
break;
|
|
1521
|
+
case "PushInvalid":
|
|
1522
|
+
this.#needsRebase = true;
|
|
1523
|
+
this.#requestResync();
|
|
1524
|
+
break;
|
|
1525
|
+
case "PresenceInvalid":
|
|
1526
|
+
this.#log("warn", `[cf-sync] server rejected presence state: ${msg.message ?? "PresenceInvalid"}`);
|
|
1527
|
+
break;
|
|
1528
|
+
case "BadMessage":
|
|
1529
|
+
case "Internal":
|
|
1530
|
+
if (this.#retryPushTimer) clearTimeout(this.#retryPushTimer);
|
|
1531
|
+
this.#retryPushTimer = setTimeout(() => this.#flushPush(), 1e3);
|
|
1532
|
+
break;
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
#nextMutationId() {
|
|
1536
|
+
let max = this.#confirmedLmid;
|
|
1537
|
+
for (const entry of this.#outbox) if (entry.id !== null && entry.id > max) max = entry.id;
|
|
1538
|
+
return max + 1;
|
|
1539
|
+
}
|
|
1540
|
+
#assignPendingIds() {
|
|
1541
|
+
for (const entry of this.#outbox) if (entry.id === null) entry.id = this.#nextMutationId();
|
|
1542
|
+
this.#persistOutbox();
|
|
1543
|
+
}
|
|
1544
|
+
#rebaseOutboxIds() {
|
|
1545
|
+
let next = this.#confirmedLmid;
|
|
1546
|
+
for (const entry of this.#outbox) entry.id = ++next;
|
|
1547
|
+
this.#persistOutbox();
|
|
1548
|
+
}
|
|
1549
|
+
#settleOutbox(results) {
|
|
1550
|
+
const errorById = new Map(results.filter((r) => r.error).map((r) => [r.id, r.error]));
|
|
1551
|
+
for (const entry of [...this.#outbox]) if (entry.id !== null && entry.id <= this.#confirmedLmid) {
|
|
1552
|
+
const error = errorById.get(entry.id);
|
|
1553
|
+
this.#settleEntry(entry, error ? new MutationError(error.code, error.message, {
|
|
1554
|
+
name: entry.name,
|
|
1555
|
+
args: entry.args
|
|
1556
|
+
}) : void 0);
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
#settleEntry(entry, error) {
|
|
1560
|
+
if (!entry.settled) {
|
|
1561
|
+
entry.settled = true;
|
|
1562
|
+
if (entry.timer) {
|
|
1563
|
+
clearTimeout(entry.timer);
|
|
1564
|
+
entry.timer = null;
|
|
1565
|
+
}
|
|
1566
|
+
if (error) entry.reject(error);
|
|
1567
|
+
else entry.resolve();
|
|
1568
|
+
}
|
|
1569
|
+
this.#outbox = this.#outbox.filter((e) => e !== entry);
|
|
1570
|
+
this.#persistOutbox();
|
|
1571
|
+
}
|
|
1572
|
+
#schedulePush() {
|
|
1573
|
+
if (this.#flushScheduled) return;
|
|
1574
|
+
this.#flushScheduled = true;
|
|
1575
|
+
queueMicrotask(() => {
|
|
1576
|
+
this.#flushScheduled = false;
|
|
1577
|
+
this.#flushPush();
|
|
1578
|
+
});
|
|
1579
|
+
}
|
|
1580
|
+
#outboxSnapshot() {
|
|
1581
|
+
return this.#outbox.map((e) => ({
|
|
1582
|
+
id: e.id,
|
|
1583
|
+
name: e.name,
|
|
1584
|
+
args: e.args
|
|
1585
|
+
}));
|
|
1586
|
+
}
|
|
1587
|
+
/**
|
|
1588
|
+
* Persists the outbox alone (microtask-coalesced). Suppressed during
|
|
1589
|
+
* hydration (a partial snapshot would clobber restored entries) and after
|
|
1590
|
+
* stop (stopping must not discard the durable outbox).
|
|
1591
|
+
*/
|
|
1592
|
+
#persistOutbox() {
|
|
1593
|
+
const store = this.#store;
|
|
1594
|
+
if (!store || this.#hydrating || this.#stopped || this.#persistScheduled) return;
|
|
1595
|
+
this.#persistScheduled = true;
|
|
1596
|
+
queueMicrotask(() => {
|
|
1597
|
+
this.#persistScheduled = false;
|
|
1598
|
+
if (this.#stopped) return;
|
|
1599
|
+
store.saveOutbox(this.#outboxSnapshot(), this.#confirmedLmid).catch((err) => this.#log("warn", "[cf-sync] failed to persist outbox", err));
|
|
1600
|
+
});
|
|
1601
|
+
}
|
|
1602
|
+
#flushPush() {
|
|
1603
|
+
if (!this.#socket || !this.#syncedThisConnection) return;
|
|
1604
|
+
const mutations = this.#outbox.filter((e) => e.id !== null && e.id > this.#confirmedLmid).sort((a, b) => a.id - b.id).map((e) => ({
|
|
1605
|
+
id: e.id,
|
|
1606
|
+
name: e.name,
|
|
1607
|
+
args: e.args
|
|
1608
|
+
}));
|
|
1609
|
+
if (mutations.length > 0) this.#send({
|
|
1610
|
+
type: "push",
|
|
1611
|
+
mutations
|
|
1612
|
+
});
|
|
1613
|
+
}
|
|
1614
|
+
#presenceSet(state) {
|
|
1615
|
+
const schema = this.#opts.app.presence;
|
|
1616
|
+
if (!schema) throw new Error("SyncClient: the app declares no presence schema — add `presence: <schema>` to defineApp to use client.presence");
|
|
1617
|
+
if (state !== null) {
|
|
1618
|
+
const result = schema["~standard"].validate(state);
|
|
1619
|
+
if (result instanceof Promise) result.catch(() => {});
|
|
1620
|
+
else if (result.issues) throw new Error(`SyncClient: presence state fails the app's presence schema: ${formatIssues(result.issues)}`);
|
|
1621
|
+
else {
|
|
1622
|
+
state = result.value;
|
|
1623
|
+
if (!this.#presenceRoundTripChecked) {
|
|
1624
|
+
this.#presenceRoundTripChecked = true;
|
|
1625
|
+
const echo = schema["~standard"].validate(state);
|
|
1626
|
+
if (!(echo instanceof Promise) && echo.issues) throw new Error(`SyncClient: the presence schema does not parse its own output (${formatIssues(echo.issues)}). presence.update merges into previously parsed state and reconnect re-announces it, so the schema must round-trip — use a plain object schema (no transform/pipe) for presence (ARCHITECTURE.md#presence)`);
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
if (jsonByteSize(state) > MAX_PRESENCE_BYTES) throw new Error(`SyncClient: presence state exceeds ${MAX_PRESENCE_BYTES} bytes`);
|
|
1630
|
+
}
|
|
1631
|
+
this.#presenceState = state;
|
|
1632
|
+
this.#schedulePresenceSend();
|
|
1633
|
+
this.#notifyPresence();
|
|
1634
|
+
}
|
|
1635
|
+
#presenceUpdate(partial) {
|
|
1636
|
+
const current = this.#presenceState;
|
|
1637
|
+
const base = typeof current === "object" && current !== null ? current : {};
|
|
1638
|
+
try {
|
|
1639
|
+
this.#presenceSet({
|
|
1640
|
+
...base,
|
|
1641
|
+
...partial
|
|
1642
|
+
});
|
|
1643
|
+
} catch (err) {
|
|
1644
|
+
if (current === void 0 || current === null) {
|
|
1645
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
1646
|
+
throw new Error(`SyncClient: presence.update() was called before any presence state existed, so the partial merged into {} — a mount-order race, not a data bug. Pass initialPresence at construction (or call presence.set once first); every later call can then stay a bare partial. (${detail})`);
|
|
1647
|
+
}
|
|
1648
|
+
throw err;
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
/**
|
|
1652
|
+
* Trailing-edge throttle: at most one frame per cadence window, carrying
|
|
1653
|
+
* whatever `#presenceState` holds when it fires — so `set` is safe at input
|
|
1654
|
+
* frequency and the last call always wins.
|
|
1655
|
+
*/
|
|
1656
|
+
#schedulePresenceSend() {
|
|
1657
|
+
if (this.#presenceTimer !== null) return;
|
|
1658
|
+
const cadence = this.#opts.presenceThrottleMs ?? 100;
|
|
1659
|
+
const elapsed = Date.now() - this.#presenceLastSentAt;
|
|
1660
|
+
if (elapsed >= cadence) {
|
|
1661
|
+
this.#sendPresence();
|
|
1662
|
+
return;
|
|
1663
|
+
}
|
|
1664
|
+
this.#presenceTimer = setTimeout(() => {
|
|
1665
|
+
this.#presenceTimer = null;
|
|
1666
|
+
this.#sendPresence();
|
|
1667
|
+
}, cadence - elapsed);
|
|
1668
|
+
}
|
|
1669
|
+
#sendPresence() {
|
|
1670
|
+
if (!this.#presenceLive || !this.#socket || this.#presenceState === void 0) return;
|
|
1671
|
+
this.#presenceLastSentAt = Date.now();
|
|
1672
|
+
this.#send({
|
|
1673
|
+
type: "presence",
|
|
1674
|
+
state: this.#presenceState
|
|
1675
|
+
});
|
|
1676
|
+
}
|
|
1677
|
+
#applyPeerUpdate(clientId, principal, state) {
|
|
1678
|
+
if (clientId === this.#clientId) return;
|
|
1679
|
+
if (state === null || state === void 0) {
|
|
1680
|
+
if (!this.#presencePeers.delete(clientId)) return;
|
|
1681
|
+
} else {
|
|
1682
|
+
const peer = {
|
|
1683
|
+
clientId,
|
|
1684
|
+
state,
|
|
1685
|
+
receivedAt: Date.now()
|
|
1686
|
+
};
|
|
1687
|
+
if (principal !== void 0) peer.principal = principal;
|
|
1688
|
+
this.#presencePeers.set(clientId, peer);
|
|
1689
|
+
}
|
|
1690
|
+
this.#notifyPresence();
|
|
1691
|
+
}
|
|
1692
|
+
/** Peers reset to empty on disconnect — stale presence is worse than absent presence. */
|
|
1693
|
+
#presenceDisconnected() {
|
|
1694
|
+
this.#presenceLive = false;
|
|
1695
|
+
if (this.#presenceTimer) {
|
|
1696
|
+
clearTimeout(this.#presenceTimer);
|
|
1697
|
+
this.#presenceTimer = null;
|
|
1698
|
+
}
|
|
1699
|
+
if (this.#presencePeers.size === 0) return;
|
|
1700
|
+
this.#presencePeers.clear();
|
|
1701
|
+
this.#notifyPresence();
|
|
1702
|
+
}
|
|
1703
|
+
#notifyPresence() {
|
|
1704
|
+
this.#presenceSnapshot = null;
|
|
1705
|
+
for (const listener of this.#presenceListeners) listener();
|
|
1706
|
+
}
|
|
1707
|
+
#presencePeersList() {
|
|
1708
|
+
this.#presenceSnapshot ??= [...this.#presencePeers.values()];
|
|
1709
|
+
return this.#presenceSnapshot;
|
|
1710
|
+
}
|
|
1711
|
+
#send(msg) {
|
|
1712
|
+
try {
|
|
1713
|
+
this.#socket?.send(JSON.stringify(msg));
|
|
1714
|
+
} catch {}
|
|
1715
|
+
}
|
|
1716
|
+
#setStatus(status) {
|
|
1717
|
+
if (this.#status === status) return;
|
|
1718
|
+
this.#status = status;
|
|
1719
|
+
this.#opts.onStatusChange?.(status);
|
|
1720
|
+
for (const listener of this.#statusListeners) listener(status);
|
|
1721
|
+
}
|
|
1722
|
+
#fatal(error) {
|
|
1723
|
+
this.#setStatus("fatal");
|
|
1724
|
+
this.#stopHeartbeat();
|
|
1725
|
+
this.#presenceDisconnected();
|
|
1726
|
+
for (const hooks of this.#tables.values()) hooks.markReady();
|
|
1727
|
+
for (const entry of [...this.#outbox]) this.#settleEntry(entry, error);
|
|
1728
|
+
try {
|
|
1729
|
+
this.#socket?.close(1e3, "fatal");
|
|
1730
|
+
} catch {}
|
|
1731
|
+
this.#socket = null;
|
|
1732
|
+
if (this.#opts.onFatal) this.#opts.onFatal(error);
|
|
1733
|
+
else defaultFatalRecovery(this.#opts.workspaceId, error, this.#opts.logger ?? consoleLogger);
|
|
1734
|
+
}
|
|
1735
|
+
#warnUnregistered(tbl) {
|
|
1736
|
+
if (this.#warnedTables.has(tbl)) return;
|
|
1737
|
+
this.#warnedTables.add(tbl);
|
|
1738
|
+
this.#log("warn", `[cf-sync] dropping synced data for unregistered table "${tbl}"`);
|
|
1739
|
+
}
|
|
1740
|
+
};
|
|
1741
|
+
//#endregion
|
|
1742
|
+
//#region src/collection.ts
|
|
1743
|
+
/**
|
|
1744
|
+
* ARCHITECTURE.md#optimistic-intents: one atomic optimistic transaction per intent mutation.
|
|
1745
|
+
* Writes inside `tx.mutate` join the ambient transaction and skip the
|
|
1746
|
+
* collections' own mutation handlers; the overlay drops when `persist`
|
|
1747
|
+
* resolves (the confirm patch is already applied — synced commits buffer
|
|
1748
|
+
* while the transaction persists, so the swap is one recompute) and rolls
|
|
1749
|
+
* back when it rejects.
|
|
1750
|
+
*/
|
|
1751
|
+
const runIntentTransaction = (intent, flush, persist) => {
|
|
1752
|
+
const tx = createTransaction({
|
|
1753
|
+
mutationFn: () => persist(),
|
|
1754
|
+
metadata: { intent }
|
|
1755
|
+
});
|
|
1756
|
+
tx.mutate(flush);
|
|
1757
|
+
if (tx.mutations.length === 0) return persist();
|
|
1758
|
+
return tx.isPersisted.promise.then(() => void 0);
|
|
1759
|
+
};
|
|
1760
|
+
/** TanStack enriches rows with virtual props; keep them out of mutator reads and overlays. */
|
|
1761
|
+
function stripVirtualProps(row) {
|
|
1762
|
+
const { $synced, $origin, $key, $collectionId, ...data } = row;
|
|
1763
|
+
return data;
|
|
1764
|
+
}
|
|
1765
|
+
function createHookGate() {
|
|
1766
|
+
let target = null;
|
|
1767
|
+
let pendingClear = false;
|
|
1768
|
+
let pendingReady = false;
|
|
1769
|
+
const pendingOps = /* @__PURE__ */ new Map();
|
|
1770
|
+
return {
|
|
1771
|
+
hooks: {
|
|
1772
|
+
begin: () => target?.begin(),
|
|
1773
|
+
write: (op) => {
|
|
1774
|
+
if (target) target.write(op);
|
|
1775
|
+
else pendingOps.set(op.id, op);
|
|
1776
|
+
},
|
|
1777
|
+
commit: () => target?.commit(),
|
|
1778
|
+
truncate: () => {
|
|
1779
|
+
if (target) target.truncate();
|
|
1780
|
+
else {
|
|
1781
|
+
pendingClear = true;
|
|
1782
|
+
pendingOps.clear();
|
|
1783
|
+
}
|
|
1784
|
+
},
|
|
1785
|
+
markReady: () => {
|
|
1786
|
+
if (target) target.markReady();
|
|
1787
|
+
else pendingReady = true;
|
|
1788
|
+
}
|
|
1789
|
+
},
|
|
1790
|
+
attach: (t) => {
|
|
1791
|
+
target = t;
|
|
1792
|
+
if (pendingClear || pendingOps.size > 0) {
|
|
1793
|
+
t.begin();
|
|
1794
|
+
if (pendingClear) t.truncate();
|
|
1795
|
+
for (const op of pendingOps.values()) t.write(op);
|
|
1796
|
+
t.commit();
|
|
1797
|
+
}
|
|
1798
|
+
if (pendingReady) t.markReady();
|
|
1799
|
+
pendingClear = false;
|
|
1800
|
+
pendingReady = false;
|
|
1801
|
+
pendingOps.clear();
|
|
1802
|
+
},
|
|
1803
|
+
detach: () => {
|
|
1804
|
+
target = null;
|
|
1805
|
+
}
|
|
1806
|
+
};
|
|
1807
|
+
}
|
|
1808
|
+
function collectionApplier(collection) {
|
|
1809
|
+
return {
|
|
1810
|
+
has: (id) => collection.has(id),
|
|
1811
|
+
get: (id) => {
|
|
1812
|
+
const row = collection.get(id);
|
|
1813
|
+
return row ? stripVirtualProps(row) : null;
|
|
1814
|
+
},
|
|
1815
|
+
list: () => Array.from(collection.entries(), ([id, data]) => ({
|
|
1816
|
+
id,
|
|
1817
|
+
data: stripVirtualProps(data)
|
|
1818
|
+
})),
|
|
1819
|
+
insert: (data) => {
|
|
1820
|
+
collection.insert(data);
|
|
1821
|
+
},
|
|
1822
|
+
update: (id, data) => {
|
|
1823
|
+
collection.update(id, (draft) => {
|
|
1824
|
+
for (const key of Object.keys(draft)) if (!(key in data)) delete draft[key];
|
|
1825
|
+
Object.assign(draft, data);
|
|
1826
|
+
});
|
|
1827
|
+
},
|
|
1828
|
+
delete: (id) => {
|
|
1829
|
+
collection.delete(id);
|
|
1830
|
+
}
|
|
1831
|
+
};
|
|
1832
|
+
}
|
|
1833
|
+
/**
|
|
1834
|
+
* TanStack DB collection options creator backed by a cf-sync SyncClient.
|
|
1835
|
+
* The row type, the collection's runtime validation schema, and the key
|
|
1836
|
+
* function all derive from the table's entry in the shared `defineSchema`.
|
|
1837
|
+
*
|
|
1838
|
+
* Synced data flows through the poke pipeline (begin/write/commit per poke,
|
|
1839
|
+
* truncate on reset). Local writes become `sync.put` / `sync.del` mutations;
|
|
1840
|
+
* each handler resolves only when the server confirms the mutation, at which
|
|
1841
|
+
* point TanStack DB drops the optimistic overlay (TanStack's store handles
|
|
1842
|
+
* rebasing overlays on top of newly synced state).
|
|
1843
|
+
*
|
|
1844
|
+
* Table hooks register with the client at options creation, buffered until
|
|
1845
|
+
* TanStack starts the sync pipeline — a lazily-subscribed collection costs no
|
|
1846
|
+
* full resync. The collection also serves as `mutate`'s optimistic surface:
|
|
1847
|
+
* intent mutations run their shared `apply` against it locally.
|
|
1848
|
+
*/
|
|
1849
|
+
function workspaceCollectionOptions(cfg) {
|
|
1850
|
+
const { client, table } = cfg;
|
|
1851
|
+
const tableSchema = client.schema.tables[table];
|
|
1852
|
+
if (!tableSchema) throw new Error(`workspaceCollectionOptions: table "${table}" is not in the schema passed to SyncClient — known tables: ${Object.keys(client.schema.tables).join(", ") || "(none)"}`);
|
|
1853
|
+
for (const required of ["sync.put", "sync.del"]) if (!client.app.mutators[required]) throw new Error(`workspaceCollectionOptions: the app's mutator registry has no "${required}", which collections emit for local writes — the app was defined with crud: false; remove it (defineApp includes the crud mutators by default) or drive this table through intent mutators only, without a collection`);
|
|
1854
|
+
const getKey = cfg.getKey ?? ((row) => {
|
|
1855
|
+
const id = row.id;
|
|
1856
|
+
if (typeof id !== "string") throw new Error(`workspaceCollectionOptions: row in table "${table}" has no string "id"; provide getKey`);
|
|
1857
|
+
return id;
|
|
1858
|
+
});
|
|
1859
|
+
const mutate = (name, args) => client[RAW_MUTATE](name, args);
|
|
1860
|
+
const gate = createHookGate();
|
|
1861
|
+
let registered = true;
|
|
1862
|
+
let unregister = client.registerTable(table, gate.hooks);
|
|
1863
|
+
return {
|
|
1864
|
+
id: `workspace-${client.workspaceId}-${table}`,
|
|
1865
|
+
getKey,
|
|
1866
|
+
schema: tableSchema,
|
|
1867
|
+
startSync: cfg.startSync,
|
|
1868
|
+
sync: {
|
|
1869
|
+
rowUpdateMode: "full",
|
|
1870
|
+
sync: (params) => {
|
|
1871
|
+
const { begin, write, commit, markReady, truncate } = params;
|
|
1872
|
+
client.registerApplier(table, collectionApplier(params.collection), runIntentTransaction);
|
|
1873
|
+
if (!registered) {
|
|
1874
|
+
unregister = client.registerTable(table, gate.hooks);
|
|
1875
|
+
registered = true;
|
|
1876
|
+
}
|
|
1877
|
+
const syncedKeys = /* @__PURE__ */ new Set();
|
|
1878
|
+
gate.attach({
|
|
1879
|
+
begin: () => begin(),
|
|
1880
|
+
write: (op) => {
|
|
1881
|
+
if (op.type === "put") {
|
|
1882
|
+
const type = syncedKeys.has(op.id) ? "update" : "insert";
|
|
1883
|
+
syncedKeys.add(op.id);
|
|
1884
|
+
write({
|
|
1885
|
+
type,
|
|
1886
|
+
value: op.value
|
|
1887
|
+
});
|
|
1888
|
+
} else if (syncedKeys.delete(op.id)) write({
|
|
1889
|
+
type: "delete",
|
|
1890
|
+
key: op.id
|
|
1891
|
+
});
|
|
1892
|
+
},
|
|
1893
|
+
commit: () => commit(),
|
|
1894
|
+
truncate: () => {
|
|
1895
|
+
syncedKeys.clear();
|
|
1896
|
+
truncate();
|
|
1897
|
+
},
|
|
1898
|
+
markReady: () => markReady()
|
|
1899
|
+
});
|
|
1900
|
+
return { cleanup: () => {
|
|
1901
|
+
gate.detach();
|
|
1902
|
+
unregister();
|
|
1903
|
+
registered = false;
|
|
1904
|
+
} };
|
|
1905
|
+
}
|
|
1906
|
+
},
|
|
1907
|
+
onInsert: async ({ transaction }) => {
|
|
1908
|
+
await Promise.all(transaction.mutations.map((m) => mutate("sync.put", {
|
|
1909
|
+
tbl: table,
|
|
1910
|
+
id: getKey(m.modified),
|
|
1911
|
+
data: m.modified
|
|
1912
|
+
})));
|
|
1913
|
+
},
|
|
1914
|
+
onUpdate: async ({ transaction }) => {
|
|
1915
|
+
await Promise.all(transaction.mutations.map((m) => mutate("sync.put", {
|
|
1916
|
+
tbl: table,
|
|
1917
|
+
id: getKey(m.modified),
|
|
1918
|
+
data: m.modified
|
|
1919
|
+
})));
|
|
1920
|
+
},
|
|
1921
|
+
onDelete: async ({ transaction }) => {
|
|
1922
|
+
await Promise.all(transaction.mutations.map((m) => mutate("sync.del", {
|
|
1923
|
+
tbl: table,
|
|
1924
|
+
id: String(m.key)
|
|
1925
|
+
})));
|
|
1926
|
+
}
|
|
1927
|
+
};
|
|
1928
|
+
}
|
|
1929
|
+
/**
|
|
1930
|
+
* Creates one collection per table in the client's schema, fully typed —
|
|
1931
|
+
* the one-line alternative to a `createCollection(workspaceCollectionOptions(…))`
|
|
1932
|
+
* block per table:
|
|
1933
|
+
*
|
|
1934
|
+
* ```ts
|
|
1935
|
+
* const { todos, issues } = createCollections(client)
|
|
1936
|
+
* ```
|
|
1937
|
+
*
|
|
1938
|
+
* Collections start syncing immediately (`startSync` defaults to true here,
|
|
1939
|
+
* unlike `workspaceCollectionOptions`, which keeps TanStack's lazy default):
|
|
1940
|
+
* the client receives pokes for every table on the one socket regardless, so
|
|
1941
|
+
* eager sync costs no extra network — it only applies already-buffered data,
|
|
1942
|
+
* and first render sees rows without waiting for a subscriber. Pass
|
|
1943
|
+
* `{ startSync: false }` to defer to first subscriber anyway.
|
|
1944
|
+
*
|
|
1945
|
+
* Rows are keyed by their `id` field (this engine's row model); a table whose
|
|
1946
|
+
* rows key differently needs an individual `workspaceCollectionOptions` call
|
|
1947
|
+
* with its own `getKey`.
|
|
1948
|
+
*/
|
|
1949
|
+
function createCollections(client, options) {
|
|
1950
|
+
const collections = {};
|
|
1951
|
+
for (const table of Object.keys(client.schema.tables)) {
|
|
1952
|
+
const collection = createCollection(workspaceCollectionOptions({
|
|
1953
|
+
client,
|
|
1954
|
+
table,
|
|
1955
|
+
startSync: options?.startSync ?? true
|
|
1956
|
+
}));
|
|
1957
|
+
client.registerApplier(table, collectionApplier(collection), runIntentTransaction);
|
|
1958
|
+
client.onDestroy(() => collection.cleanup());
|
|
1959
|
+
collections[table] = collection;
|
|
1960
|
+
}
|
|
1961
|
+
return collections;
|
|
1962
|
+
}
|
|
1963
|
+
/**
|
|
1964
|
+
* The one-call bootstrap: constructs the `SyncClient` and every collection,
|
|
1965
|
+
* and returns them with their shared teardown —
|
|
1966
|
+
*
|
|
1967
|
+
* ```ts
|
|
1968
|
+
* const ws = createWorkspace({ url: SYNC_URL, workspaceId, app, persist: true })
|
|
1969
|
+
* ws.collections.todos.insert({ id, title: 'ship it' })
|
|
1970
|
+
* await ws.client.mutate.todos.clearCompleted()
|
|
1971
|
+
* ```
|
|
1972
|
+
*
|
|
1973
|
+
* The unit shape is the point for workspace-per-project apps: switching
|
|
1974
|
+
* projects is `await ws.destroy()` then `createWorkspace({ ...same, workspaceId: next })`
|
|
1975
|
+
* — nothing to individually rebuild or re-thread. Takes every
|
|
1976
|
+
* `SyncClientOptions` field, plus `startSync` forwarded to
|
|
1977
|
+
* {@link createCollections}.
|
|
1978
|
+
*/
|
|
1979
|
+
function createWorkspace(options) {
|
|
1980
|
+
const { startSync, ...clientOptions } = options;
|
|
1981
|
+
const client = new SyncClient(clientOptions);
|
|
1982
|
+
return {
|
|
1983
|
+
client,
|
|
1984
|
+
collections: createCollections(client, startSync === void 0 ? void 0 : { startSync }),
|
|
1985
|
+
destroy: () => client.destroy()
|
|
1986
|
+
};
|
|
1987
|
+
}
|
|
1988
|
+
//#endregion
|
|
1989
|
+
//#region src/store.ts
|
|
1990
|
+
/**
|
|
1991
|
+
* In-memory SyncStore: reference implementation and test double. Also usable
|
|
1992
|
+
* to pass a fresh "store" that intentionally forgets on reload.
|
|
1993
|
+
*/
|
|
1994
|
+
var MemorySyncStore = class {
|
|
1995
|
+
#schemaVersion = null;
|
|
1996
|
+
#cursor = null;
|
|
1997
|
+
#confirmedLmid = 0;
|
|
1998
|
+
#rows = /* @__PURE__ */ new Map();
|
|
1999
|
+
#outbox = [];
|
|
2000
|
+
#hasState = false;
|
|
2001
|
+
async load() {
|
|
2002
|
+
if (!this.#hasState) return null;
|
|
2003
|
+
const rows = [];
|
|
2004
|
+
for (const [tbl, byId] of this.#rows) for (const [id, value] of byId) rows.push({
|
|
2005
|
+
tbl,
|
|
2006
|
+
id,
|
|
2007
|
+
value
|
|
2008
|
+
});
|
|
2009
|
+
return {
|
|
2010
|
+
schemaVersion: this.#schemaVersion,
|
|
2011
|
+
cursor: this.#cursor,
|
|
2012
|
+
confirmedLmid: this.#confirmedLmid,
|
|
2013
|
+
rows,
|
|
2014
|
+
outbox: this.#outbox.map((e) => ({ ...e }))
|
|
2015
|
+
};
|
|
2016
|
+
}
|
|
2017
|
+
async applyPoke(update) {
|
|
2018
|
+
if (!update.clear && this.#cursor !== null && this.#cursor.backendId === update.cursor.backendId && this.#cursor.version >= update.cursor.version) {
|
|
2019
|
+
await this.saveOutbox(update.outbox, update.confirmedLmid);
|
|
2020
|
+
return;
|
|
2021
|
+
}
|
|
2022
|
+
if (update.clear) this.#rows.clear();
|
|
2023
|
+
for (const op of update.ops) {
|
|
2024
|
+
let byId = this.#rows.get(op.tbl);
|
|
2025
|
+
if (op.op === "put") {
|
|
2026
|
+
if (!byId) this.#rows.set(op.tbl, byId = /* @__PURE__ */ new Map());
|
|
2027
|
+
byId.set(op.id, op.value);
|
|
2028
|
+
} else byId?.delete(op.id);
|
|
2029
|
+
}
|
|
2030
|
+
this.#cursor = update.cursor;
|
|
2031
|
+
this.#schemaVersion = update.schemaVersion;
|
|
2032
|
+
this.#confirmedLmid = update.confirmedLmid;
|
|
2033
|
+
this.#outbox = update.outbox.map((e) => ({ ...e }));
|
|
2034
|
+
this.#hasState = true;
|
|
2035
|
+
}
|
|
2036
|
+
async saveOutbox(outbox, confirmedLmid) {
|
|
2037
|
+
this.#outbox = outbox.map((e) => ({ ...e }));
|
|
2038
|
+
this.#confirmedLmid = confirmedLmid;
|
|
2039
|
+
this.#hasState = true;
|
|
2040
|
+
}
|
|
2041
|
+
async reset() {
|
|
2042
|
+
this.#schemaVersion = null;
|
|
2043
|
+
this.#cursor = null;
|
|
2044
|
+
this.#confirmedLmid = 0;
|
|
2045
|
+
this.#rows.clear();
|
|
2046
|
+
this.#outbox = [];
|
|
2047
|
+
this.#hasState = false;
|
|
2048
|
+
}
|
|
2049
|
+
};
|
|
2050
|
+
//#endregion
|
|
2051
|
+
export { AppError, CLOSE_AUTH_CONTEXT_INVALID, CLOSE_PERMANENT_MAX, CLOSE_PERMANENT_MIN, CLOSE_REFRESH, CLOSE_SUPERSEDED, CLOSE_UNAUTHORIZED, CLOSE_VERSION_NOT_SUPPORTED, IndexedDBSyncStore, MemorySyncStore, MutationError, SyncClient, SyncFatalError, createCollections, createWorkspace, crudMutators, defineApp, defineMutators, defineSchema, isPermanentCloseCode, workspaceCollectionOptions };
|