@cf-sync/client 0.1.0 → 0.2.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/README.md CHANGED
@@ -27,6 +27,8 @@ Mutations are optimistic out of the box: the shared mutator runs locally as one
27
27
 
28
28
  React hooks ship at `@cf-sync/client/react`: `useSyncStatus` and `usePresence`. Read collections with `useLiveQuery` from `@tanstack/react-db` (both React and `@tanstack/react-db` are optional peers).
29
29
 
30
- **Docs:** [Getting started](https://github.com/InfinityBowman/cf-sync/blob/main/docs/guide/getting-started.md) · [Mutations](https://github.com/InfinityBowman/cf-sync/blob/main/docs/guide/mutations.md) · [Offline & persistence](https://github.com/InfinityBowman/cf-sync/blob/main/docs/guide/offline-persistence.md) · [Presence](https://github.com/InfinityBowman/cf-sync/blob/main/docs/guide/presence.md) · [Repository](https://github.com/InfinityBowman/cf-sync)
30
+ **Docs:** the full guide and API reference ship inside this package at `node_modules/@cf-sync/client/docs`, version-matched to what you installed — `docs/config.json` indexes every page.
31
+
32
+ Online: [Getting started](https://github.com/InfinityBowman/cf-sync/blob/main/docs/guide/getting-started.md) · [Mutations](https://github.com/InfinityBowman/cf-sync/blob/main/docs/guide/mutations.md) · [Offline & persistence](https://github.com/InfinityBowman/cf-sync/blob/main/docs/guide/offline-persistence.md) · [Presence](https://github.com/InfinityBowman/cf-sync/blob/main/docs/guide/presence.md) · [Repository](https://github.com/InfinityBowman/cf-sync)
31
33
 
32
34
  MIT
@@ -612,6 +612,18 @@ declare class SyncClient<S extends AnySyncSchema = AnySyncSchema, M extends AnyM
612
612
  get whenHydrated(): Promise<boolean>;
613
613
  /** The last server cursor this client applied, or null before the first sync. */
614
614
  get cursor(): Cursor | null;
615
+ /**
616
+ * The number of mutations applied locally but not yet confirmed durable by
617
+ * the server — entries queued before the connection synced and pushed ones
618
+ * awaiting confirmation both count, as do entries restored from the store
619
+ * on startup. 0 means everything this client has issued is on the server.
620
+ *
621
+ * This is the one durability signal that survives a reload: restored
622
+ * entries have no promise to await ({@link mutate} promises do not outlive
623
+ * the client), but they still count here until confirmed. Subscribe to
624
+ * changes via {@link subscribePending}.
625
+ */
626
+ get pending(): number;
615
627
  /** The workspace this client syncs, as passed at construction. */
616
628
  get workspaceId(): string;
617
629
  /** The resolved clientId — the configured one, or the library-managed default. */
@@ -626,6 +638,13 @@ declare class SyncClient<S extends AnySyncSchema = AnySyncSchema, M extends AnyM
626
638
  * React: `useSyncExternalStore(client.subscribeStatus, () => client.status)`.
627
639
  */
628
640
  readonly subscribeStatus: (listener: (status: SyncStatus) => void) => (() => void);
641
+ /**
642
+ * Subscribes to {@link pending} changes; returns an unsubscribe function.
643
+ * Fires only when the count actually changes. An arrow property, so it
644
+ * plugs straight into React:
645
+ * `useSyncExternalStore(client.subscribePending, () => client.pending)`.
646
+ */
647
+ readonly subscribePending: (listener: (pending: number) => void) => (() => void);
629
648
  /**
630
649
  * Subscribes to {@link hydrated} changes; returns an unsubscribe function.
631
650
  * Fires at most once per client — hydration settles one way and stays
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { S as SyncFatalError, _ as Mutate, a as SyncLogger, b as MutationErrorCode, c as TableHooks, d as MemorySyncStore, f as PersistedOutboxEntry, g as SyncStore, h as PokePersist, i as SyncClientOptions, l as TableWriteOp, m as PersistedState, n as IntentTransactionRunner, o as SyncStatus, p as PersistedRowOp, r as PresenceApi, s as TableApplier, t as SyncClient, u as WebSocketLike, v as MutateNamespace, x as SyncFatalCode, y as MutationError } from "./client-tvsT_ixa.js";
1
+ import { S as SyncFatalError, _ as Mutate, a as SyncLogger, b as MutationErrorCode, c as TableHooks, d as MemorySyncStore, f as PersistedOutboxEntry, g as SyncStore, h as PokePersist, i as SyncClientOptions, l as TableWriteOp, m as PersistedState, n as IntentTransactionRunner, o as SyncStatus, p as PersistedRowOp, r as PresenceApi, s as TableApplier, t as SyncClient, u as WebSocketLike, v as MutateNamespace, x as SyncFatalCode, y as MutationError } from "./client-C488ro1Y.js";
2
2
  import { AnyMutators, AnyMutators as AnyMutators$1, AnySyncSchema, AnySyncSchema as AnySyncSchema$1, AppDefinition, AppError, AuthContextOf, CLOSE_AUTH_CONTEXT_INVALID, CLOSE_PERMANENT_MAX, CLOSE_PERMANENT_MIN, CLOSE_REFRESH, CLOSE_SUPERSEDED, CLOSE_UNAUTHORIZED, CLOSE_VERSION_NOT_SUPPORTED, CrudDelArgs, CrudMutators, CrudPutArgs, EngineErrorCode, MutationArgs, MutatorContext, MutatorDef, MutatorTx, MutatorsFor, PresenceOf, PresencePeer, RowInputOf, RowInputOf as RowInputOf$1, RowOf, RowOf as RowOf$1, SchemaMigration, SchemaMigrationFn, StandardSchemaV1, StandardSchemaV1 as StandardSchemaV1$1, SyncSchema, TableName, TableName as TableName$1, TableSchema, crudMutators, defineApp, defineMutators, defineSchema, isPermanentCloseCode } from "@cf-sync/protocol";
3
3
  import { Collection, CollectionConfig } from "@tanstack/db";
4
4
  //#region src/collection.d.ts
package/dist/index.js CHANGED
@@ -475,6 +475,7 @@ var SyncClient = class {
475
475
  #warnedTables = /* @__PURE__ */ new Set();
476
476
  #warnedNoApplier = /* @__PURE__ */ new Set();
477
477
  #statusListeners = /* @__PURE__ */ new Set();
478
+ #pendingListeners = /* @__PURE__ */ new Set();
478
479
  #binaryListeners = /* @__PURE__ */ new Set();
479
480
  #rejectionListeners = /* @__PURE__ */ new Set();
480
481
  #log(level, message, ...detail) {
@@ -497,6 +498,7 @@ var SyncClient = class {
497
498
  #cursor = null;
498
499
  #confirmedLmid = 0;
499
500
  #outbox = [];
501
+ #notifiedPending = 0;
500
502
  #poke = null;
501
503
  #syncedThisConnection = false;
502
504
  #awaitingCatchUp = false;
@@ -659,6 +661,20 @@ var SyncClient = class {
659
661
  get cursor() {
660
662
  return this.#cursor;
661
663
  }
664
+ /**
665
+ * The number of mutations applied locally but not yet confirmed durable by
666
+ * the server — entries queued before the connection synced and pushed ones
667
+ * awaiting confirmation both count, as do entries restored from the store
668
+ * on startup. 0 means everything this client has issued is on the server.
669
+ *
670
+ * This is the one durability signal that survives a reload: restored
671
+ * entries have no promise to await ({@link mutate} promises do not outlive
672
+ * the client), but they still count here until confirmed. Subscribe to
673
+ * changes via {@link subscribePending}.
674
+ */
675
+ get pending() {
676
+ return this.#outbox.length;
677
+ }
662
678
  /** The workspace this client syncs, as passed at construction. */
663
679
  get workspaceId() {
664
680
  return this.#opts.workspaceId;
@@ -687,6 +703,18 @@ var SyncClient = class {
687
703
  };
688
704
  };
689
705
  /**
706
+ * Subscribes to {@link pending} changes; returns an unsubscribe function.
707
+ * Fires only when the count actually changes. An arrow property, so it
708
+ * plugs straight into React:
709
+ * `useSyncExternalStore(client.subscribePending, () => client.pending)`.
710
+ */
711
+ subscribePending = (listener) => {
712
+ this.#pendingListeners.add(listener);
713
+ return () => {
714
+ this.#pendingListeners.delete(listener);
715
+ };
716
+ };
717
+ /**
690
718
  * Subscribes to {@link hydrated} changes; returns an unsubscribe function.
691
719
  * Fires at most once per client — hydration settles one way and stays
692
720
  * settled. An arrow property, so it plugs straight into React:
@@ -926,6 +954,7 @@ var SyncClient = class {
926
954
  settled: false
927
955
  }));
928
956
  this.#outbox = [...restored, ...this.#outbox];
957
+ this.#notifyPending();
929
958
  if (state.cursor !== null) {
930
959
  const byTable = /* @__PURE__ */ new Map();
931
960
  for (const row of state.rows) {
@@ -1171,6 +1200,7 @@ var SyncClient = class {
1171
1200
  }, timeoutMs);
1172
1201
  }
1173
1202
  this.#outbox.push(entry);
1203
+ this.#notifyPending();
1174
1204
  if (this.#syncedThisConnection) {
1175
1205
  entry.id = this.#nextMutationId();
1176
1206
  this.#schedulePush();
@@ -1567,8 +1597,20 @@ var SyncClient = class {
1567
1597
  else entry.resolve();
1568
1598
  }
1569
1599
  this.#outbox = this.#outbox.filter((e) => e !== entry);
1600
+ this.#notifyPending();
1570
1601
  this.#persistOutbox();
1571
1602
  }
1603
+ /**
1604
+ * Every outbox removal funnels through #settleEntry (the confirm sweep,
1605
+ * shutdown, and fatal all settle entry by entry), so notifying there plus
1606
+ * the two growth sites (mutate's push, hydration's prepend) is exhaustive.
1607
+ */
1608
+ #notifyPending() {
1609
+ const pending = this.#outbox.length;
1610
+ if (pending === this.#notifiedPending) return;
1611
+ this.#notifiedPending = pending;
1612
+ for (const listener of this.#pendingListeners) listener(pending);
1613
+ }
1572
1614
  #schedulePush() {
1573
1615
  if (this.#flushScheduled) return;
1574
1616
  this.#flushScheduled = true;
package/dist/react.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { o as SyncStatus, r as PresenceApi, t as SyncClient } from "./client-tvsT_ixa.js";
1
+ import { o as SyncStatus, r as PresenceApi, t as SyncClient } from "./client-C488ro1Y.js";
2
2
  import { PresencePeer } from "@cf-sync/protocol";
3
3
  //#region src/react.d.ts
4
4
  /**
@@ -0,0 +1,75 @@
1
+ {
2
+ "title": "cf-sync",
3
+ "description": "Server-authoritative sync engine on Cloudflare Durable Objects, with TanStack DB on the client",
4
+ "repository": "InfinityBowman/cf-sync",
5
+ "branch": "main",
6
+ "sections": [
7
+ {
8
+ "label": "Introduction",
9
+ "area": "guide",
10
+ "children": [
11
+ { "label": "Why cf-sync", "to": "guide/why" },
12
+ { "label": "Getting started", "to": "guide/getting-started" }
13
+ ]
14
+ },
15
+ {
16
+ "label": "Core concepts",
17
+ "area": "guide",
18
+ "children": [
19
+ { "label": "Defining your app", "to": "guide/defining-your-app" },
20
+ { "label": "Mutations & optimistic writes", "to": "guide/mutations" },
21
+ { "label": "Schema evolution", "to": "guide/schema-evolution" },
22
+ { "label": "Auth & sessions", "to": "guide/auth" }
23
+ ]
24
+ },
25
+ {
26
+ "label": "Collaboration",
27
+ "area": "guide",
28
+ "children": [
29
+ { "label": "Presence", "to": "guide/presence" },
30
+ { "label": "Collaborative text", "to": "guide/collaborative-text" }
31
+ ]
32
+ },
33
+ {
34
+ "label": "Client",
35
+ "area": "guide",
36
+ "children": [
37
+ { "label": "Reading data", "to": "guide/reading-data" },
38
+ { "label": "Offline & persistence", "to": "guide/offline-persistence" }
39
+ ]
40
+ },
41
+ {
42
+ "label": "Production",
43
+ "area": "guide",
44
+ "children": [
45
+ { "label": "Testing your app", "to": "guide/testing" },
46
+ { "label": "Operations", "to": "guide/operations" },
47
+ { "label": "Limits & costs", "to": "guide/limits-and-costs" },
48
+ { "label": "Troubleshooting", "to": "guide/troubleshooting" }
49
+ ]
50
+ },
51
+ {
52
+ "label": "Internals",
53
+ "area": "guide",
54
+ "children": [
55
+ {
56
+ "label": "Architecture",
57
+ "href": "https://github.com/InfinityBowman/cf-sync/blob/main/ARCHITECTURE.md"
58
+ }
59
+ ]
60
+ },
61
+ {
62
+ "label": "API reference",
63
+ "area": "reference",
64
+ "children": [
65
+ { "label": "Overview", "to": "reference/index" },
66
+ { "label": "SyncClient", "to": "reference/sync-client" },
67
+ { "label": "Collections", "to": "reference/collections" },
68
+ { "label": "defineApp & the definition kit", "to": "reference/define-kit" },
69
+ { "label": "Server", "to": "reference/server" },
70
+ { "label": "Test engine", "to": "reference/testing" },
71
+ { "label": "Yjs fields", "to": "reference/yjs" }
72
+ ]
73
+ }
74
+ ]
75
+ }
@@ -0,0 +1,135 @@
1
+ # Auth & sessions
2
+
3
+ cf-sync deliberately owns no identity. Your users, roles, and entitlements live in your own authority (your app database, your auth provider); the engine gives that data a **lifecycle on the connection**: a way to stamp it, carry it to mutators, revoke it, and refresh it.
4
+
5
+ ## The `authorize` hook
6
+
7
+ Every socket upgrade passes through `authorize` in the worker — before the Durable Object ever wakes:
8
+
9
+ ```ts
10
+ createSyncFetch<Env>({
11
+ namespace: (env) => env.WORKSPACE,
12
+ authorize: async (request, { workspaceId, clientId, env }) => {
13
+ const session = await verifyAuth(request, env)
14
+ if (!session) return { ok: false, reason: 'unauthenticated' }
15
+
16
+ const member = await getMember(env.DB, workspaceId, session.userId)
17
+ if (!member) return { ok: false, reason: 'not-a-member' }
18
+
19
+ return {
20
+ ok: true,
21
+ principal: session.userId,
22
+ context: { role: member.role, writeAllowed: member.entitled },
23
+ }
24
+ },
25
+ })
26
+ ```
27
+
28
+ `authorize` is required — an unauthenticated deployment must be a written-down choice, not a forgotten option. Pass the literal `'public'` to opt out explicitly (anyone who can reach the worker can read and write every workspace — fine for a demo or first run). The hook form may return:
29
+
30
+ - `true` / `false` — admit or reject (a bare `false` answers HTTP 403)
31
+ - a `Response` — full control over the rejection
32
+ - an **`AuthVerdict`** — `{ ok: true, principal?, context?, expiresAt? }` or `{ ok: false, code?, reason? }`
33
+
34
+ The verdict's `principal` and `context` are stamped onto the connection, survive DO hibernation, and cannot be spoofed from outside (the internal header that carries them is stripped from inbound requests).
35
+
36
+ ::: tip Rejections are observable in the browser
37
+ A browser can't see the HTTP status of a failed WebSocket upgrade — a 403 looks identical to a network error. So on a structured rejection, the router completes the upgrade and immediately closes with a code and your `reason` slug. The client gets a real close event, your `onFatal` gets the reason, and the DO never wakes. Keep reasons short stable slugs (`membership-revoked`, not prose) — WebSocket close reasons cap at 123 bytes.
38
+ :::
39
+
40
+ ## Sending a credential
41
+
42
+ Cookie-based sessions need nothing: the browser attaches cookies to the upgrade request and `verifyAuth(request, env)` above reads them. Token-based auth uses the client's `authToken` option — browsers can't set headers on a WebSocket upgrade, so the token rides the sync URL as a `token` query parameter:
43
+
44
+ ```ts
45
+ const client = new SyncClient({
46
+ url: SYNC_URL,
47
+ workspaceId,
48
+ app,
49
+ authToken: () => getSession().accessToken,
50
+ })
51
+ ```
52
+
53
+ ```ts
54
+ // worker — the authorize hook reads it back off the URL
55
+ authorize: async (request, { workspaceId, env }) => {
56
+ const token = new URL(request.url).searchParams.get('token')
57
+ const session = token && (await verifyToken(token, env))
58
+ if (!session) return { ok: false, reason: 'unauthenticated' }
59
+ // …membership checks as above
60
+ }
61
+ ```
62
+
63
+ A function is invoked fresh on **every** connection attempt — including the immediate reconnect after a [refresh close](#close-codes) — so short-lived tokens renew without any bookkeeping: revoke entitlements, `disconnect({ mode: 'refresh' })`, and the reconnect carries a new token through a fresh `authorize` run. An async provider is awaited before the socket opens; a rejection counts as a failed attempt and retries with backoff. The router strips `token` from the URL after `authorize` runs, so the credential never reaches the Durable Object or workspace-side logs.
64
+
65
+ Don't confuse this with `authContext`, the client's *local, untransmitted* copy of what `authorize` stamps — that one only feeds optimistic mutator runs (`ctx.auth`), and the server never sees or trusts it.
66
+
67
+ ## Reading the verdict in mutators
68
+
69
+ Type the context once with `authContext`, and every mutator sees it as `ctx.auth`:
70
+
71
+ ```ts
72
+ const mutators = defineMutators(schema, {
73
+ 'issue.delete': {
74
+ args: z.object({ id: z.string() }),
75
+ apply(tx, { id }, ctx) {
76
+ if (ctx.authoritative && !ctx.auth?.writeAllowed)
77
+ throw new AppError('ReadOnly', 'subscription lapsed')
78
+ tx.del('issues', id)
79
+ },
80
+ },
81
+ }, { authContext: z.object({ role: z.enum(['owner', 'member']), writeAllowed: z.boolean() }) })
82
+ ```
83
+
84
+ Two details that keep this honest:
85
+
86
+ - **`ctx.authoritative`** is `true` on the server, `false` in optimistic client runs — where no server verdict exists. `if (ctx.authoritative && !allowed) throw` enforces on the server and lets the optimistic apply proceed; a rejection rolls back through the normal path.
87
+ - **Validation at connect, not mid-mutation**: the DO validates the verdict's `context` against `authContext` at upgrade. If your `authorize` hook and your mutators ship disagreeing shapes, the connection fails immediately with a descriptive reason — a configuration bug surfaces at connect time, not as a runtime surprise during someone's mutation.
88
+
89
+ `ctx.principal` (the server-attested user id) and `ctx.clientId` are always available.
90
+
91
+ ## Revoking and refreshing live sessions
92
+
93
+ Membership removal must stop *reads*, not just writes — so revocation closes sockets. From a command handler or webhook:
94
+
95
+ ```ts
96
+ import { workspaceAdmin } from '@cf-sync/server'
97
+
98
+ const ws = workspaceAdmin(env.WORKSPACE, workspaceId)
99
+
100
+ // membership revoked → close their sockets, client goes fatal with the reason
101
+ await ws.disconnect({ principal: userId, mode: 'kick', reason: 'membership-revoked' })
102
+
103
+ // entitlements changed → everyone reconnects and re-runs authorize with fresh stamps
104
+ await ws.disconnect({ mode: 'refresh' })
105
+ ```
106
+
107
+ Selectors: `principal`, `clientId`, or neither (all sockets). The same op is exposed over HTTP as `POST /admin/<workspaceId>/disconnect` — see [Operations](/guide/operations).
108
+
109
+ ### Stamps with an expiry
110
+
111
+ Push-driven revocation depends on the webhook arriving. If you want a bound on how long stamps stay trusted without being re-derived, return `expiresAt` (epoch ms) in the verdict — past-due sockets are closed with the *refresh* code at the next interaction, and the reconnect re-runs `authorize`. Omitted means no expiry: apps with reliable revocation webhooks don't pay for one.
112
+
113
+ ## Close codes {#close-codes}
114
+
115
+ The client sorts server-initiated closes into two behaviors:
116
+
117
+ - **Refresh (4300)** — reconnect immediately with a fresh `authorize` run. Not an error; this is the entitlement-freshness mechanism working. (Loop guard: consecutive refreshes without a successful sync fall back to normal backoff, so a stuck webhook can't storm your auth database.)
118
+ - **Permanent (4400–4499)** — stop reconnecting and call `onFatal` with `{ code, reason }`. This is `VersionNotSupported` after a deploy, a kick, or an auth-context validation failure.
119
+
120
+ ```ts
121
+ new SyncClient({
122
+ url, workspaceId, app, persist: true,
123
+ onFatal: (err) => {
124
+ if (err.reason === 'membership-revoked') return leaveWorkspace()
125
+ if (err.reason === 'workspace-deleted') return cleanupAndRedirect()
126
+ location.reload() // default behavior, throttled to once per minute
127
+ },
128
+ })
129
+ ```
130
+
131
+ Without `onFatal`, the default is a page reload throttled to once per minute — so a bad deploy window degrades to a paced retry, not a reload loop.
132
+
133
+ ## One place evaluates auth
134
+
135
+ All auth evaluation happens in `authorize`, in the worker, against your database. The DO never re-derives it — refresh is a socket bounce, and the cursor catch-up path makes reconnects cheap. One place to audit, one place to get right.
@@ -0,0 +1,83 @@
1
+ # Collaborative text
2
+
3
+ Row sync is last-write-wins on purpose — character-level merging never flows through the mutation log. But some fields genuinely need it: two people typing in the same notes box should merge, not clobber. For those fields, the `@cf-sync/yjs` add-on gives you **Yjs documents that live in the same Workspace Durable Object** as your rows.
4
+
5
+ Same storage authority, same socket, same export/import surface. `yjs` is a peer dependency of the add-on; the cf-sync core stays yjs-free — apps that don't need collaborative text never ship a CRDT.
6
+
7
+ ## When to reach for this
8
+
9
+ Use a Yjs field when concurrent *in-field* editing is an expected workflow (notes, descriptions, documents). Don't use it for titles, statuses, or anything a form submits atomically — LWW rows with intent mutators are simpler, cheaper, and easier to reason about. The demo's rule of thumb: rows by default, a field only where merging has proven necessary.
10
+
11
+ ## Server: register the extension
12
+
13
+ ```ts
14
+ import { createWorkspaceDO } from '@cf-sync/server'
15
+ import { yjsFields } from '@cf-sync/yjs/server'
16
+
17
+ export class WorkspaceDO extends createWorkspaceDO({
18
+ app,
19
+ extension: yjsFields(),
20
+ }) {}
21
+ ```
22
+
23
+ Field updates travel on a binary lane over the existing sync socket and persist in the DO's SQLite alongside your rows.
24
+
25
+ ## Client: field handles
26
+
27
+ ```ts
28
+ import { createYjsFields } from '@cf-sync/yjs/client'
29
+
30
+ const fields = createYjsFields(client)
31
+
32
+ const handle = fields.getDoc(`todo-notes:${todoId}`)
33
+ await handle.whenSynced // resolves once the server state has landed
34
+ handle.text // a Y.Text — bind it to your editor
35
+ handle.doc // the underlying Y.Doc, for richer bindings
36
+ handle.canWrite // reactive — readers render read-only from first paint
37
+ handle.release() // handles are ref-counted; release on unmount
38
+ ```
39
+
40
+ `handle.text` plugs directly into the Yjs editor ecosystem — y-codemirror, y-prosemirror, or a minimal textarea binding like the demo's [`NotesField.tsx`](https://github.com/InfinityBowman/cf-sync/blob/main/apps/demo/src/NotesField.tsx). Offline edits merge on resume instead of overwriting — that's the CRDT earning its keep.
41
+
42
+ ## React: `useYjsField`
43
+
44
+ In React, skip the manual lifecycle entirely — `@cf-sync/yjs/react` owns acquire, release, re-acquire on field change, the sync gate, and reactive `canWrite`:
45
+
46
+ ```tsx
47
+ import { useYjsField } from '@cf-sync/yjs/react'
48
+
49
+ function Notes({ todoId }: { todoId: string }) {
50
+ const field = useYjsField(fields, `todo-notes:${todoId}`)
51
+ if (!field.synced) return <Spinner />
52
+ return <Editor text={field.text} readOnly={!field.canWrite} />
53
+ }
54
+ ```
55
+
56
+ The result is discriminated on `synced`, so TypeScript makes the loading state impossible to forget: `doc`, `text`, and `handle` are only non-null once the field is renderable. The hook re-renders on sync and permission changes — **not** per keystroke; content binding belongs to the editor attached to `field.text`, exactly as everywhere else in the Yjs ecosystem. StrictMode's double mount and SSR (renders as not-yet-synced, matching the client's first paint) are both handled.
57
+
58
+ ## Field ids are your convention
59
+
60
+ The engine never interprets field ids. `todo-notes:<todoId>` is an app convention linking a field to a row — which also means **deleting a row does not delete its field** (the engine can't see your pointer convention). An app that wants orphaned fields collected deletes them through the same [admin surface](/guide/operations) that exports and imports them.
61
+
62
+ ## Write access
63
+
64
+ Write access defaults to "any workspace member". To gate per field, stamp what you need in the sync router's [`authorize` hook](/guide/auth) and give the extension an `authorizeWrite` predicate over `{ fieldId, auth, principal, clientId }`. Pass `app` alongside and `auth` is typed from the `authContext` schema the app already declared in `defineMutators` — no hand-written generic to keep in sync:
65
+
66
+ ```ts
67
+ yjsFields({
68
+ app,
69
+ authorizeWrite: ({ fieldId, auth }) => auth?.role !== 'viewer',
70
+ })
71
+ ```
72
+
73
+ (Without an app value in scope, the explicit generic still works: `yjsFields<MyAuthContext>({ … })`.)
74
+
75
+ Readers aren't second-class: the sync state carries the writable flag, so `handle.canWrite` is correct from first paint — no flash of editable UI before a rejection. And when a field *is* read-only, `handle.writeBlocked` (also on `useYjsField`'s state) says why — `'NotWritable'`/`'Frozen'` (access) vs `'TooLarge'`/`'LocalTooLarge'` (the document is full) — so the banner can tell the user something actionable.
76
+
77
+ ## Presence for fields
78
+
79
+ "X is editing this field" is ordinary [presence](/guide/presence) — put a `focusedField` in your presence schema and render it next to the field. The demo wires this end to end.
80
+
81
+ ## Operations
82
+
83
+ The [admin surface](/guide/operations) is fields-aware: `stats` includes the extension's gauges (field count, frozen fields, pending updates, cached docs), and `export`/`import` round-trip fields alongside rows. An import carrying fields cycles live sockets so both planes rebuild consistently.
@@ -0,0 +1,117 @@
1
+ # Defining your app
2
+
3
+ Everything cf-sync knows about your application comes from one object, built with `defineApp` and imported by **both** the worker and the browser bundle:
4
+
5
+ ```ts
6
+ import { defineApp, defineSchema, defineMutators, AppError } from '@cf-sync/protocol'
7
+ import { z } from 'zod'
8
+
9
+ export const app = defineApp({ version: 1, schema, mutators })
10
+ ```
11
+
12
+ That one value drives server-side row and args validation, collection row types, typed `mutate` calls, presence typing, and the schema-version rollout. Because both sides are configured with the same value, they cannot disagree.
13
+
14
+ ## The schema
15
+
16
+ `defineSchema` takes a zod object schema per table:
17
+
18
+ ```ts
19
+ const schema = defineSchema({
20
+ issues: z.object({
21
+ id: z.string(),
22
+ title: z.string(),
23
+ column: z.string().default('backlog'),
24
+ }),
25
+ })
26
+ ```
27
+
28
+ The server validates **every row write** against the table's schema before it commits — a client can never write a shape the schema doesn't allow, no matter what it sends. Defaults apply on insert (`column` above is filled in for you). Row types for collections and `tx.get`/`tx.put` all derive from here.
29
+
30
+ ## Mutators
31
+
32
+ Mutations are **named intents**, not field writes. `issue.move`, not "set column to X" — intent survives rebase against concurrent changes, and gives the server one place to enforce invariants.
33
+
34
+ ```ts
35
+ const mutators = defineMutators(schema, {
36
+ 'issue.move': {
37
+ args: z.object({ id: z.string(), column: z.string() }),
38
+ apply: (tx, { id, column }) => { // args are validated and typed
39
+ const issue = tx.get('issues', id) // typed: { id, title, column } | null
40
+ if (!issue) throw new AppError('NotFound', `issue ${id} does not exist`)
41
+ tx.put('issues', id, { ...issue, column })
42
+ },
43
+ },
44
+ })
45
+ ```
46
+
47
+ The server validates `args` against the schema before `apply` runs. Inside `apply`, `tx` gives you `get`, `put`, `del`, and `list` over the workspace's tables — every write validated, all of them committed atomically with the mutation's bookkeeping.
48
+
49
+ The definitions can also be written directly inside `defineApp({ mutators: { ... } })` — inference is identical either way. `defineMutators` is only *required* when declaring an [`authContext`](/guide/auth#reading-the-verdict-in-mutators), its third argument.
50
+
51
+ ### CRUD is included
52
+
53
+ The full-row last-write-wins pair (`sync.put` / `sync.del`) — what collections emit for local `insert`/`update`/`delete` — is added by `defineApp` automatically. Pass `crud: false` for an intent-only app where every write must go through a named mutator.
54
+
55
+ ## The two authoring rules
56
+
57
+ The same `apply` runs twice: **optimistically on the client** the moment you call `mutate`, and **authoritatively on the server** when the push arrives. Two rules keep those runs in agreement:
58
+
59
+ ::: warning Rule 1 — reserve `throw` for genuine invariant violations
60
+ A local throw rejects the call immediately and sends nothing. But local state can legitimately be *behind* the server — so "row not synced yet" must not be an error. Throw for things that can never be valid, not for things that aren't visible yet.
61
+ :::
62
+
63
+ ::: warning Rule 2 — pass nondeterministic values in as args
64
+ Ids, timestamps, random values: compute them at the call site and pass them as args, never inside `apply`. Otherwise the client's optimistic prediction and the server's authoritative run produce different results, and the UI flickers on confirm.
65
+ :::
66
+
67
+ ```ts
68
+ // ✅ deterministic — both runs agree
69
+ await client.mutate.issue.create({ id: ulid(), createdAt: Date.now(), title })
70
+
71
+ // ❌ nondeterministic — server echo won't match the local prediction
72
+ apply: (tx, { title }) => tx.put('issues', ulid(), { id: ulid(), createdAt: Date.now(), title })
73
+ ```
74
+
75
+ ## Errors: `AppError` vs everything else
76
+
77
+ `throw new AppError(code, message)` is a **permanent** rejection: the server refuses the mutation, tells the client, and the optimistic effect rolls back. Your `code` string surfaces on the client as [`MutationError.code`](/guide/mutations#rejection-codes), so UIs can branch on it.
78
+
79
+ Any *other* throw is treated as **transient** (a bug, an infrastructure hiccup): nothing commits, and the mutation may be retried. Don't use plain `Error` for business rules — use `AppError` so the outcome is deterministic.
80
+
81
+ Permanent errors still advance the client's mutation bookkeeping (that's an engine invariant) — a permanently-rejected mutation is *done*, never retried, never blocking the queue behind it.
82
+
83
+ ## Auth context in mutators
84
+
85
+ Mutators receive a context as their third argument — who is calling, and what your `authorize` hook stamped on the connection:
86
+
87
+ ```ts
88
+ const mutators = defineMutators(schema, {
89
+ 'issue.delete': {
90
+ args: z.object({ id: z.string() }),
91
+ apply(tx, { id }, ctx) {
92
+ if (ctx.authoritative && ctx.auth?.role !== 'admin')
93
+ throw new AppError('Forbidden', 'admins only')
94
+ tx.del('issues', id)
95
+ },
96
+ },
97
+ }, { authContext: z.object({ role: z.enum(['admin', 'member']) }) })
98
+ ```
99
+
100
+ `ctx.authoritative` is `true` on the server and `false` in optimistic client runs — the honest signal for permission checks. See [Auth & sessions](/guide/auth) for the full picture.
101
+
102
+ ## Presence shape
103
+
104
+ Declare an ephemeral presence payload on the same object and the whole presence surface lights up typed — see [Presence](/guide/presence):
105
+
106
+ ```ts
107
+ export const app = defineApp({
108
+ version: 1,
109
+ schema,
110
+ mutators,
111
+ presence: z.object({ name: z.string(), cursor: z.object({ x: z.number(), y: z.number() }).optional() }),
112
+ })
113
+ ```
114
+
115
+ ## Versioning
116
+
117
+ `version` starts at 1 and bumps with **every** schema change, paired with a `migrations` entry. This is load-bearing enough to get its own page: [Schema evolution](/guide/schema-evolution).