@cf-sync/client 0.1.0 → 0.1.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.
@@ -0,0 +1,102 @@
1
+ # Reading data
2
+
3
+ Reads are the half of the sync engine you don't see in the protocol: the whole workspace is already on the client, so **every query is local**. There is no fetch, no loading spinner per query, no cache to invalidate — a query is a live view over synced rows, updated incrementally as pokes land and optimistic writes apply. Collections created by [`createCollections`](/reference/collections) are plain TanStack DB collections; everything on this page is TanStack DB's query engine doing its job over cf-sync's data.
4
+
5
+ ```tsx
6
+ import { eq, useLiveQuery } from '@tanstack/react-db' // react-db re-exports all of @tanstack/db
7
+ import { issues } from './sync'
8
+
9
+ const { data: open } = useLiveQuery((q) =>
10
+ q
11
+ .from({ issue: issues })
12
+ .where(({ issue }) => eq(issue.column, 'open'))
13
+ .orderBy(({ issue }) => issue.createdAt, 'asc'),
14
+ )
15
+ ```
16
+
17
+ The result re-renders when — and only when — a row affecting it changes: a poke from another user, one of your own optimistic writes, a rollback. TanStack DB applies **differential updates** (the query doesn't re-run from scratch), so queries over thousands of rows stay cheap at interactive rates.
18
+
19
+ ## The mental model
20
+
21
+ Query state and sync state are different axes, and conflating them is the classic mistake:
22
+
23
+ - A query is **always answerable** — it runs against whatever is local right now. With [`persist: true`](/guide/offline-persistence), that includes every previously synced row from the first paint, before the socket even connects.
24
+ - Whether local state is *current* is the client's business, not the query's: render staleness from [`useSyncStatus`](/reference/sync-client#react-hooks), not by making queries wait. `useLiveQuery` does expose `isLoading`/`isReady`, but for synced collections these gate on the collection's first data, not on the server round-trip.
25
+
26
+ This is also why there are no query params to send anywhere: queries **filter** what's synced, they don't **fetch**. The workspace syncs whole to every member ([by design](/guide/why#honest-non-goals)) — a query can never pull in rows the workspace doesn't hold, and sizing workspaces so that's fine is the one thing the engine asks of your data model.
27
+
28
+ ## Filtering, sorting, shaping
29
+
30
+ The builder covers the SQL-shaped essentials — `where`, `select`, `orderBy`, `limit`, `offset`, `distinct`, `findOne` — with typed expression helpers imported from `@tanstack/db`:
31
+
32
+ ```ts
33
+ import { eq, and, or, not, gt, gte, lt, lte, inArray, like, ilike } from '@tanstack/db'
34
+
35
+ q.from({ issue: issues })
36
+ .where(({ issue }) => and(eq(issue.column, 'doing'), gt(issue.priority, 1)))
37
+ .orderBy(({ issue }) => issue.createdAt, 'desc')
38
+ .limit(50)
39
+ ```
40
+
41
+ Rows are typed from your [schema](/guide/defining-your-app#the-schema), so `issue.column` autocompletes and a typo is a compile error. Aggregations come from the same helper set (`count`, `sum`, `avg`, `min`, `max`) with `groupBy`/`having`:
42
+
43
+ ```ts
44
+ import { count, useLiveQuery } from '@tanstack/react-db'
45
+
46
+ const { data: perColumn } = useLiveQuery((q) =>
47
+ q
48
+ .from({ issue: issues })
49
+ .groupBy(({ issue }) => issue.column)
50
+ .select(({ issue }) => ({ column: issue.column, total: count(issue.id) })),
51
+ )
52
+ ```
53
+
54
+ ## Joins
55
+
56
+ Synced tables join like tables anywhere — `join` (left by default in TanStack DB's builder), or the explicit `innerJoin`/`leftJoin`/`rightJoin`/`fullJoin`:
57
+
58
+ ```ts
59
+ const { data: assigned } = useLiveQuery((q) =>
60
+ q
61
+ .from({ issue: issues })
62
+ .innerJoin({ user: users }, ({ issue, user }) => eq(issue.assigneeId, user.id))
63
+ .select(({ issue, user }) => ({ id: issue.id, title: issue.title, assignee: user.name })),
64
+ )
65
+ ```
66
+
67
+ Because both sides are local, joins cost no waterfall — this is where the synced-workspace model quietly pays for itself. The one discipline it asks: relations are by id (`assigneeId`), exactly as the [LWW row model](/guide/mutations) wants them, not embedded documents.
68
+
69
+ ## Derived collections
70
+
71
+ A query can be materialized as a collection of its own with `createLiveQueryCollection` from `@tanstack/db` — module scope, no React required — and further queries can build on it:
72
+
73
+ ```ts
74
+ import { createLiveQueryCollection, eq } from '@tanstack/db'
75
+
76
+ export const myIssues = createLiveQueryCollection((q) =>
77
+ q.from({ issue: issues }).where(({ issue }) => eq(issue.assigneeId, currentUserId)),
78
+ )
79
+ ```
80
+
81
+ Derived collections are the layering tool: one canonical filter defined once, consumed by many components (each `useLiveQuery` over it stays differential), instead of the same `where` clause copy-pasted per call site. They are read views — writes still go through the [source collections](/reference/collections) or [intent mutations](/guide/mutations).
82
+
83
+ ## Outside React
84
+
85
+ Collections are framework-free. The imperative surface:
86
+
87
+ ```ts
88
+ issues.get(id) // one row (or undefined)
89
+ issues.has(id)
90
+ issues.toArray // snapshot of all rows
91
+ issues.size
92
+
93
+ const unsubscribe = issues.subscribeChanges((changes) => {
94
+ // inserts/updates/deletes since last emission — a differential feed
95
+ })
96
+ ```
97
+
98
+ `subscribeChanges` plus `createLiveQueryCollection` is the complete vanilla story — what `useLiveQuery` wraps. Solid, Svelte, and Vue adapters exist upstream (`@tanstack/solid-db`, `@tanstack/svelte-db`, `@tanstack/vue-db`); cf-sync itself never assumes React.
99
+
100
+ ## Where the query engine's docs take over
101
+
102
+ Everything above is TanStack DB surface, documented exhaustively — operators, functional variants, index tuning, `unionAll` — in the [TanStack DB docs](https://tanstack.com/db/latest/docs/overview). What cf-sync adds is the contract underneath: rows arrive validated against the shared schema, appear atomically per mutation (a multi-row intent never renders half-applied), and optimistic writes flow through queries exactly like confirmed state — with rejection rollback arriving as just another change event.
@@ -0,0 +1,91 @@
1
+ # Schema evolution
2
+
3
+ The rule is short: **every schema change requires a version bump, paired with a migration entry.** Additive changes too. The engine enforces this instead of trusting you to remember.
4
+
5
+ ## Bumping the version
6
+
7
+ `version` is an integer starting at 1. When the schema changes, bump it and add a `migrations` entry keyed by the version it migrates *to*:
8
+
9
+ ```ts
10
+ export const app = defineApp({
11
+ version: 2,
12
+ schema, // issues now also have `priority`
13
+ mutators,
14
+ migrations: {
15
+ 2: (tx) => {
16
+ for (const { id, data } of tx.list('issues')) {
17
+ tx.put('issues', id, { priority: 'normal', ...data })
18
+ }
19
+ },
20
+ // an additive change that needs no data rewrite is an explicit null:
21
+ // 3: null
22
+ },
23
+ })
24
+ ```
25
+
26
+ The chain is validated at startup, in both bundles: entries must be consecutive and end at `version`. Bumping the version without saying what happens to existing data is a **loud error at boot**, not silent skew at runtime.
27
+
28
+ ## What happens on deploy
29
+
30
+ A workspace Durable Object can sleep through any number of deploys. On its first wake after one:
31
+
32
+ 1. The DO replays the migration chain from its stored version to the current one, **atomically** — a workspace that slept from v1 to v5 replays 2, 3, 4, 5 in order.
33
+ 2. The *net result* is validated against the current schema. A chain that produces invalid rows aborts instead of committing garbage.
34
+ 3. Old clients are rejected at hello with `VersionNotSupported` and reload into the new bundle.
35
+ 4. A stored version *outside* the chain (e.g. a rollback deploy) aborts initialization rather than restamping data it can't interpret.
36
+
37
+ ## Why additive changes need a bump too
38
+
39
+ Two failure modes, both silent without the bump:
40
+
41
+ - Rows written before the change never gain the new field at runtime — your zod defaults apply on *write*, not on read, so old rows stay in the old shape indefinitely.
42
+ - During a deploy window, old and new bundles share the same workspace. An old bundle doing a full-row write (`sync.put`) can silently strip a field it doesn't know about.
43
+
44
+ A `null` entry (or a backfill `migrate` when the new field needs a value on old rows) closes both holes.
45
+
46
+ ## Drift detection
47
+
48
+ This is enforced mechanically, not by convention — twice, at different distances from the mistake.
49
+
50
+ **In CI, before the deploy** (the one to actually rely on): add one test with `checkSchemaEvolution` from `@cf-sync/server/testing`, and a schema change without a version bump fails the build with the exact migrations entry to add:
51
+
52
+ ```ts
53
+ it('every schema change ships with a version bump', async () => {
54
+ await checkSchemaEvolution(app, new URL('./schema-snapshot.json', import.meta.url))
55
+ })
56
+ ```
57
+
58
+ The snapshot file works like a jest snapshot — the first run scaffolds it, a legitimate version bump rewrites it automatically, and you commit it. It records the same structural fingerprint the engine uses, so the two layers can never disagree about what counts as a change. (Presence is deliberately excluded — reshaping it needs no bump.)
59
+
60
+ **At runtime, after the fact**: each workspace also stores that fingerprint next to its version. If a deploy slips through with changed schemas under an unbumped version, the DO logs a warning that names the same fix:
61
+
62
+ ```
63
+ [cf-sync] table schemas changed under schema version 3 (fingerprint a41f… -> 9c02…).
64
+ Every schema change requires a version bump: set version: 4 in defineApp and add
65
+ migrations: { 4: ... } (a migrate function if existing rows need backfilling,
66
+ null if the change is additive)
67
+ ```
68
+
69
+ The runtime layer only warns (the fingerprint derives from zod's JSON Schema emission, which a zod upgrade could shift with no semantic change — a heuristic gets to shout, never to brick a workspace). The CI layer can afford to be strict: a false positive there is one deleted snapshot file, not an outage.
70
+
71
+ Both layers read zod's JSON Schema emission, so **drift detection only covers zod tables**. A table defined with another Standard Schema vendor fingerprints as opaque — its drift is invisible — and rather than silently passing forever, `checkSchemaEvolution` refuses to run over such tables and says so. Non-zod schemas still work for everything else (typing, validation); they just don't get the tripwire.
72
+
73
+ ## Testing migrations
74
+
75
+ Migrations are unit-testable in plain node with [`createTestEngine`](/guide/testing) — seed rows in their **old** shape at an old stored version, and the chain replays exactly as it would on the DO's first wake:
76
+
77
+ ```ts
78
+ const engine = createTestEngine(app, {
79
+ storedVersion: 1,
80
+ rows: { issues: { i1: { id: 'i1', title: 'old', column: 'doing' } } },
81
+ })
82
+ expect(engine.get('issues', 'i1')?.priority).toBe('normal')
83
+ ```
84
+
85
+ A chain that produces schema-invalid rows throws from `createTestEngine` itself — the same guarantee the DO gives you, in milliseconds.
86
+
87
+ ## What never changes
88
+
89
+ Mutator names deployed under a schema version are never removed — a queued mutation from an old client must always find its mutator when it finally arrives. (Replicache documents the failure mode: stubbing missing mutators to no-ops silently loses effects. cf-sync refuses to have the problem.)
90
+
91
+ Presence schemas are the exception to all of this: presence is ephemeral, nothing is stored, so reshaping it needs **no version bump** — see [Presence](/guide/presence#evolving-the-presence-schema).
@@ -0,0 +1,66 @@
1
+ # Testing your app
2
+
3
+ Your mutators and migrations are plain functions over a transaction — they deserve unit tests that run in milliseconds, not a workerd harness. `@cf-sync/server/testing` exports an in-memory engine that runs **the same write-buffer, validation, and error semantics as the Durable Object** — shared code, not a reimplementation.
4
+
5
+ ```ts
6
+ import { createTestEngine } from '@cf-sync/server/testing'
7
+ import { app } from '../src/schema'
8
+
9
+ it('clearCompleted deletes only completed todos', () => {
10
+ const engine = createTestEngine(app)
11
+ engine.seed('todos', 't1', { id: 't1', title: 'keep', done: false })
12
+ engine.seed('todos', 't2', { id: 't2', title: 'drop', done: true })
13
+
14
+ const result = engine.mutate('todo.clearCompleted', {})
15
+
16
+ expect(result.error).toBeUndefined()
17
+ expect(engine.get('todos', 't1')).toBeDefined()
18
+ expect(engine.get('todos', 't2')).toBeNull()
19
+ })
20
+ ```
21
+
22
+ Runs in plain vitest or jest, in node — no workerd, no miniflare, no bindings.
23
+
24
+ ::: warning Import paths matter in node
25
+ The server's **main** entry imports `cloudflare:workers`, which node can't load — never import it in test files that run outside workerd. To make that mistake hard, `@cf-sync/server/testing` re-exports the whole definition kit (`defineApp`, `defineSchema`, `defineMutators`, `crudMutators`, `AppError`, and their types), so a test file needs exactly one import source. Importing the kit from `@cf-sync/protocol` works identically.
26
+ :::
27
+
28
+ ## Testing migrations
29
+
30
+ Seed rows in their **old** shape at an old stored version; the migration chain replays inside `createTestEngine`, exactly like the DO's first wake after a deploy:
31
+
32
+ ```ts
33
+ it('the 1 -> 2 migration backfills priority', () => {
34
+ const engine = createTestEngine(app, {
35
+ storedVersion: 1,
36
+ rows: { issues: { i1: { id: 'i1', title: 'old', column: 'doing' } } },
37
+ })
38
+ expect(engine.get('issues', 'i1')?.priority).toBe('normal')
39
+ })
40
+ ```
41
+
42
+ A chain that produces schema-invalid rows throws from `createTestEngine` itself — you find out in the test run, not on a production workspace's first wake.
43
+
44
+ ## The schema-evolution tripwire
45
+
46
+ One more test makes the *forgotten* migration impossible to ship — a schema change with no version bump fails CI with the exact `migrations` entry to add:
47
+
48
+ ```ts
49
+ it('every schema change ships with a version bump', async () => {
50
+ await checkSchemaEvolution(app, new URL('./schema-snapshot.json', import.meta.url))
51
+ })
52
+ ```
53
+
54
+ Commit the snapshot file it scaffolds; a legitimate version bump rewrites it automatically. Details in [Schema evolution](/guide/schema-evolution#drift-detection).
55
+
56
+ ## The semantics are the real ones
57
+
58
+ The engine honors the [engine invariants](https://github.com/InfinityBowman/cf-sync/blob/main/ARCHITECTURE.md#invariants):
59
+
60
+ - An `AppError` from a mutator (or invalid args) reports as `result.error` — **permanent**, no data written, and `engine.lastMutationId()` still advances. Assert on both when testing rejection paths.
61
+ - Any other throw is **transient**: rethrown, nothing committed.
62
+ - Auth-dependent mutators can be exercised by passing a principal and auth context, so `ctx.authoritative` permission checks are testable without a socket in sight.
63
+
64
+ ## Testing the full stack
65
+
66
+ For end-to-end coverage (sockets, hibernation, convergence), the engine's own test suite runs against real workerd via `@cloudflare/vitest-pool-workers` — including a seeded multi-client convergence simulation. Most apps don't need to replicate that layer: if your mutators are correct against `createTestEngine`, the engine's contract tests cover the transport. Put your effort into mutator edge cases and migration coverage.
@@ -0,0 +1,68 @@
1
+ # Troubleshooting
2
+
3
+ The engine tries hard to make its error messages name the fix. This page collects the failure modes that happen *before* a good error message can reach you, plus context for the warnings you may see in logs.
4
+
5
+ ## The DO deploys fine, then fails on first SQL access
6
+
7
+ You declared the Durable Object with `new_classes` instead of **`new_sqlite_classes`**. The workspace DO requires SQLite-backed storage, and the storage backend of a deployed class cannot be changed — you'll need a new class name (or a fresh worker in dev):
8
+
9
+ ```jsonc
10
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["WorkspaceDO"] }]
11
+ ```
12
+
13
+ ## `Cannot resolve "cloudflare:workers"` in tests or scripts
14
+
15
+ Something running in node imported `@cf-sync/server`'s main entry. Only workerd can load it. In test files and node scripts, import `@cf-sync/server/testing` and get the definition kit from `@cf-sync/protocol` — see [Testing your app](/guide/testing).
16
+
17
+ ## `[cf-sync] dropped a binary frame that was not an ArrayBuffer`
18
+
19
+ You passed a custom `createSocket` and the socket it returns defaults to Blob binary frames. Set `binaryType = 'arraybuffer'` on it. Binary frames carry [yjs field](/guide/collaborative-text) traffic; without this, fields never sync.
20
+
21
+ ## `[cf-sync] table schemas changed under schema version N (fingerprint …)`
22
+
23
+ A deploy changed table schemas without bumping `version`. The warning names the exact entry to add. This is drift detection working — fix it before old and new bundles disagree about row shapes. See [Schema evolution](/guide/schema-evolution#drift-detection).
24
+
25
+ ## `defineApp: migrations end at N but version is M`
26
+
27
+ The migration chain must be consecutive and end at `version`. Every bump gets an entry: a `migrate` function if existing rows need rewriting, an explicit `null` if the change is additive.
28
+
29
+ ## The page reloads after a deploy
30
+
31
+ Working as intended: an old bundle was told `VersionNotSupported` and reloaded into the new one. Reloads are throttled to once per minute, so a bad deploy window degrades to paced retries. Pass `onFatal` to handle it yourself — see [Auth & sessions](/guide/auth#close-codes).
32
+
33
+ ## A mutation rejected with `RowTooLarge`
34
+
35
+ Single rows are capped (they must fit comfortably inside a chunked frame). Rows are for structured state, not payloads — put large text in a [yjs field](/guide/collaborative-text) and blobs in R2 with a key in the row.
36
+
37
+ ## Mutations reject with `Timeout` after ~30s
38
+
39
+ You're running memory-only (no `persist`). Without a durable store, a queued mutation can't survive a reload, so the client rejects rather than pretend. Turn on `persist: true` for a durable outbox with pending-until-delivered semantics — see [Offline & persistence](/guide/offline-persistence).
40
+
41
+ ## A departed peer's presence lingers
42
+
43
+ Liveness is TCP-bound: silent deaths (laptop lid, network partition) take ~75s+ to surface. Use each peer's `receivedAt` to fade stale entries on your own deadline — see [Presence](/guide/presence#two-semantics-to-know).
44
+
45
+ ## `workspaceCollectionOptions: table "…" is not in the schema`
46
+
47
+ The collection name must match a table key in `defineSchema`. The error lists the known tables — usually it's a typo, or the client and worker are importing different copies of the app definition. There must be exactly one `defineApp` value shared by both bundles.
48
+
49
+ ## Duplicate clients under Vite HMR / React Fast Refresh
50
+
51
+ A module-scope `createWorkspace(...)` (or `new SyncClient(...)`) is safe as long as the module it lives in triggers a full reload on change. The moment it's exported from a file Fast Refresh *accepts* — a component file, usually — a hot update re-evaluates the module and constructs a **second live client** sharing the first one's sessionStorage clientId: two sockets, duplicate collections, confusing double traffic. Dev-only, but it looks exactly like a sync bug.
52
+
53
+ Two fixes: keep the workspace in its own module that no component file re-exports (the demo's `sync.ts` pattern), or register a dispose hook so the old client is torn down before the module re-evaluates:
54
+
55
+ ```ts
56
+ export const ws = createWorkspace({ url, workspaceId, app, persist: true })
57
+ if (import.meta.hot) {
58
+ import.meta.hot.dispose(() => void ws.destroy())
59
+ }
60
+ ```
61
+
62
+ ## Two tabs, one user — two presence avatars
63
+
64
+ Peers are per connection by design. Group by `principal` (server-attested) for one-avatar-per-user — see [Presence](/guide/presence).
65
+
66
+ ## Still stuck?
67
+
68
+ [Open an issue](https://github.com/InfinityBowman/cf-sync/issues) — include the full error text; the messages are written to be quoted.
@@ -0,0 +1,54 @@
1
+ # Why cf-sync
2
+
3
+ cf-sync is a server-authoritative sync engine for building collaborative, offline-capable apps on Cloudflare. It gives you the Linear-style experience — instant optimistic mutations, real-time propagation, reconnect-and-converge — as a library, on infrastructure you already run: Workers, Durable Objects, and DO SQLite. Nothing else.
4
+
5
+ ## The model in one paragraph
6
+
7
+ Each **workspace** (a team, a project, a document space — your call) is one Durable Object. The DO's SQLite is the system of record; the server is the *only* writer of canonical state. Clients hold an optimistic cache in TanStack DB, apply named **intent mutations** locally for instant feedback, and push them over a hibernating WebSocket. The DO re-runs each mutator authoritatively, stamps changes with a monotonic version, and broadcasts a data-carrying poke to every connected client. Clients apply the patch as new base state and drop or rebase their optimistic overlay. Convergence is guaranteed by construction — the server's answer always wins.
8
+
9
+ ## What you get for that trade
10
+
11
+ **No conflict-resolution puzzles in app code.** Mutations are intents (`issue.move`), not field writes. The server enforces invariants once, in one place, with full authority. You never write merge functions for row data.
12
+
13
+ **One system of record.** No dual writes to a database *and* a sync layer, no cache-invalidation choreography. DO SQLite has point-in-time recovery; the mutation log streams to R2 for archive and analytics.
14
+
15
+ **Offline as a property, not a feature.** The idempotency contract (per-client `lastMutationId`) means a mutation queued offline replays exactly once, even across reloads. The client persists its mirror and outbox in IndexedDB.
16
+
17
+ **Schema evolution with teeth.** Every schema change requires a version bump with an explicit migration entry — and the engine *detects* drift (a structural fingerprint per workspace) instead of letting old and new bundles silently corrupt each other's rows.
18
+
19
+ ## Honest non-goals
20
+
21
+ These are design decisions, not roadmap gaps. If you need one of them, cf-sync is the wrong tool — better to know now:
22
+
23
+ - **Partial sync / row-level read permissions.** A workspace syncs whole to any member. Size workspaces accordingly (Linear's model: fine for teams, wrong for a global feed).
24
+ - **Peer-to-peer or local-first-purist architectures.** The server is authoritative by design. If you want CRDTs all the way down with no authority, look at Jazz or plain Yjs.
25
+ - **Cross-workspace transactions.** Moving data between workspaces is an application-level saga.
26
+ - **Portability.** cf-sync is Cloudflare-native on purpose. There is no Postgres adapter and there won't be.
27
+
28
+ ## How it compares
29
+
30
+ The sync space is crowded, and most of these tools are excellent. cf-sync exists in a specific gap: *server-authoritative semantics, on Cloudflare primitives, with no separate backend to operate*. Its design borrows deliberately from prior art — the [architecture document](https://github.com/InfinityBowman/cf-sync/blob/main/ARCHITECTURE.md) cites Replicache, Zero, LiveStore, tldraw sync, and partyserver at file:line granularity.
31
+
32
+ | | Authority model | Backend you operate | Client store |
33
+ |---|---|---|---|
34
+ | **cf-sync** | Server-authoritative mutators | None beyond your Worker (DO SQLite is the record) | TanStack DB |
35
+ | **Replicache / Zero** | Server-authoritative | Your own push/pull endpoints + Postgres (Zero: plus zero-cache) | Replicache KV / Zero queries |
36
+ | **LiveStore** | Event-sourcing, client-side materialization | CF sync backend or others | Client SQLite |
37
+ | **ElectricSQL** | Postgres-authoritative (read-path sync) | Postgres + Electric service | Shapes into your store |
38
+ | **PartyKit / partyserver** | None — a room/socket toolkit | Your DO code | BYO |
39
+ | **Yjs ecosystems** | CRDT merge, no authority | A relay/persistence provider | Y.Doc |
40
+
41
+ Points of difference worth calling out:
42
+
43
+ - **vs. Replicache/Zero** — same protocol lineage (push / pull / poke, the `lastMutationId` contract), but you don't build the backend: the Durable Object *is* the backend, and the per-DO monotonic version eliminates the timestamp races Replicache's docs warn about. If you're on Postgres and want query-driven partial sync, Zero is the stronger fit.
44
+ - **vs. LiveStore** — LiveStore is event-sourcing with client-side materialization; cf-sync keeps materialized state on the server and syncs rows. cf-sync's transport learned from LiveStore's CF backend (chunking under the 1MB hibernation limit, `backendId` reset detection).
45
+ - **vs. PartyKit** — PartyKit gives you rooms and sockets; the sync semantics (idempotency, cursors, rebase, migrations) are yours to build. cf-sync is those semantics, prebuilt.
46
+ - **vs. pure Yjs** — CRDTs merge everything and enforce nothing. cf-sync keeps rows last-write-wins with server-enforced invariants, and offers [Yjs per field](/guide/collaborative-text) where character-level merging genuinely pays for itself — inside the same Durable Object, same socket, same export surface.
47
+
48
+ ## Where the trust comes from
49
+
50
+ - Invariants are written down and tested: a mutation's data effects and the client's `lastMutationId` advance commit in the same SQLite transaction; permanent app errors still advance it; DO handlers never `await` between reading state and sending frames.
51
+ - A seeded multi-client convergence simulation runs in CI against real workerd.
52
+ - [`createTestEngine`](/guide/testing) runs the same engine code in plain node, so *your* mutators and migrations are as testable as the engine itself.
53
+
54
+ Sold, or at least curious? [Get started](/guide/getting-started).
package/docs/index.md ADDED
@@ -0,0 +1,38 @@
1
+ ---
2
+ layout: home
3
+
4
+ hero:
5
+ name: cf-sync
6
+ text: Sync engine for Cloudflare Durable Objects
7
+ tagline: Server-authoritative, Linear-style sync — optimistic mutations, offline support, presence, and collaborative text, with TanStack DB on the client.
8
+ actions:
9
+ - theme: brand
10
+ text: Get started
11
+ link: /guide/getting-started
12
+ - theme: alt
13
+ text: Why cf-sync?
14
+ link: /guide/why
15
+ - theme: alt
16
+ text: GitHub
17
+ link: https://github.com/InfinityBowman/cf-sync
18
+
19
+ features:
20
+ - icon: 🏛️
21
+ title: Server-authoritative
22
+ details: The Durable Object is the only writer of canonical state. Clients are optimistic caches that always converge — no conflict-resolution puzzles in app code.
23
+ - icon: ⚡
24
+ title: Optimistic out of the box
25
+ details: Define a mutator once; it runs instantly on the client and authoritatively on the server. Rollback, rebase, and replay are the engine's job, not yours.
26
+ - icon: 📴
27
+ title: Offline that survives reloads
28
+ details: An IndexedDB mirror hydrates the UI instantly, and a durable outbox replays offline mutations exactly once when connectivity returns.
29
+ - icon: 🧩
30
+ title: One shared definition
31
+ details: defineApp bundles schema, mutators, presence shape, and the migration chain into one object both bundles import — server and client can't disagree.
32
+ - icon: 👥
33
+ title: Presence & collaborative text
34
+ details: Typed ephemeral presence with built-in throttling, and an optional Yjs add-on for character-level merging on the fields that need it.
35
+ - icon: ☁️
36
+ title: Cloudflare-native
37
+ details: Workers + Durable Objects + DO SQLite only. One DO per workspace, hibernating WebSockets, R2 archive. No external database tier to operate.
38
+ ---
@@ -0,0 +1,105 @@
1
+ # Collections
2
+
3
+ The TanStack DB collection adapter from `@cf-sync/client`. Collections are the read surface for synced rows — live, queryable, optimistic — and the write surface for [full-row LWW writes](/guide/mutations). Row types, runtime validation, and keys all derive from the table's entry in the shared [app definition](/reference/define-kit#defineapp); synced data flows in through the client's poke pipeline, and local writes flow out as the built-in `sync.put`/`sync.del` mutations.
4
+
5
+ ```ts
6
+ import { SyncClient, createCollections } from '@cf-sync/client'
7
+ import { app } from './schema'
8
+
9
+ const client = new SyncClient({ url, workspaceId, app })
10
+ const { todos, issues } = createCollections(client)
11
+
12
+ todos.insert({ id: crypto.randomUUID(), title: 'ship it' })
13
+ ```
14
+
15
+ ## createWorkspace
16
+
17
+ `(options: SyncClientOptions & { startSync? }) => Workspace`
18
+
19
+ The one-call bootstrap: constructs the [`SyncClient`](/reference/sync-client) and every collection, and returns `{ client, collections, destroy }` — the unit to hold and thread:
20
+
21
+ ```ts
22
+ const ws = createWorkspace({ url: SYNC_URL, workspaceId, app, persist: true })
23
+ ws.collections.todos.insert({ id, title: 'ship it' })
24
+ await ws.client.mutate.todos.clearCompleted()
25
+ ```
26
+
27
+ The unit shape is the point for workspace-per-project apps: switching projects is `await ws.destroy()` then `createWorkspace({ ...same, workspaceId: next })` — nothing to individually rebuild or re-thread. Takes every `SyncClientOptions` field plus `startSync`, forwarded to [`createCollections`](#createcollections). Constructing the pieces separately (below) remains fully supported.
28
+
29
+ ## createCollections
30
+
31
+ `(client: SyncClient, options?: { startSync?: boolean }) => WorkspaceCollections`
32
+
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
+
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.
36
+
37
+ ### startSync
38
+
39
+ `boolean` · default `true`
40
+
41
+ Collections start syncing immediately — unlike `workspaceCollectionOptions`, which keeps TanStack's lazy default. The client receives pokes for every table on the one socket regardless, so eager sync costs no extra network: it only applies already-buffered data, and first render sees rows without waiting for a subscriber. Pass `{ startSync: false }` to defer each collection's pipeline to its first subscriber anyway.
42
+
43
+ ## workspaceCollectionOptions
44
+
45
+ `(config: WorkspaceCollectionConfig) => CollectionConfig`
46
+
47
+ The per-table options creator — pass its result to TanStack DB's `createCollection` when one table needs individual control (a custom `getKey`, per-table `startSync`). The collection's schema, row type, and key function derive from the table's entry in the shared `defineSchema`, so the collection validates rows with the same schema the server enforces.
48
+
49
+ Table hooks register with the client at options creation, not at first subscriber — synced data buffers until TanStack starts the (lazy) sync pipeline, so a collection created up front never triggers a late-registration full resync no matter when it gets its first subscriber.
50
+
51
+ Two misconfigurations fail at setup instead of at runtime: a `table` not present in the client's schema throws immediately, and an app defined with `crud: false` throws because its registry lacks the `sync.put`/`sync.del` mutators collections emit — the alternative would be every insert rejecting with `UnknownMutator` and silently rolling back. `defineApp` [includes the CRUD mutators by default](/guide/defining-your-app#crud-is-included).
52
+
53
+ ### client
54
+
55
+ `SyncClient` · **required**
56
+
57
+ The workspace client the collection syncs through. One collection per table per client.
58
+
59
+ ### table
60
+
61
+ `string` · **required**
62
+
63
+ The server-side table name — a key of the client's schema, autocompleted from the app definition.
64
+
65
+ ### getKey
66
+
67
+ `(row) => string` · default: `row.id`
68
+
69
+ Maps a row to its collection key. Required only when the table's row schema has no string `id` field — with one, the field-level default applies and the option is optional (the conditional type enforces this: omitting `getKey` on an id-less table is a compile error).
70
+
71
+ ### startSync
72
+
73
+ `boolean` · default: TanStack's lazy default
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.
76
+
77
+ ## Writes and the wire
78
+
79
+ Collection writes are the full-row half of the [two write paths](/guide/mutations): `insert` and `update` emit the built-in `sync.put` mutation carrying the complete row, `delete` emits `sync.del` — last-writer-wins per row on the server. Updates are full-row replacement, not field merge: a field absent from the written row is removed, matching the LWW row model.
80
+
81
+ Each write is optimistic — visible immediately, resolved only when the server confirms, at which point TanStack DB drops the optimistic overlay (its store handles rebasing overlays on top of newly synced state). A rejected write rolls back, and since collection writes have no awaiting caller, the rejection surfaces **only** through [`onMutationRejected`](/reference/sync-client#onmutationrejected) — without that hook set, a rejected insert vanishes silently. Multi-row [intent mutations](/guide/mutations) run against collections as one atomic overlay: all of a mutator's writes appear together and roll back together.
82
+
83
+ ## Reading
84
+
85
+ Collections are plain TanStack DB collections — read them with `useLiveQuery` from `@tanstack/react-db`. The full read story — filtering, joins, derived collections, vanilla usage — is in [Reading data](/guide/reading-data).
86
+
87
+ ```tsx
88
+ import { eq, useLiveQuery } from '@tanstack/react-db'
89
+
90
+ const { data: openIssues } = useLiveQuery((q) =>
91
+ q.from({ issue: issues }).where(({ issue }) => eq(issue.status, 'open')),
92
+ )
93
+ ```
94
+
95
+ `@tanstack/react-db` is an optional peer of `@cf-sync/client` — install it alongside, and your package manager will flag a version pair whose pinned `@tanstack/db` disagrees. Query syntax, joins, and non-React usage are TanStack DB's domain: see the [TanStack DB docs](https://tanstack.com/db/latest). Sync-pipe state (connecting, synced, fatal) comes from [`useSyncStatus`](/reference/sync-client#react-hooks), not from collections.
96
+
97
+ ## Types
98
+
99
+ ### WorkspaceCollectionConfig
100
+
101
+ The `workspaceCollectionOptions` argument: `{ client, table, getKey?, startSync? }`, with `getKey` required when the row schema lacks a string `id` (see [getKey](#getkey)).
102
+
103
+ ### WorkspaceCollections
104
+
105
+ What `createCollections` returns: a record with one live TanStack DB `Collection` per table name, each carrying the table's row type and schema — `collections.issues` is a compile error if the schema has no `issues` table.