@cf-sync/client 0.2.0 → 0.3.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.
@@ -78,6 +78,8 @@ interface PersistedOutboxEntry {
78
78
  id: number | null;
79
79
  name: string;
80
80
  args: unknown;
81
+ /** The mutation's seed (`ctx.seed`). Absent only in entries persisted before protocol 2; the client mints one at replay. */
82
+ seed?: string;
81
83
  }
82
84
  /** A put/del row operation in durable form (clear is signaled separately). */
83
85
  type PersistedRowOp = {
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-C488ro1Y.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-Brf5_aXB.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
@@ -1,5 +1,5 @@
1
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";
2
+ import { KEEPALIVE_PING, PROTOCOL_VERSION, compileWhere, createIdSource, cursorEquals, formatIssues, jsonByteSize, mintSeed, serverMsgSchema } from "@cf-sync/protocol/internal";
3
3
  import { createCollection, createTransaction } from "@tanstack/db";
4
4
  //#region src/idb-store.ts
5
5
  const ROWS = "rows";
@@ -324,12 +324,17 @@ var LocalWriteSet = class {
324
324
  const row = applier.get(id);
325
325
  return row ? structuredClone(row) : null;
326
326
  },
327
- list: (tbl) => {
327
+ list: (tbl, opts) => {
328
328
  const applier = this.#applier(tbl);
329
+ const matches = compileWhere(opts?.where);
329
330
  const merged = /* @__PURE__ */ new Map();
330
- for (const { id, data } of applier.list()) merged.set(id, structuredClone(data));
331
+ for (const { id, data } of applier.list()) if (matches(data)) merged.set(id, structuredClone(data));
331
332
  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
+ for (const put of this.#puts.values()) {
334
+ if (put.tbl !== tbl) continue;
335
+ if (matches(put.data)) merged.set(put.id, structuredClone(put.data));
336
+ else merged.delete(put.id);
337
+ }
333
338
  return [...merged].map(([id, data]) => ({
334
339
  id,
335
340
  data
@@ -948,6 +953,7 @@ var SyncClient = class {
948
953
  id: e.id,
949
954
  name: e.name,
950
955
  args: e.args,
956
+ seed: e.seed ?? mintSeed(),
951
957
  resolve: noop,
952
958
  reject: (err) => this.#notifyRejected(err, e.name, e.args),
953
959
  timer: null,
@@ -1007,11 +1013,7 @@ var SyncClient = class {
1007
1013
  }
1008
1014
  const writes = new LocalWriteSet(this.schema, this.#appliers);
1009
1015
  try {
1010
- def.apply(writes.tx, applyArgs, {
1011
- clientId: this.#clientId,
1012
- auth: this.#auth,
1013
- authoritative: false
1014
- });
1016
+ def.apply(writes.tx, applyArgs, this.#localContext(entry.seed));
1015
1017
  } catch (err) {
1016
1018
  if (err instanceof MissingApplierError) this.#warnNoApplier(entry.name, err.tbl);
1017
1019
  else this.#log("warn", `[cf-sync] startup replay of "${entry.name}" threw locally — it stays queued without an optimistic overlay`, err);
@@ -1084,12 +1086,13 @@ var SyncClient = class {
1084
1086
  name,
1085
1087
  args
1086
1088
  }));
1089
+ const seed = mintSeed();
1087
1090
  let applyArgs = args;
1088
1091
  if (def.args) {
1089
1092
  const result = def.args["~standard"].validate(args);
1090
1093
  if (result instanceof Promise) {
1091
1094
  result.catch(() => {});
1092
- return this.#enqueue(name, args);
1095
+ return this.#enqueue(name, args, seed);
1093
1096
  }
1094
1097
  if (result.issues) return Promise.reject(new MutationError("InvalidArgs", `invalid args for "${name}": ${formatIssues(result.issues)}`, {
1095
1098
  name,
@@ -1098,18 +1101,14 @@ var SyncClient = class {
1098
1101
  applyArgs = result.value;
1099
1102
  }
1100
1103
  const runner = this.#intentRunner;
1101
- if (!runner || this.#appliers.size === 0) return this.#enqueue(name, args);
1104
+ if (!runner || this.#appliers.size === 0) return this.#enqueue(name, args, seed);
1102
1105
  const writes = new LocalWriteSet(this.schema, this.#appliers);
1103
1106
  try {
1104
- def.apply(writes.tx, applyArgs, {
1105
- clientId: this.#clientId,
1106
- auth: this.#auth,
1107
- authoritative: false
1108
- });
1107
+ def.apply(writes.tx, applyArgs, this.#localContext(seed));
1109
1108
  } catch (err) {
1110
1109
  if (err instanceof MissingApplierError) {
1111
1110
  this.#warnNoApplier(name, err.tbl);
1112
- return this.#enqueue(name, args);
1111
+ return this.#enqueue(name, args, seed);
1113
1112
  }
1114
1113
  if (err instanceof AppError$1) return Promise.reject(new MutationError(err.code, err.message, {
1115
1114
  name,
@@ -1121,8 +1120,23 @@ var SyncClient = class {
1121
1120
  args
1122
1121
  }));
1123
1122
  }
1124
- if (writes.isEmpty()) return this.#enqueue(name, args);
1125
- return runner(name, () => this.#flushLocalWrites(writes), () => this.#enqueue(name, args));
1123
+ if (writes.isEmpty()) return this.#enqueue(name, args, seed);
1124
+ return runner(name, () => this.#flushLocalWrites(writes), () => this.#enqueue(name, args, seed));
1125
+ }
1126
+ /**
1127
+ * The optimistic run's context: no server verdict exists here — no
1128
+ * principal, and `authoritative: false` is the honest signal permission
1129
+ * checks key on (ARCHITECTURE.md#session-control). The seed is the one the
1130
+ * wire will carry, so `nextId` agrees with the authoritative run.
1131
+ */
1132
+ #localContext(seed) {
1133
+ return {
1134
+ clientId: this.#clientId,
1135
+ auth: this.#auth,
1136
+ authoritative: false,
1137
+ seed,
1138
+ nextId: createIdSource(seed)
1139
+ };
1126
1140
  }
1127
1141
  /**
1128
1142
  * The adapter's raw path (see `RAW_MUTATE`): validate and enqueue, no
@@ -1150,7 +1164,7 @@ var SyncClient = class {
1150
1164
  args
1151
1165
  }));
1152
1166
  }
1153
- return this.#enqueue(name, args);
1167
+ return this.#enqueue(name, args, mintSeed());
1154
1168
  }
1155
1169
  /** Translates an intent's net writes to collection ops (inside the runner's atomic scope). */
1156
1170
  #flushLocalWrites(writes) {
@@ -1171,7 +1185,7 @@ var SyncClient = class {
1171
1185
  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.`);
1172
1186
  }
1173
1187
  /** Queues a validated mutation; resolves/rejects on server confirm (the LMID contract). */
1174
- #enqueue(name, args) {
1188
+ #enqueue(name, args, seed) {
1175
1189
  if (this.#status === "fatal") return Promise.reject(new MutationError("Fatal", "sync client is in a fatal state", {
1176
1190
  name,
1177
1191
  args
@@ -1185,6 +1199,7 @@ var SyncClient = class {
1185
1199
  id: null,
1186
1200
  name,
1187
1201
  args,
1202
+ seed,
1188
1203
  resolve,
1189
1204
  reject,
1190
1205
  timer: null,
@@ -1623,7 +1638,8 @@ var SyncClient = class {
1623
1638
  return this.#outbox.map((e) => ({
1624
1639
  id: e.id,
1625
1640
  name: e.name,
1626
- args: e.args
1641
+ args: e.args,
1642
+ seed: e.seed
1627
1643
  }));
1628
1644
  }
1629
1645
  /**
@@ -1646,7 +1662,8 @@ var SyncClient = class {
1646
1662
  const mutations = this.#outbox.filter((e) => e.id !== null && e.id > this.#confirmedLmid).sort((a, b) => a.id - b.id).map((e) => ({
1647
1663
  id: e.id,
1648
1664
  name: e.name,
1649
- args: e.args
1665
+ args: e.args,
1666
+ seed: e.seed
1650
1667
  }));
1651
1668
  if (mutations.length > 0) this.#send({
1652
1669
  type: "push",
package/dist/react.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { o as SyncStatus, r as PresenceApi, t as SyncClient } from "./client-C488ro1Y.js";
1
+ import { o as SyncStatus, r as PresenceApi, t as SyncClient } from "./client-Brf5_aXB.js";
2
2
  import { PresencePeer } from "@cf-sync/protocol";
3
3
  //#region src/react.d.ts
4
4
  /**
@@ -46,6 +46,16 @@ const mutators = defineMutators(schema, {
46
46
 
47
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
48
 
49
+ Relation-shaped reads take an equality filter instead of a hand-written loop — `list` returns only the rows whose fields strictly equal the values you name, typed against the row so a misspelled field is a compile error:
50
+
51
+ ```ts
52
+ for (const { id } of tx.list('checklists', { where: { studyId, assignedTo: userId } })) {
53
+ tx.del('checklists', id)
54
+ }
55
+ ```
56
+
57
+ The filter runs in SQL on the server before rows are parsed and before rows are cloned on the client; it still walks the table, so a mutator that filters once per item in a large batch should build its own lookup up front.
58
+
49
59
  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
60
 
51
61
  ### CRUD is included
@@ -61,7 +71,7 @@ A local throw rejects the call immediately and sends nothing. But local state ca
61
71
  :::
62
72
 
63
73
  ::: 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.
74
+ Timestamps, random values, ids you know up front: 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
75
  :::
66
76
 
67
77
  ```ts
@@ -72,6 +82,17 @@ await client.mutate.issue.create({ id: ulid(), createdAt: Date.now(), title })
72
82
  apply: (tx, { title }) => tx.put('issues', ulid(), { id: ulid(), createdAt: Date.now(), title })
73
83
  ```
74
84
 
85
+ The one exception is ids for rows the caller *cannot* enumerate — a batch whose size depends on what the server holds. `ctx.nextId()` mints ids from a per-mutation seed the engine carries with the mutation, so the n-th call returns the same id in both runs:
86
+
87
+ ```ts
88
+ apply: (tx, { studyId }, ctx) => {
89
+ for (const reviewer of tx.list('members', { where: { studyId } })) {
90
+ const id = ctx.nextId() // same id optimistically and on the server
91
+ tx.put('checklists', id, { id, studyId, assignedTo: reviewer.id })
92
+ }
93
+ }
94
+ ```
95
+
75
96
  ## Errors: `AppError` vs everything else
76
97
 
77
98
  `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.
@@ -110,3 +110,20 @@ const status = useSyncStatus(client)
110
110
  ```
111
111
 
112
112
  Status is about the *pipe*, not about individual mutations — individual outcomes arrive through each `mutate` promise.
113
+
114
+ ## Reacting after the commit
115
+
116
+ Mutators are pure over the workspace's rows; anything that reaches outside them — a notification, a projection into your primary database, an activity log — belongs in [`onMutationCommitted`](/reference/server#onmutationcommitted) on the server config. It runs after the mutation's transaction committed with the net before/after image of every row it touched, plus the mutator name, its parsed args, and the connection's principal:
117
+
118
+ ```ts
119
+ export class WorkspaceDO extends createWorkspaceDO({
120
+ app,
121
+ onMutationCommitted: async ({ workspaceId, name, principal, changes }, env) => {
122
+ await env.DB.prepare('UPDATE projects SET last_activity_at = ?, last_activity_by = ? WHERE id = ?')
123
+ .bind(Date.now(), principal, workspaceId)
124
+ .run()
125
+ },
126
+ }) {}
127
+ ```
128
+
129
+ The hook observes; it cannot reject or alter the mutation, and the client's confirmation never waits on it. It also never fires for a rejected mutation, a schema migration, or an admin import — only for a mutation that changed rows. Delivery is at-most-once, so a consumer that must not miss an event keys its effects on `version` and can rebuild from an admin export. The same change list comes back from the [test engine](/reference/testing#testmutationresult), so the logic you put behind the hook is unit-testable in node.
@@ -27,13 +27,15 @@ Routes resolve to `null` for traffic that isn't theirs, so they chain with `??`
27
27
  ```
28
28
  GET /admin/<workspaceId>/stats gauges + counters (rows, versions, connections, db size)
29
29
  GET /admin/<workspaceId>/export JSON snapshot of live rows
30
- POST /admin/<workspaceId>/import replace state from a snapshot (live clients converge via reset poke)
30
+ POST /admin/<workspaceId>/import replace state from a snapshot (live clients converge via reset poke); older snapshots are migrated on the way in
31
31
  POST /admin/<workspaceId>/reset wipe the workspace; new history (backendId)
32
32
  POST /admin/<workspaceId>/disconnect kick or refresh live sessions ({principal?, clientId?, mode})
33
33
  ```
34
34
 
35
35
  With the [yjs fields extension](/guide/collaborative-text) registered, `stats` includes its gauges and `export`/`import` round-trip fields alongside rows.
36
36
 
37
+ A snapshot taken before a schema bump still imports: the server replays the app's migration chain over the snapshot's rows — the same steps a sleeping workspace runs on wake — and the response carries `migratedFrom` so the operator can see it happened. A snapshot *newer* than the deployed app is rejected, and a chain that cannot be replayed (a missing or throwing step) rejects with the workspace untouched. Retained backups therefore stay restorable across version bumps for as long as the migration chain reaches back to them.
38
+
37
39
  Live clients need no special handling around any of these: an `import` or `reset` changes the workspace's history id, and connected clients converge through a reset poke — a full re-bootstrap delivered as a normal protocol message.
38
40
 
39
41
  ## Same-worker callers
@@ -60,6 +60,7 @@ The engine honors the [engine invariants](https://github.com/InfinityBowman/cf-s
60
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
61
  - Any other throw is **transient**: rethrown, nothing committed.
62
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
+ - `result.changes` is the before/after row list the Durable Object would hand to [`onMutationCommitted`](/reference/server#onmutationcommitted), so a hook's logic — which changes warrant a notification, what a projection row should look like — is unit-testable here by feeding it a real mutation's changes.
63
64
 
64
65
  ## Testing the full stack
65
66
 
@@ -66,7 +66,7 @@ The server validates **every** row write against the table's schema before it co
66
66
  Declares the named, intent-based mutations for a schema — shared by the server (authoritative apply) and the client (typed `mutate`, fail-fast validation). Each entry is a `MutatorDef`:
67
67
 
68
68
  - `args` — optional standard schema for the mutation's arguments. The server validates before `apply` runs (invalid args are a permanent `InvalidArgs` error that still advances the LMID); a SyncClient built with the same registry validates at `mutate()` time as a fail-fast. Omit for mutators that take no args.
69
- - `apply(tx, args, ctx)` — the mutation itself, against a [`MutatorTx`](#mutatortx) with a [`MutatorContext`](#mutatorcontext). The same function runs twice — optimistically on the client the moment `mutate` is called, authoritatively on the server when the push arrives — so it must be deterministic: pass ids, timestamps, and random values in as args, never compute them inside, or the server's result will not match the local prediction. See [the two authoring rules](/guide/defining-your-app#the-two-authoring-rules).
69
+ - `apply(tx, args, ctx)` — the mutation itself, against a [`MutatorTx`](#mutatortx) with a [`MutatorContext`](#mutatorcontext). The same function runs twice — optimistically on the client the moment `mutate` is called, authoritatively on the server when the push arrives — so it must be deterministic: pass timestamps and random values in as args, and take ids from args or [`ctx.nextId()`](#mutatorcontext), never compute them inside, or the server's result will not match the local prediction. See [the two authoring rules](/guide/defining-your-app#the-two-authoring-rules).
70
70
 
71
71
  Names are validated at definition time: non-empty, no empty dot-segments, and — because dots namespace the `client.mutate` call tree (`mutate.todos.clearCompleted`) — a name cannot be both a mutator and a namespace prefix of another (`todos` alongside `todos.clear` throws).
72
72
 
@@ -85,7 +85,7 @@ The full-row last-write-wins pair — `sync.put` and `sync.del`, the mutations [
85
85
  The authoritative view a mutator runs against, typed from the schema:
86
86
 
87
87
  - `get(tbl, id)` — the stored row (output shape, defaults applied) or `null`.
88
- - `list(tbl)` — every row as `{ id, data }`.
88
+ - `list(tbl, { where? })` — every row as `{ id, data }`, or only the rows whose fields strictly equal the scalars in `where` (`{ studyId: 's1', assignedTo: null }`; all named fields must match). `where` is typed against the row (`RowFilter<Row>`): an undeclared field, or a field holding an object or array, is a type error; a non-scalar value at runtime is a permanent `InvalidArgs`. The server evaluates the filter in SQL before parsing rows, the client before cloning them.
89
89
  - `put(tbl, id, data)` — writes the input shape, stores the validated output.
90
90
  - `del(tbl, id)` — removes the row.
91
91
 
@@ -99,6 +99,8 @@ The third argument every `apply` receives — how a mutator tells its two runs a
99
99
  - `principal` — the identity the worker's `authorize` hook stamped on the connection; `undefined` when no hook stamped one, and always `undefined` in optimistic runs (the client has no server verdict).
100
100
  - `auth` — the verdict's context, validated against the `authContext` schema at connect; on the client, the value passed as the SyncClient [`auth`](/reference/sync-client#auth) option.
101
101
  - `authoritative` — `true` on the server's run, `false` optimistically. Permission checks written as `if (ctx.authoritative && !allowed) throw` enforce on the server while letting the optimistic apply proceed; a server rejection rolls back through the normal permanent-error path.
102
+ - `seed` — the mutation's seed: minted once by the client at `mutate()` time, persisted with the queued mutation, carried on the wire, so every run of the mutation — optimistic, replayed after a reload, authoritative — sees the same value. Opaque; the reason it exists is `nextId`.
103
+ - `nextId()` — mints an id both runs agree on: the n-th call returns the same UUID-shaped string in the optimistic run and the authoritative one, and the sequence restarts at the top of each `apply`. This is how a mutator creates rows it cannot name at `mutate()` time — a batch whose size depends on server state — while keeping ids opaque. Ids from different mutations never collide (each has its own seed), and a rejected mutation does not shift the next one's ids.
102
104
 
103
105
  ### AppError
104
106
 
@@ -85,6 +85,36 @@ logger: (level, message, { workspaceId }, ...detail) => {
85
85
  }
86
86
  ```
87
87
 
88
+ ### onMutationCommitted
89
+
90
+ `(event: MutationCommitted, env: Env) => void | Promise<void>`
91
+
92
+ Runs after a mutation's data effects commit, with the rows it wrote or deleted — the seam for notifications, projections into another store, and activity logging. Fires once per mutation that changed rows; a rejected mutation, one whose writes net to nothing, a schema migration, and an admin `import` or `reset` all emit nothing. The worker env rides along so the hook can reach its own bindings.
93
+
94
+ ```ts
95
+ onMutationCommitted: async ({ workspaceId, name, principal, changes }, env) => {
96
+ for (const { tbl, before, after } of changes) {
97
+ if (tbl === 'tasks' && after?.assignee && after.assignee !== before?.assignee) {
98
+ await env.NOTIFY.send({ to: after.assignee, workspaceId, by: principal })
99
+ }
100
+ }
101
+ }
102
+ ```
103
+
104
+ The hook is an observer, never a participant: it cannot veto or amend the mutation, and the engine never waits for it — the client's confirmation is sent regardless. A returned promise is held with `waitUntil` so the object stays alive until it settles; a rejection or a synchronous throw goes to [`logger`](#logger) at `error` level and affects nothing else. Delivery is at-most-once: a workspace evicted with the promise in flight does not replay it, so a consumer that must not miss an event makes its effects idempotent on `version` and keeps a way to rebuild from an admin [`export`](#createadminfetch-createadminroute).
105
+
106
+ `MutationCommitted` carries:
107
+
108
+ - `workspaceId` — the workspace the mutation was applied to.
109
+ - `name` — the mutator name, as registered in the app definition.
110
+ - `args` — the args the mutator ran with: validated and parsed, defaults applied.
111
+ - `principal` — the connection's principal stamp, when [`authorize`](#authorize) set one.
112
+ - `clientId` — the client that pushed the mutation.
113
+ - `version` — the data version the mutation committed as; every `after` row is stamped with it.
114
+ - `changes` — `RowChange[]`, the rows the mutation wrote or deleted in the order it first touched them, never empty. Each is `{ tbl, id, before, after }`: `before` is the row as stored when the mutation began (`null` for an insert), `after` what it left (`null` for a delete). A row the mutation touched more than once appears once, spanning its net effect.
115
+
116
+ The [test engine](/reference/testing#testmutationresult) returns the same `changes` from `mutate`, so the logic behind a hook can be unit-tested in node without a Durable Object.
117
+
88
118
  ## createSyncFetch · createSyncRoute
89
119
 
90
120
  `(opts: SyncFetchOptions) => (request, env) => Promise<Response>` · `…Promise<Response | null>`
@@ -159,7 +189,7 @@ Typed admin surface over a workspace DO stub, for same-worker callers — app co
159
189
 
160
190
  - `stats()` — operational gauges and counters, designed to be scraped.
161
191
  - `export()` — a JSON snapshot of every live row (plus extension state when one is registered), accepted back by `import`.
162
- - `import(snapshot)` — replaces the workspace's rows atomically at a single new data version, resolving `{ imported, version }`. Live clients converge on their own: a reset poke re-bootstraps them in place, or — when the snapshot carries extension state — every socket is cycled with a refresh close instead.
192
+ - `import(snapshot)` — replaces the workspace's rows atomically at a single new data version, resolving `{ imported, version }`. A snapshot from an older schema version is migrated first — the app's migration chain replays over its rows in memory, and the result carries `migratedFrom` — while a newer snapshot, or one whose chain cannot replay (missing or throwing step), is rejected with the workspace untouched. Live clients converge on their own: a reset poke re-bootstraps them in place, or — when the snapshot carries extension state — every socket is cycled with a refresh close instead.
163
193
  - `reset()` — wipes the workspace and starts a new history under a fresh `backendId`, resolving `{ backendId }`. Also the one op a quarantined workspace still serves — the [recovery hatch](/guide/operations#reset-as-the-recovery-hatch).
164
194
  - `disconnect(opts?)` — closes live sockets matching the selectors (`principal`, `clientId`, or neither for all sockets), resolving `{ disconnected }`. `mode: 'kick'` (default) closes permanently — the client stops reconnecting and calls `onFatal` with `code` (default 4403) and `reason` — while `'refresh'` closes with 4300 so the client reconnects through a fresh `authorize` run and picks up new stamps. See [revoking and refreshing](/guide/auth#revoking-and-refreshing-live-sessions).
165
195
 
@@ -53,6 +53,17 @@ Simulates a workspace whose data was stored under an older schema version. When
53
53
 
54
54
  Initial rows, keyed table → id → row data. Whether they are validated or taken raw depends on [`storedVersion`](#storedversion) above.
55
55
 
56
+ ### nextSeed
57
+
58
+ `() => string` · default a random UUID per mutation
59
+
60
+ Mints the seed each [`mutate`](#mutate) runs under — `ctx.seed`, the value behind [`ctx.nextId()`](/reference/define-kit#mutatorcontext). The default is what a real client does. Supply a counter for reproducible ids, so a test can assert on the rows a batched mutator created:
61
+
62
+ ```ts
63
+ let n = 0
64
+ const engine = createTestEngine(app, { nextSeed: () => `seed-${++n}` })
65
+ ```
66
+
56
67
  ## Methods
57
68
 
58
69
  ### mutate
@@ -64,6 +75,8 @@ Applies a named mutation authoritatively as the engine's default client, with th
64
75
  - An `AppError` thrown by the mutator — or invalid args — is a **permanent** rejection: writes are discarded, the result carries [`error`](#testmutationresult), and [`lastMutationId`](#lastmutationid) still advances. Assert on both when testing rejection paths.
65
76
  - Any other throw is **transient**: it rethrows out of `mutate`, nothing commits, and the LMID does not advance — the real client would retry the push.
66
77
 
78
+ A successful result also carries [`changes`](#testmutationresult) — the rows the mutation wrote or deleted as before/after pairs, exactly what the Durable Object hands to [`onMutationCommitted`](/reference/server#onmutationcommitted) — so the logic behind a hook is testable here too.
79
+
67
80
  ### mutateAs
68
81
 
69
82
  `(clientId, name, args?) => TestMutationResult`
@@ -102,10 +115,12 @@ Read-only getters: the default clientId, and the current data version — bumps
102
115
 
103
116
  ### TestMutationResult
104
117
 
105
- `{ error?: { code: string; message: string } }`
118
+ `{ error?: { code: string; message: string }; changes: RowChange[] }`
106
119
 
107
120
  The outcome of one authoritative mutation. `error` is present only for permanent rejections: `code` is an engine built-in (`InvalidArgs`, `UnknownMutator`, …) or an app-defined `AppError` code passed through verbatim — the same vocabulary the client's [`MutationError`](/reference/sync-client#mutationerror) carries. Transient failures never produce a result; they throw.
108
121
 
122
+ `changes` lists the rows the mutation wrote or deleted, in the order it first touched them, as `{ tbl, id, before, after }` — `before` the stored row when the mutation began (`null` for an insert), `after` what it left (`null` for a delete); a row touched more than once appears once with its net effect. Empty on a permanent error and when the writes net to nothing (then `version` does not move either). This is the same list the Durable Object passes to [`onMutationCommitted`](/reference/server#onmutationcommitted).
123
+
109
124
  ## Schema-drift helpers
110
125
 
111
126
  The CI side of [drift detection](/guide/schema-evolution#drift-detection) — catching the one schema mistake the type system cannot: changing a table schema without bumping `version`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cf-sync/client",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
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": {
@@ -40,7 +40,7 @@
40
40
  "access": "public"
41
41
  },
42
42
  "dependencies": {
43
- "@cf-sync/protocol": "^0.1.1"
43
+ "@cf-sync/protocol": "^0.2.0"
44
44
  },
45
45
  "peerDependencies": {
46
46
  "@tanstack/db": "^0.8.0",
@@ -67,7 +67,7 @@
67
67
  "vitest": "^4.1.10",
68
68
  "yjs": "^13.6.31",
69
69
  "zod": "^4.0.0",
70
- "@cf-sync/yjs": "0.2.0"
70
+ "@cf-sync/yjs": "0.2.1"
71
71
  },
72
72
  "scripts": {
73
73
  "build": "tsdown",