Repository navigation
Releases
v0.8.1
Fixes for tabs whose local data is gone, and the CLI's deploy advice. No breaking changes.
Fixes
- A tab whose local data is gone loads again without waiting for another tab.
- A tab with no stored data downloads its own and is ready once that download is complete. That covers a first visit and IndexedDB deleted or cleared.
- Before, a tab that wasn't the leader counted itself ready only once the leader reported a successful sync. A leader in a background tab, which browsers throttle or freeze, could keep it loading indefinitely.
- That download retries with backoff when it fails, and a follower's own download leaves its status as it was rather than "bootstrapping".
- A bootstrap or pull whose response ends before the server's
endmarker fails and is retried. That covers a dropped connection or a proxy cutting the stream. Before, what had arrived was taken as complete. - A tab taking over as the leader starts syncing even when writing its data to storage fails. It then runs without storage instead of never connecting.
clientdb --helpmatches the deploy docs. It says to runmigrateandsetuponce the new release serves, never in a build while the old release serves.- The docs, READMEs and landing page match 0.8.0, and every TypeScript snippet in them is type-checked against the packages in CI.
Published to npm
v0.8.0
Claims are declared values. Breaking for code that uses claims; everything else is unchanged from 0.7.0, and the protocol's session claims map keeps its shape (a value is never a list).
Breaking changes
- Declare each claim once, in a file the server and the client both import:
declareClaim("staff")is yes or no;declareClaim("currentTeam").uuid()holds a UUID;.string()holds any text.
- Sessions set values by calling the claim:
claims: [staffClaim(isStaff), currentTeamClaim(teamId)]. Each call is typed by the claim's kind, and a UUID claim refuses a value that isn't one. A claim left out isfalseornull. - Rules read claims with
$.claim(…):$.claim(staffClaim)is a condition;tag.teamId.is($.claim(currentTeamClaim))compares a column (or a membership row insidesome()) with the claim's value;enforce: ($) => ({ teamId: $.claim(currentTeamClaim) })works too.
- The engine learns claims from the rules that read them. Two claims of one name with different kinds are refused, and so is a session setting a claim whose kind differs from the one the rules read.
- Clients read
db.$session.claim(currentTeamClaim), typed by its kind. Swift:Claim("currentTeam").uuid()anddb.session.claim(_:). - Migrating from 0.7.0:
- drop the schema's
claimsoption, from bothcreateSchemaandfromPrisma; - replace
claim.*builders withdeclareClaim,$.claims.<name>with$.claim(claim),claims: { name: value }withclaims: [claim(value)], anddb.$session.claims.<name>withdb.$session.claim(claim); claim.idOf,idsOf,stringsand list values are gone: use.uuid()or.string();- Swift's
isGranted,value(of:)andvalues(of:)are replaced bydb.session.claim(_:).
- drop the schema's
Fixes
sequenceNow()drains everything committed before the call, also when another process holds the drain. Change ids are drawn at insert, so a change can commit after one with a later id. A caller that waited for another process's drain could find nothing past the last drained id and return with its own change still queued; it went into the log only with the next drain. The leader's idle check had the same blind spot. Nothing was lost.
Published to npm
v0.7.0
Claims with values, server logic in the client's transaction, refusals in the app's words, open tabs that survive deploys, and connections no slow download can hold. Two breaking changes, in the claims API and the client; the session's claims changed shape in the protocol, so update clients and server together.
Breaking changes
- Claims hold values and are declared in the schema.
createSchema(models, { claims: { staff: claim.boolean(), currentTeam: claim.idOf("team") } })(alsofromPrisma(datamodel, { claims })); the session callback setsclaims: { staff, currentTeam }; rules read$.claims.staffand compare columns with$.claims.currentTeam.declareClaim,$staff(…)grants anddb.$session.hasClaimare removed; readdb.$session.claims.<name>. The protocol's sessionclaimsis now a map. Swift:db.session.isGranted(_:),value(of:),values(of:). db.$viewerIdreplacesdb.$session.viewerId.
Features
- Server logic in the same transaction:
createEngine({ transaction }), withprismaTransaction(prisma, …)from@clientdb/prisma(Prisma 5, 6 and 7), writes a device's change in a transaction you open;beforeCommit(writes, $)sees every row it wrote and can write more, or refuse;$.afterCommit(work)runs after the commit.
- Refusals in your words:
createEngine({ messages: defineMessages(schema, { conflict, forbidden, fallback }) })words what devices are told;- duplicates are matched by unique key through Postgres's catalog;
TransactionRejected(code, message)refuses frombeforeCommitwith your message;- composite unique keys come from the
uniquemodel option or Prisma's@@unique.
- Deploys and open tabs:
- clients and server exchange per-model hashes, and the server sends each client only the models it knows;
db.$versionis"current","updateAvailable"(the server only added models; the client keeps working) or"reloadRequired"(a model it uses changed: writes throw andonReloadRequiredasks to reload);- Swift:
db.versionandSyncOptions(onReloadRequired:); - the deploy docs now run setup when the new release starts serving, not in the build.
fromPrisma:sync: [...]lists the models that sync, andsyncAuthModelsreplacesinclude;models.<Model>.uniquedeclares keys schema.prisma can't;- the types now refuse everything startup refuses, including fields of schema.prisma that can't sync and calls without options.
validateis typed by model.onErroron the fetch and Next.js handlers and oncreateSyncServer.- The permission helpers on
$can be destructured without lint errors.
Fixes
- Slow or abandoned downloads hold no database connection:
- a bootstrap reads each page in its own short transaction;
- a pull commits before it sends;
- a stream whose device takes nothing for 60 s is ended (
downloadIdleTimeoutMs); - the Node server no longer leaks
closelisteners.
indexedDb()storage can't hang:- opening, loading and writing time out after 10 s;
- a load that can't read what is stored downloads afresh;
- other tabs' upgrades and deletes never block.
- The capture trigger ignores updates that change only columns that don't sync.
npx clientdb setupexplains a missing generated module, the usual monorepo mistake.
Published to npm
v0.6.3
Prisma 5 and 6 support. No breaking changes.
Features
@clientdb/prismaworks with Prisma 5, 6 and 7, with no workaround.- The generator speaks Prisma's generator protocol itself, and the package depends on none of Prisma's packages.
prismais an optional peer (5 or later), so a Prisma 5 app gets nothing of Prisma 7 installed. - Prisma 5's DMMF is converted in its own module:
@db.*native types are read from the schema source (every file of a multi-file schema), anduuid(4)-style default names read asuuid(). - Without the generator,
datamodelSubset(dmmf, { schema })takes the schema source for a Prisma 5 DMMF.
- The generator speaks Prisma's generator protocol itself, and the package depends on none of Prisma's packages.
- The generator stops with a clear error for a datasource that isn't PostgreSQL and for Prisma older than 5.
Fixes
npx clientdb setupandmigrateread.env.localand.envfrom the working directory, as the Prisma CLI does. Variables already set win.
Published to npm
v0.6.2
Fixes for sessions that change while a client is connected. No breaking changes, and no new options; 0.6.x clients and servers talk to each other.
Fixes
$sync()no longer loops after a claim is removed on an idle database. The pull that removed the claim ended at the position it started from, and the client waited for a later position before trusting any answer, so it asked/partialand/revalidateagain forever. The token change now takes the position the pull ends at. The Swift client has the same fix.- An open socket follows the session the client's requests resolve. A socket keeps the credentials it opened with, for example the cookie from before a switch from an admin token to a plain one for the same user.
- The server closes a client's socket with code 4409 and routes nothing more to it when a read, pull or push from that client resolves another session. Reads now carry
clientId. - The client also reconnects its socket when an answer names other tokens than its stream gave it, at most once every 10 seconds. This covers a socket on another instance, and it fetches a new sync token first. The Swift client does the same.
- The server closes a client's socket with code 4409 and routes nothing more to it when a read, pull or push from that client resolves another session. Reads now carry
- A session revoked on the server (an allowlist change, a revoked session) while the client is idle is applied at the socket's next session check, every token lifetime (300 s by default). A demotion evicts the claim's rows; a
nullsession closes the socket with 4401.
Published to npm
v0.6.1
Fixes and the 0.6.0 regressions. No breaking changes; 0.6.0 and 0.6.1 clients and servers talk to each other.
Fixes
$sync()no longer loops onPOST /revalidateafter a session claim is removed (for exampleclaim:staff, when the session is re-resolved on a later request). Answers remove tokens the client no longer has; answers to requests sent before a token change are asked again; a pull ends with the session's token changes. A token gain's revalidation names the tokens the client held before it (heldBefore).- Setup no longer deadlocks with writes in progress. It locks the synced tables first and retries on deadlock, serialization failure or lock timeout.
fromPrismaacceptsmodels.<Model>.relations.<relation>.mayBeUnreadableat runtime.- The readability proof accepts narrower memberships (a rule readable by members or admins, where admins are members), so it no longer warns falsely.
- A child deleted just before its parent moved or was deleted reaches every client that read it through the parent.
@clientdb/prisma's BigInt notice goes to stderr.
Performance (one 4-core VM, local Postgres 16)
- Promote / demote / move-out on a client: 108 / 54 / 14 ms → 51–57 / 20–27 / 3.9–4.9 ms (
bench:access; 0.5.0: 52 / 19 / 3.9). Client access evaluation is incremental. - One process serves 20,000 WebSockets (p50 5.6–15.4 ms at 300 writes/s; 0.6.0 saturated at 323 ms), with about a third less memory per connection.
- Polling server CPU at 5,000 / 10,000 clients: 72–76% / 98–102% → 56% / 77%.
- Postgres CPU per write while the engine drains: 0.35 → 0.21 ms (0.5.0: 0.23); 10,500–10,766 concurrent upserts/s.
- Serverless throughput with 8 instances: 650 → 920–1,050 pushes/s (0.5.0: 1,184).
Published to npm
v0.6.0
A new sync engine (wire protocol v3, see spec/protocol.md and spec/replica.md): no migrations, every write to a synced table syncs, access compiled into tokens and an access plan that clients evaluate, revalidation with digests instead of reloads, and lazy clients that receive only what they hold. 0.5 and 0.6 clients and servers don't talk to each other, and stored client data (IndexedDB, Swift SQLite) is fetched again once.
Breaking changes
-
No clientdb tables or models in your schema. The engine keeps its bookkeeping in its own Postgres schema,
clientdb, and installs one capture trigger per synced table when it first starts (createEngine({ setup: "auto" }), the default).npx clientdb setup <module>does it from a deploy step;--print-sqlprints the SQL for a migration of your own (then usesetup: "verify", which answers503 NotMigrateduntil the database matches).npx clientdb-prisma models/triggers, theClientdb*Prisma models, theclientdb_*tables and adopting existing rows are gone.Migrating: delete the
Clientdb*models and the clientdb trigger migrations, and drop the adoption step from your deploy. Keepsetup: "auto", or add a migration fromclientdb setup --print-sqland usesetup: "verify". -
Every write syncs. Prisma, raw SQL, other services and cascades all sync; a statement over
bulkRowsrows (default 1,000) or aTRUNCATEis logged as one invalidation.engine.changed(),engine.reconcile(),engine.resync(),engine.uncaptured(), thewarnUntrackedhandler option andresyncInvalidateThresholdare removed. -
Tokens instead of groups. Viewers hold tokens (
user|<id>,team.member|<teamId>,claim:staff|*).db.$groupsisdb.$tokens, and theonAccessRemovedhook receivestokens. Rows readable through a parent ($.canRead(row.parent)) leave the client with the parent, and answers ship the parents their rows need.$.canRead(row, { except })is removed. -
Required relations a viewer may not read. The engine warns at startup when the rules don't prove a required relation's target readable wherever its row is. Mark such relations
t.belongsTo(…).mayBeUnreadable()(fromPrisma:models.<Model>.relations.<relation>.mayBeUnreadable: true) to type them nullable on clients. -
Force sync resolves with
{ missing }and applies its answer as a revalidation. -
Protocol v3: stamps on every answer,
tokens,planandinvalidateactions,POST /revalidate, chunked/partial, interest by hash (interestHash,interestChange,interestUnknown) and replays.QueryRequest.whereis a list of clauses ({ or }alternatives). -
Swift implements protocol v3 (
ClientDBCorepasses every conformance vector). The per-modelLoadModeisModelLoad; the client'sLoadModeislazy,schemaorall. SQLite layout v3 drops older stored data.
Features
- Revalidation instead of reloads: after an invalidation, a gained token, a deploy with new rules or a pruned log, clients re-read what they hold with per-item digests; unchanged items answer
same. - Lazy clients send their interest and receive changes only for rows and collections they hold; an idle pull stays about 300 bytes at any held-row count.
entity.forceSync()/db.<model>.forceSync(ids),load: "all", and session-levelloadandforceSyncpermissions (NotAllowed, 403).wheretakesoralternatives, locally and in server queries.- Named rules that reach the viewer several ways get one token kind per way (
name#1,name#2).
Fixes
where({ id })on a lazy model loads that row, not the whole model.fromPrismarefuses implicit many-to-many relations with guidance.clientdb migrate/setupload app modules with tsconfig path aliases and extensionless imports.
Known regressions (fixes planned for 0.6.x)
- Postgres spends about 50% more CPU per write while the engine drains (0.35 vs 0.23 ms per write in
bench:triggers). - One process serves about 10,000 WebSocket clients comfortably; 20,000 saturate it. Polling costs more server CPU than in 0.5.
- Promoting, demoting or hiding a row from a client re-evaluates its whole held set (promote 132 vs 52 ms in
bench:server). - Serverless throughput with many instances draining inline is lower (667 vs 1,184 tx/s with 8 instances).
Published to npm
v0.5.0
The public API settles: models named by their createSchema key with relations as fields, $ as a rule argument, sessions with claims and read-only access, restricted fields, server queries, lazy clients with eviction, writes that apply at most once across long offline periods, retention, a round of security fixes and a faster sequencer. Old APIs are removed, not deprecated. Wire protocol v2 and schema IR v2: 0.4 and 0.5 clients and servers don't talk to each other, and open tabs reload once when you deploy. Breaking changes are listed first, each with what to change; the Swift client follows every change.
Breaking changes
-
Schema.
model(fields, options)takes no name, andcreateSchema({ user, todo }, { viewer: "user" })names models by their key. Relations are fields:project: t.belongsTo("project", { inverse: "todos", foreignKey, onDelete, eager })replacesschema(models, (relations) => …)andrelations.belongsTo.Migrating: move each model into the
createSchemaobject under its name, and eachrelations.belongsTo(…)onto the child as at.belongsTofield. -
ownedis removed; cascades come fromonDelete.t.belongsTo("todo", { inverse: "comments", onDelete: "cascade" })is the one way to cascade (default"setNull"for nullable relations,"restrict"otherwise). WithfromPrisma, the relation'sonDeleteinschema.prismadecides:Cascadecascades,SetNullclears the key, anything else restricts. Client deletes, undo,ensureUndoableand archive inheritance follow every cascading relation, and a model may cascade from several parents (archived while any of them is). Schema metadata hascascadingParents/cascadingChildreninstead ofowner/ownedChildren; the schema IR dropsowned.Migrating: replace
owned: truewithonDelete: "cascade", or give the Prisma relationonDelete: Cascade. -
Load modes are
"eager"and"lazy"."eager:critical"and"partial"are gone: a lazy model loads by its id, unique fields and foreign keys, andeager: trueon a relation loads children with their parent.db.$ready()takes no level, and<DatabaseProvider ready>is a boolean.Migrating:
"eager:critical"becomes"eager","partial"becomes"lazy",ready="critical"becomesready. -
fromPrismaoptions per model.models: { Todo: { load, id: { prefix }, restricted, archivable, relations: { project: { eager } } } }replaces the top-levelloadandownedlists;eageris the only relation option. Mistakes are type errors on the offending key, including misspelled model names inmodels,omitandnotSecret. -
Permissions take
$as an argument.defineModelRules(schema, "todo", { read: (todo, $) => { … } }),defineRule(schema, "project", (project, $) => …, { name })anddefinePermissions(schema, [rules…], { strict, groups })replacecreateRules,rules(…)andrules.fn; explicit groups move todefinePermissions'groups. -
$.canRead(row.relation), and nothing is readable implicitly.$.canRead(comment.todo)(or$.canRead(comment.todo, { except })), in read and write rules, replacescomment.todo.canRead(). Children no longer inherit their parent's read rule: every synced model needs areadrule, and outside production (strict)definePermissionsfails without one.read: (comment, $) => { return $.canRead(comment.todo); }reads exactly like the parent and is re-tagged in bulk when the parent's access changes.Migrating: add that rule to each formerly owned child.
-
updaterules are field groups:{ when, fields }or a list of them. Each changed field must belong to a group whosewhenholds before and after the write. -
Sessions replace viewers. The handlers'
viewer(request)option is nowsession(request), returning{ viewer, claims?, readOnly?, tenant? }ornull, andverifyJwt({ viewer })isverifyJwt({ session }). Sync tokens carry the whole session. On the client,db.$viewerIdisdb.$session.viewerId. Engine methods (bootstrap,pull,push,partial,connect) take aSessionfromcreateSession(viewer, { claims, readOnly, tenant })instead of tenant and viewer ids,engine.viewerGroupsisengine.sessionGroups(session), and sync ids are opaque strings.Migrating: rename
viewer:tosession:and return{ viewer: id }. -
Server mutators are removed, with
createEngine({ mutators }),db.$calland thecalloperation. Keep server logic in your own server actions or routes and call them throughdb.$action(fn). -
EntitiesOf<Schema>(DB["Todo"]) replaces the publicEntityOf<Schema, "todo">. -
db.$sync()resolves only after a pull that started after the call (a barrier on live sockets), not after one already in flight. -
Stricter security defaults, each refusing something 0.4 accepted:
- Sync token secrets (
tokens.secret,mintSyncToken) andverifyJwt({ secret })need at least 32 characters (openssl rand -base64 32). - POST bodies must be
application/json; other media types get 415. ?token=is read only on WebSocket upgrades, never on plain HTTP requests.- Without
cors, a WebSocket from another origin needs a sync token: cookies alone get 403. Passcorsif pages on other origins call the server.
- Sync token secrets (
-
Custom
Reactivityimplementations need areaction(onInvalidate)method;signalsandmobxReactivity()have it. -
Engine:
sequenceOnce()is removed.sequenceNow()takes no arguments anddrainChanges()resolves once the backlog is empty; both return nothing. -
Upgrading the database. Run
npx clientdb migrate <engine module>when you deploy (--dry-runfirst prints the plan). On engine-owned tables it adds the new columns itself. Prisma apps first re-runnpx clientdb-prisma modelsand migrate, for the newclientdb_row.field_readers,clientdb_log.created_atandnonce,clientdb_head.transactions_horizonandclientdb_transactions.headcolumns (clientdb migratenames any that are missing), and regenerate the capture triggers withnpx clientdb-prisma triggers src/sync/schema.ts: they now coverserverOnlymodels, key changes, TRUNCATE and cascaded rows, and wake the sequencer.
Features
-
Restricted fields:
.restricted()(ormodels.X.restrictedwith Prisma) and per-field read rules,read: { when, fields: { inviteCode: (project, $) => { … } } }. Hidden fields areundefinedon the client and routed in their ownfield_readerscolumn. -
Claims and read-only sessions:
declareClaim("staff"), granted by the session callback, used as a condition in rules and checked on the client withdb.$session.hasClaim($staff).readOnly: trueon a session or route refuses writes withReadOnly(ReadOnlyErroron the client), andcreateDatabaseClient({ readOnly: true })types a client without writes. Live sockets check their session again every token lifetime and renew sync tokens, and changed claims move rows on and off the device. -
Writes apply at most once, also after long offline periods. Applied transaction ids are kept for
retention.transactions(default the longer ofretention.logand 90 days). A pull from a client behind the pruned log is answered withresetbefore anything it sent is applied, and a resend the server may have applied after its id was pruned is refused with the newStalecode instead of applied twice. The client stamps each transaction with the sync position it is first sent from. -
Server queries:
db.todo.query({ where, orderBy, limit })overPOST /query, with keyset pages and per-modelquery: { fields, maxLimit }rules.wheregains text operators (contains,startsWith,endsWith). -
Lazy clients and eviction:
createDatabaseClient({ load: "lazy" })starts with no rows, andeviction: { maxRows }drops the loads used longest ago that nothing observes. -
Fields:
t.uuid({ prefix }),t.decimal(),.unique()and.generated()(Prisma autoincrement anddbgenerated()columns). -
db.$action(fn, { optimistic })previews a server action's outcome on the device until the server answers. -
Engine:
retention: { log, transactions, archived }applied byengine.prune()(hourly instart(), and byclientdb migrate); clients behind the pruned log start over.hooks: { onWriteRejected, onAccessRemoved }(no row data, safe to log),bootstrapRowWarning,cascadeRowLimitandrecentLogActions.clientdb migrate --dry-runandengine.migrationPlan()show what a migration would do. -
Prisma archives:
models.X.archivablewitharchivedAt/archivedBycolumns, so Prisma tables supportarchive(),unarchive()andretention.archived. -
Transient database failures (a lost connection, shutdown, statement timeout or deadlock) throw
Unavailable: HTTP answers 503, a live socket closes with 1011, and the client keeps the transaction and resends it, instead of dropping a write that was never wrong.
Fixes
-
Security:
- Cross-site WebSockets authenticated by cookies are refused (browsers attach cookies to any site's upgrade), and an opaque
nullOrigin no longer crashes the server. - Non-JSON POST bodies get 415, so another site can't push transactions with the viewer's cookies through a form or a no-cors fetch.
- Tokens are no longer read from URLs of plain HTTP requests, and the Swift client sends its token as a header on the WebSocket too.
- Secrets under 32 characters are refused. Malformed JWTs and JWKS keys that don't fit the token's algorithm answer 401 instead of 500.
- Written values are checked against their field (type, enum, nullability) before rules run, so a rule can't be passed with
"0"that Postgres then stores as0. - Client archives, and creates or restores of archived rows, are stamped with the server's clock and the viewer and need the archive rule, so a back-dated archive can't make retention delete a row.
- Writes to r...
- Cross-site WebSockets authenticated by cookies are refused (browsers attach cookies to any site's upgrade), and an opaque
v0.4.0
load: "partial" with load keys inferred from relations, a round of API fixes so each thing has one name and one shape, and helpers for plain Node.js servers (Express, Fastify, Hono). Breaking changes are listed first, each with what to change.
Breaking changes
-
load: { partial: [...] }is nowload: "partial", and every relation's foreign key is a load key. Before, a reference left out of the list was treated as fully loaded, souser.commentsreported"complete"while showing only the comments already on the device; now each parent's collection loads (and reports"partial") on its own.Migrating: replace
load: { partial: ["todoId"] }withload: "partial"(inmodel()options orfromPrisma'sload). The old shape throws with a pointer to the new one, and a partial model without a relation to a parent is rejected (use"lazy"). On your own tables (Prisma), index every foreign key of a partial model, such as@@index([authorId]).engine.partial/partialManyonly load a partial model by one of its load keys (or as a whole, for reloads afterinvalidate); loads by other fields return nothing.Model and schema hashes now cover
loadand each relation'sonDelete, so a client running an older bundle getsSchemaOutdatedafter a load-strategy change instead of showing a now-partial model as complete. Every schema hash changes once with this release, so open tabs reload when you deploy it. Migrations compare the newshapeHash(the previous formula), so stored snapshots stay valid and changing onlyloadoronDeleteneeds no migration. -
One way to keep a model on the server:
model("auditLog", { … }, { serverOnly: true }), orfromPrisma(models, { serverOnly: ["AuditLog"] }). A server-only model needs no rules, clients can't write it, and it and its relations are left out of client types, accessors and generated Swift code; rules can still read it.Removed, with errors that name the replacement:
load: "local". It was documented as "never synced", but the server accepted and fanned out its writes, required rules for it, and its collections reportedcompletewithout loading the server's rows.sync: falseon models (nowserverOnly: true).rules("model", "server-only")(mark the modelserverOnlyin the schema; rules for a server-only model now throw).
The schema IR writes
serverOnlyinstead ofsync; the Swift client still reads"sync": false. -
syncno longer means three things.fromPrisma'ssync(the secret-looking columns that may go to clients) is nownotSecret, andcreateDatabaseClient({ sync: false })(no network) is nownetwork: false; the model option becameserverOnlyearlier. The old spellings throw with the new name. -
updatedAtfields now change on every update, as documented. Declare them with the field modifierupdatedAt: t.timestamp().updatedAt()(theupdatedAtmodel option is removed and throws;fromPrismamaps@updatedAtto it). The client stamps the field at once on every update that changes another field (optimistically, and the operation carries the value), the server stamps it on updates made on the server (system writes, mutators) on engine-owned tables too, and field permissions (update.fields) never need to list it. Previously the field was only set on insert, except on Prisma tables, where clients didn't receive the new value until a reconcile.dirtyFieldsdoesn't list stamped fields. New:completeUpdatein@clientdb/core(spec/replica.md§4.1), mirrored by the Swift client. -
One name for each thing: the permission helpers
$.alland$.anyare removed in favour of$.andand$.or(they were documented as "same as"), andCollection.findById(id)(which returnednull) is nowget(id)returningundefined, the same name and convention asdb.issue.get(id). -
Owned children now inherit their parent's read access, as documented: an
owned: truechild without a read rule is readable exactly when its parent is (parent.canRead()), and strict mode no longer asks for a rule for it. Its writes still need rules; an explicitreadrule still wins.owned: { inheritAccess: false }is removed (it only switched off a set-based re-tagging optimization; give the child its own read rule instead), and so isinheritAccesson relation metadata and in the schema IR. The engine'sbulkInheritoption is now internal. -
ownedno longer silently overridesonDelete.belongsTo(…, { owned: true, onDelete })is a type error and throws (owned relations always cascade), andfromPrisma'sownedrefuses a relation whose schema.prismaonDeleteisn'tCascade, so deleting a parent with Prisma Client and with clientdb does the same thing. -
archivableis now a boolean:model("issue", { … }, { archivable: true }). Theretainsetting is gone: it was required but nothing read it (there is no purge job), so a value like"30d"silently kept archived rows forever. An object value now throws. The schema IR writes"archivable": true | false; the Swift client still reads the old object form.ArchivableOptionsis no longer exported. -
load: "onDemand"is removed: it behaved exactly likeload: "lazy", which stays. The load strategies are now"eager:critical","eager"(default),"lazy"and"partial". Using"onDemand"throws with the replacement; the Swift client reads it aslazyin older schema files. -
createSyncServerserves under/api/syncby default, the client's defaulturl, instead of/sync, so an unconfigured server and client meet. PassbasePath: "/sync"to keep the old path. It also acceptswarnUntracked, like the fetch and Next.js handlers. -
Safer token and error defaults:
- Sync tokens carry
aud: "clientdb-sync", and the handlers accept a bearer token as a sync token only with that audience, so another HS256 token signed with the same secret (another app's, or staging's) isn't one. New exports:verifySyncToken,SYNC_TOKEN_AUDIENCE. verifyJwtandverifyJwtTokenrefuse tokens without an expiry (exp), which would otherwise never expire.verifyJwt({ jwks })warns in development when noaudienceis set: without one, tokens your auth provider issued for your other apps are accepted.- In production, a failed request answers
{ error: "internal error" }instead of the error message (database errors name tables and constraints); the details are still logged.
- Sync tokens carry
Features
-
Plain Node.js servers:
createSyncServernow plugs into Express and Connect (syncServer.middleware), Fastify (app.register(syncServer.fastify)) and Hono or Bun (syncServer.fetch), andsyncServer.attachWebSocket(server)adds the realtime socket to a server you created. NewcorsandbodyLimitoptions (default 16 MiB) oncreateSyncServer,createFetchHandlerand the Next.js handler.syncServer.close()now returns a promise: it closes sockets with code 1001, refuses new ones and stops the sequencer it started. A throwingviewernow answers 500 instead of hanging the request (and crashing the process with an unhandled rejection),attachleaves other listeners' WebSocket upgrades alone, and malformed JSON bodies answer 400. Theviewercallback ofcreateSyncServeralso gets the Node request asraw. -
The schema names its viewer model:
schema(models, relations, { viewer: "member" })orfromPrisma(models, { viewer: "Member" }), defaulting to theusermodel.db.$vieweris now typed as that model's entity (it was a union of every model, sodb.$viewer?.namedidn't type-check), andcreateRules(schema)takes the viewer from the schema; an explicitcreateRules(schema, { viewer })must match it. New exports:ViewerModel,SchemaOptions;Schemahas a third type parameter and aviewerproperty. -
Less to restate in a TypeScript schema: every model gets
id: t.id()without declaring it (declaring it still works), andbelongsTonames the relation after a foreign key named…Idwhenasis left out (belongsTo(issue, "teamId", team, { inverse: "issues" })isissue.team). Other foreign keys still needas, as a type error and at runtime. -
createEngine({ permissions })takes its schema from the permissions (createRules(schema)already names it), soschemais optional. When it's passed and isn't the permissions' schema,createEnginethrows instead of compiling access for one schema and storing rows for another.EngineOptions.permissionsis now typedPermissions<S>. Docs drop the redundantschemaand, whereDATABASE_URLis the default anyway,database. -
db.$computed(fn)anddb.$effect(fn)derive values and run effects with whichever reactivity the client uses (built-in signals or MobX), so there is nocomputedto pick from the right package.mobxReactivity()no longer needs themobxmodule passed in: it uses the app'smobx(a peer dependency); passing one still works. -
createDatabaseClient(andcreateTestClient) report a type error when the classes inRegister["models"]and in themodelsoption differ. Relations returnRegister's classes whiledb.<model>returns the option's, so a class listed in only one of them used to type-check and then fail at runtime (a relation typed asTodoreturning a plain entity withouttodo.toggle()). New export:RegisterCheck. -
In development, the sync handlers warn once when
anonymousand the rules disagree: read rules use$.publicbut signed-out requests get 401, oranonymous: trueis set but no rule uses$.public.
Fixes
-
fromPrismarough edges:- Creating a row of a model whose omitted column is required without a database default is refused with a
Validationerror naming the column, instead of failing in Postgres with a 500 (ExternalModelStorage.requiredOmitted). - On the server in development,
fromPrismanotes once which columns change shape on clients:BigIntcolumns (numbers, ex...
- Creating a row of a model whose omitted column is required without a database default is refused with a