Skip to content

v0.4.0

Choose a tag to compare

@github-actions github-actions released this 02 Dec 17:53
da8f0f4

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 now load: "partial", and every relation's foreign key is a load key. Before, a reference left out of the list was treated as fully loaded, so user.comments reported "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"] } with load: "partial" (in model() options or fromPrisma's load). 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 / partialMany only load a partial model by one of its load keys (or as a whole, for reloads after invalidate); loads by other fields return nothing.

    Model and schema hashes now cover load and each relation's onDelete, so a client running an older bundle gets SchemaOutdated after 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 new shapeHash (the previous formula), so stored snapshots stay valid and changing only load or onDelete needs no migration.

  • One way to keep a model on the server: model("auditLog", { … }, { serverOnly: true }), or fromPrisma(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 reported complete without loading the server's rows.
    • sync: false on models (now serverOnly: true).
    • rules("model", "server-only") (mark the model serverOnly in the schema; rules for a server-only model now throw).

    The schema IR writes serverOnly instead of sync; the Swift client still reads "sync": false.

  • sync no longer means three things. fromPrisma's sync (the secret-looking columns that may go to clients) is now notSecret, and createDatabaseClient({ sync: false }) (no network) is now network: false; the model option became serverOnly earlier. The old spellings throw with the new name.

  • updatedAt fields now change on every update, as documented. Declare them with the field modifier updatedAt: t.timestamp().updatedAt() (the updatedAt model option is removed and throws; fromPrisma maps @updatedAt to 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. dirtyFields doesn't list stamped fields. New: completeUpdate in @clientdb/core (spec/replica.md §4.1), mirrored by the Swift client.

  • One name for each thing: the permission helpers $.all and $.any are removed in favour of $.and and $.or (they were documented as "same as"), and Collection.findById(id) (which returned null) is now get(id) returning undefined, the same name and convention as db.issue.get(id).

  • Owned children now inherit their parent's read access, as documented: an owned: true child 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 explicit read rule 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 is inheritAccess on relation metadata and in the schema IR. The engine's bulkInherit option is now internal.

  • owned no longer silently overrides onDelete. belongsTo(…, { owned: true, onDelete }) is a type error and throws (owned relations always cascade), and fromPrisma's owned refuses a relation whose schema.prisma onDelete isn't Cascade, so deleting a parent with Prisma Client and with clientdb does the same thing.

  • archivable is now a boolean: model("issue", { … }, { archivable: true }). The retain setting 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. ArchivableOptions is no longer exported.

  • load: "onDemand" is removed: it behaved exactly like load: "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 as lazy in older schema files.

  • createSyncServer serves under /api/sync by default, the client's default url, instead of /sync, so an unconfigured server and client meet. Pass basePath: "/sync" to keep the old path. It also accepts warnUntracked, 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.
    • verifyJwt and verifyJwtToken refuse tokens without an expiry (exp), which would otherwise never expire.
    • verifyJwt({ jwks }) warns in development when no audience is 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.

Features

  • Plain Node.js servers: createSyncServer now plugs into Express and Connect (syncServer.middleware), Fastify (app.register(syncServer.fastify)) and Hono or Bun (syncServer.fetch), and syncServer.attachWebSocket(server) adds the realtime socket to a server you created. New cors and bodyLimit options (default 16 MiB) on createSyncServer, createFetchHandler and 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 throwing viewer now answers 500 instead of hanging the request (and crashing the process with an unhandled rejection), attach leaves other listeners' WebSocket upgrades alone, and malformed JSON bodies answer 400. The viewer callback of createSyncServer also gets the Node request as raw.

  • The schema names its viewer model: schema(models, relations, { viewer: "member" }) or fromPrisma(models, { viewer: "Member" }), defaulting to the user model. db.$viewer is now typed as that model's entity (it was a union of every model, so db.$viewer?.name didn't type-check), and createRules(schema) takes the viewer from the schema; an explicit createRules(schema, { viewer }) must match it. New exports: ViewerModel, SchemaOptions; Schema has a third type parameter and a viewer property.

  • Less to restate in a TypeScript schema: every model gets id: t.id() without declaring it (declaring it still works), and belongsTo names the relation after a foreign key named …Id when as is left out (belongsTo(issue, "teamId", team, { inverse: "issues" }) is issue.team). Other foreign keys still need as, as a type error and at runtime.

  • createEngine({ permissions }) takes its schema from the permissions (createRules(schema) already names it), so schema is optional. When it's passed and isn't the permissions' schema, createEngine throws instead of compiling access for one schema and storing rows for another. EngineOptions.permissions is now typed Permissions<S>. Docs drop the redundant schema and, where DATABASE_URL is the default anyway, database.

  • db.$computed(fn) and db.$effect(fn) derive values and run effects with whichever reactivity the client uses (built-in signals or MobX), so there is no computed to pick from the right package. mobxReactivity() no longer needs the mobx module passed in: it uses the app's mobx (a peer dependency); passing one still works.

  • createDatabaseClient (and createTestClient) report a type error when the classes in Register["models"] and in the models option differ. Relations return Register's classes while db.<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 as Todo returning a plain entity without todo.toggle()). New export: RegisterCheck.

  • In development, the sync handlers warn once when anonymous and the rules disagree: read rules use $.public but signed-out requests get 401, or anonymous: true is set but no rule uses $.public.

Fixes

  • fromPrisma rough edges:

    • Creating a row of a model whose omitted column is required without a database default is refused with a Validation error naming the column, instead of failing in Postgres with a 500 (ExternalModelStorage.requiredOmitted).
    • On the server in development, fromPrisma notes once which columns change shape on clients: BigInt columns (numbers, exact up to 2^53) and cuid()/ulid()/nanoid() defaults (UUIDv7 from clients).
    • clientdb-prisma triggers finds triggers.sql when the generator block relies on the default output.
  • In development, createEngine now replaces its cached engine when any rule changes (write rules, update.fields, enforce, validate, explicit groups), when mutators, migrations or engine settings change, not only when read rules do. Permissions exposes the fingerprint it uses.

Published to npm