One declaration yields a type, four derived schemas, behaviour, and a class that is itself a zod schema — with branded fields, immutable data, sealed construction, and Result instead of throws.
input, output, createInput and updateInput are derived from one field map — the generated / immutable flags a field carries, plus computed. Plain ZodObjects, so they convert to JSON Schema in both directions — no hand-written omit lists.
The class is itself a zod schema, so it drops into z.object({ owner: Organization }) as a field and still parses to a real instance, with its own behaviour and identity.
Nothing throws
Every fallible operation returns an unthrown Result carrying structured issues. A bug in your own domain code stays a separate defect, never folded into caller error.
import { z } from "zod";import { Entity } from "@btravstack/entity";import { Instant, OrgId, Slug } from "./vocabulary.js"; // each brand declared onceclass Organization extends Entity("Organization")( { id: Entity.field(OrgId, { generated: true, immutable: true }), slug: Entity.field(Slug, { immutable: true }), name: Entity.field(z.string().min(1), { unbranded: true }), // free text createdAt: Entity.field(Instant, { generated: true, immutable: true }), }, { invariants: [ Entity.invariant({ code: "NAME_TOO_LONG", ensure: (d) => d.name.length <= 80, message: "name must be at most 80 characters", }), ], },) { get greeting(): string { return `Welcome, ${this.name}`; }}// The package reads no clock and generates no id: bind the sources once,// where your ports already live.const createOrganization = Organization.factory({ id: () => ids.next(), createdAt: () => clock.now(),});const org = createOrganization({ slug, name }).getOrThrow();await db.insert(org.toJSON()); // exactly the stored shape — never `_tag`const loaded = Organization.make(row).getOrThrow(); // rows, imports, event foldsconst renamed = loaded.update({ name: next }).getOrThrow(); // a NEW entity
For a new id, a version-7 UUID (RFC 9562) sorts by creation time, so a primary-key index stays append-friendly; it is not an access control, and a tenant's rows stay guarded by its policy rather than by its ids. The uuidv7 package is monotonic within a millisecond; Node's own crypto.randomUUIDv7() is not, and recent Node releases alone have it.