@cf-sync/client 0.3.2 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -220,7 +220,7 @@ function withToken(url, token) {
|
|
|
220
220
|
* instance is always safe — it just forfeits reload continuity.
|
|
221
221
|
*/
|
|
222
222
|
function defaultClientId(workspaceId) {
|
|
223
|
-
const key =
|
|
223
|
+
const key = clientIdKey(workspaceId);
|
|
224
224
|
try {
|
|
225
225
|
const stored = sessionStorage.getItem(key);
|
|
226
226
|
if (stored) return stored;
|
|
@@ -231,6 +231,59 @@ function defaultClientId(workspaceId) {
|
|
|
231
231
|
return crypto.randomUUID();
|
|
232
232
|
}
|
|
233
233
|
}
|
|
234
|
+
function clientIdKey(workspaceId) {
|
|
235
|
+
return `cf-sync:client-id:${encodeURIComponent(workspaceId)}`;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Claims made in this document, keyed by the id each started from (fresh ids
|
|
239
|
+
* included). A later or replacement client in the same tab joins the same
|
|
240
|
+
* claim, even one still waiting on its lock, instead of finding its own
|
|
241
|
+
* document's lock taken.
|
|
242
|
+
*/
|
|
243
|
+
const claims = /* @__PURE__ */ new Map();
|
|
244
|
+
function holdClientId(locks, clientId) {
|
|
245
|
+
return new Promise((resolve) => {
|
|
246
|
+
locks.request(`cf-sync:client:${clientId}`, { ifAvailable: true }, (lock) => {
|
|
247
|
+
if (!lock) {
|
|
248
|
+
resolve("taken");
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
resolve("held");
|
|
252
|
+
return new Promise(() => {});
|
|
253
|
+
}).catch(() => resolve("unavailable"));
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
async function claimOrMint(locks, workspaceId, clientId) {
|
|
257
|
+
if (await holdClientId(locks, clientId) !== "taken") return clientId;
|
|
258
|
+
const fresh = crypto.randomUUID();
|
|
259
|
+
claims.set(fresh, Promise.resolve(fresh));
|
|
260
|
+
try {
|
|
261
|
+
sessionStorage.setItem(clientIdKey(workspaceId), fresh);
|
|
262
|
+
} catch {}
|
|
263
|
+
await holdClientId(locks, fresh);
|
|
264
|
+
return fresh;
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Confirms the managed clientId belongs to this tab alone. Duplicating a tab
|
|
268
|
+
* clones its sessionStorage, so the copy would present the original's id: the
|
|
269
|
+
* server would supersede the original's socket, and both tabs would share one
|
|
270
|
+
* mutation sequence and outbox partition. A Web Lock held per id for the
|
|
271
|
+
* document's lifetime tells a duplicate (another live tab holds the lock) from
|
|
272
|
+
* a reload or a crash-restored tab (the lock died with the old document), so
|
|
273
|
+
* only the duplicate mints a fresh id and reloads keep replaying their outbox.
|
|
274
|
+
* Without Web Locks (outside a browser document, sandboxed frames) the id is
|
|
275
|
+
* kept as before.
|
|
276
|
+
*/
|
|
277
|
+
function claimClientId(workspaceId, clientId) {
|
|
278
|
+
const locks = typeof document !== "undefined" && typeof navigator !== "undefined" ? navigator.locks : void 0;
|
|
279
|
+
if (!locks) return Promise.resolve(clientId);
|
|
280
|
+
let claim = claims.get(clientId);
|
|
281
|
+
if (!claim) {
|
|
282
|
+
claim = claimOrMint(locks, workspaceId, clientId);
|
|
283
|
+
claims.set(clientId, claim);
|
|
284
|
+
}
|
|
285
|
+
return claim;
|
|
286
|
+
}
|
|
234
287
|
const FATAL_RELOAD_MIN_INTERVAL_MS = 6e4;
|
|
235
288
|
/**
|
|
236
289
|
* Default fatal handling: reload into the (presumably newer) bundle — the
|
|
@@ -620,6 +673,7 @@ var SyncClient = class {
|
|
|
620
673
|
this.#clientId = opts.clientId ?? defaultClientId(opts.workspaceId);
|
|
621
674
|
this.#url = buildSyncUrl(opts.url, opts.pathPrefix ?? "/sync", opts.workspaceId, this.#clientId);
|
|
622
675
|
this.#store = opts.store ?? (opts.persist ? createDefaultStore(opts.workspaceId, this.#clientId, opts.logger ?? consoleLogger) : void 0);
|
|
676
|
+
this.#hydrating = this.#store !== void 0;
|
|
623
677
|
this.mutate = buildMutate(Object.keys(opts.app.mutators), (name, args) => this.#guardMutation(name, args, this.#mutateByName(name, args)));
|
|
624
678
|
const self = this;
|
|
625
679
|
this.presence = {
|
|
@@ -822,6 +876,26 @@ var SyncClient = class {
|
|
|
822
876
|
this.#clearStartNudge();
|
|
823
877
|
this.#listenForWake(true);
|
|
824
878
|
this.#setStatus("connecting");
|
|
879
|
+
if (this.#opts.clientId === void 0 && this.#opts.store === void 0 && typeof document !== "undefined") {
|
|
880
|
+
claimClientId(this.#opts.workspaceId, this.#clientId).then((clientId) => {
|
|
881
|
+
if (this.#stopped) return;
|
|
882
|
+
if (clientId !== this.#clientId) this.#adoptClientId(clientId);
|
|
883
|
+
this.#begin();
|
|
884
|
+
});
|
|
885
|
+
return;
|
|
886
|
+
}
|
|
887
|
+
this.#begin();
|
|
888
|
+
}
|
|
889
|
+
#adoptClientId(clientId) {
|
|
890
|
+
const opts = this.#opts;
|
|
891
|
+
this.#clientId = clientId;
|
|
892
|
+
this.#url = buildSyncUrl(opts.url, opts.pathPrefix ?? "/sync", opts.workspaceId, clientId);
|
|
893
|
+
if (opts.persist) {
|
|
894
|
+
this.#store?.close?.();
|
|
895
|
+
this.#store = createDefaultStore(opts.workspaceId, clientId, opts.logger ?? consoleLogger);
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
#begin() {
|
|
825
899
|
const store = this.#store;
|
|
826
900
|
if (store) {
|
|
827
901
|
this.#hydrating = true;
|
|
@@ -1682,7 +1756,7 @@ var SyncClient = class {
|
|
|
1682
1756
|
this.#persistScheduled = true;
|
|
1683
1757
|
queueMicrotask(() => {
|
|
1684
1758
|
this.#persistScheduled = false;
|
|
1685
|
-
if (this.#stopped) return;
|
|
1759
|
+
if (this.#stopped || this.#hydrating || store !== this.#store) return;
|
|
1686
1760
|
store.saveOutbox(this.#outboxSnapshot(), this.#confirmedLmid).catch((err) => this.#log("warn", "[cf-sync] failed to persist outbox", err));
|
|
1687
1761
|
});
|
|
1688
1762
|
}
|
|
@@ -1843,11 +1917,11 @@ const runIntentTransaction = (intent, flush, persist) => {
|
|
|
1843
1917
|
});
|
|
1844
1918
|
tx.mutate(flush);
|
|
1845
1919
|
if (tx.mutations.length === 0) return persist();
|
|
1846
|
-
return tx.
|
|
1920
|
+
return tx.when("settled").then(() => void 0);
|
|
1847
1921
|
};
|
|
1848
1922
|
/** TanStack enriches rows with virtual props; keep them out of mutator reads and overlays. */
|
|
1849
1923
|
function stripVirtualProps(row) {
|
|
1850
|
-
const { $
|
|
1924
|
+
const { $hasPendingWrites, $origin, $key, $collectionId, ...data } = row;
|
|
1851
1925
|
return data;
|
|
1852
1926
|
}
|
|
1853
1927
|
function createHookGate() {
|
|
@@ -1953,6 +2027,7 @@ function workspaceCollectionOptions(cfg) {
|
|
|
1953
2027
|
getKey,
|
|
1954
2028
|
schema: tableSchema,
|
|
1955
2029
|
startSync: cfg.startSync,
|
|
2030
|
+
...cfg.startSync ? { gcTime: 0 } : {},
|
|
1956
2031
|
sync: {
|
|
1957
2032
|
rowUpdateMode: "full",
|
|
1958
2033
|
sync: (params) => {
|
|
@@ -2043,7 +2118,7 @@ function createCollections(client, options) {
|
|
|
2043
2118
|
startSync: options?.startSync ?? true
|
|
2044
2119
|
}));
|
|
2045
2120
|
client.registerApplier(table, collectionApplier(collection), runIntentTransaction);
|
|
2046
|
-
client.onDestroy(() => collection.cleanup());
|
|
2121
|
+
client.onDestroy(() => collection.cleanup({ dependents: true }));
|
|
2047
2122
|
collections[table] = collection;
|
|
2048
2123
|
}
|
|
2049
2124
|
return collections;
|
|
@@ -32,7 +32,7 @@ The unit shape is the point for workspace-per-project apps: switching projects i
|
|
|
32
32
|
|
|
33
33
|
One fully typed collection per table in the client's schema — the one-line alternative to a `createCollection(workspaceCollectionOptions(…))` block per table. Rows are keyed by their `id` field (this engine's row model); a table whose rows key differently needs an individual [`workspaceCollectionOptions`](#workspacecollectionoptions) call with its own `getKey`.
|
|
34
34
|
|
|
35
|
-
Each collection's lifetime is tied to the client: [`client.destroy()`](/reference/sync-client#destroy) cleans them up too, so switching workspaces is one call. Collection ids are scoped by workspace (`workspace-<workspaceId>-<table>`), so an app with two open workspaces never collides on TanStack DB's app-wide ids. The collections also serve as `mutate`'s optimistic surface — [intent mutations](/guide/mutations) run their shared `apply` against them locally, attached at creation so intents fired before a collection has subscribers still get their optimistic effect.
|
|
35
|
+
Each collection's lifetime is tied to the client: [`client.destroy()`](/reference/sync-client#destroy) cleans them up too, along with any live queries still reading them, so switching workspaces is one call. Collection ids are scoped by workspace (`workspace-<workspaceId>-<table>`), so an app with two open workspaces never collides on TanStack DB's app-wide ids. The collections also serve as `mutate`'s optimistic surface — [intent mutations](/guide/mutations) run their shared `apply` against them locally, attached at creation so intents fired before a collection has subscribers still get their optimistic effect.
|
|
36
36
|
|
|
37
37
|
### startSync
|
|
38
38
|
|
|
@@ -72,7 +72,7 @@ Maps a row to its collection key. Required only when the table's row schema has
|
|
|
72
72
|
|
|
73
73
|
`boolean` · default: TanStack's lazy default
|
|
74
74
|
|
|
75
|
-
Start the sync pipeline immediately instead of on first subscriber. `createCollections` flips this to `true` for you; here it stays lazy unless you opt in.
|
|
75
|
+
Start the sync pipeline immediately instead of on first subscriber. `createCollections` flips this to `true` for you; here it stays lazy unless you opt in. An eager collection is never garbage-collected for lack of subscribers: it lives until its `cleanup()`, which `createCollections` ties to `client.destroy()`. A lazy one keeps TanStack's `gcTime` default.
|
|
76
76
|
|
|
77
77
|
## Writes and the wire
|
|
78
78
|
|
|
@@ -52,7 +52,7 @@ Durable storage for synced rows, the cursor, and the outbox — pass your own [`
|
|
|
52
52
|
|
|
53
53
|
`string` · default: managed by the library
|
|
54
54
|
|
|
55
|
-
Identifies one contiguous mutation sequence — unique per SyncClient instance (per tab/session), never shared across concurrent tabs. The managed default is persisted per workspace in sessionStorage (reload continuity without cross-tab sharing), random where sessionStorage is unavailable. Pass explicitly to take over the lifecycle.
|
|
55
|
+
Identifies one contiguous mutation sequence — unique per SyncClient instance (per tab/session), never shared across concurrent tabs. The managed default is persisted per workspace in sessionStorage (reload continuity without cross-tab sharing), random where sessionStorage is unavailable. Duplicating a tab copies its sessionStorage, so in a browser the client holds a Web Lock on its id for the page's lifetime: a duplicate finds the lock taken and mints its own id before hydrating, while a reload or a crash-restored tab keeps its id and replays its queued mutations. This applies to the managed id with `persist` or no store, where Web Locks exist; with an explicit `clientId`, a custom `store`, or no Web Locks, the app must keep concurrent tabs from sharing an id. Pass explicitly to take over the lifecycle.
|
|
56
56
|
|
|
57
57
|
### authToken
|
|
58
58
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cf-sync/client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "Browser client for cf-sync: SyncClient (optimistic mutations, offline outbox, IndexedDB mirror, presence) and a TanStack DB collection adapter, with React hooks",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -43,8 +43,8 @@
|
|
|
43
43
|
"@cf-sync/protocol": "^0.2.1"
|
|
44
44
|
},
|
|
45
45
|
"peerDependencies": {
|
|
46
|
-
"@tanstack/db": "^0.
|
|
47
|
-
"@tanstack/react-db": "^0.
|
|
46
|
+
"@tanstack/db": "^1.0.0-rc.1",
|
|
47
|
+
"@tanstack/react-db": "^1.0.0-rc.1",
|
|
48
48
|
"react": ">=18"
|
|
49
49
|
},
|
|
50
50
|
"peerDependenciesMeta": {
|
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
}
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
|
-
"@tanstack/db": "
|
|
59
|
+
"@tanstack/db": "1.0.0-rc.1.5",
|
|
60
60
|
"@types/react": "^19.0.0",
|
|
61
61
|
"@types/react-dom": "^19.2.3",
|
|
62
62
|
"fake-indexeddb": "^6.2.5",
|