@latticecms/core
Collections that compile into hexok use cases, hexok event classes and a ts-pf contract. A collection is a Zod schema with a slug. framework() turns a set of them into a typed RPC contract, and build() wires that contract to a store and an event publisher. Every generated piece is a real hexok UseCase, Event, Errors and Port, and a real ts-pf router, so a hand-written one can take its place with the same types.
Status: before 1.0. Breaking changes are free until 1.0. The design and the reasons behind it are in docs/architecture.md.
Install
Section titled “Install”npm install @latticecms/core hexok @ts-pf/contract @ts-pf/protocol @ts-pf/server @ts-pf/docs @ts-pf/mcp zod @hexok/logger @opentelemetry/apiEverything after @latticecms/core is a peer dependency: hexok 2.3.1 or later, the @ts-pf/* packages 1, zod 4, @hexok/logger 0.2 and @opentelemetry/api 1. The app installs them, so it and Lattice share one copy of each:
- a
UseCase,PortorErrorsclass the app imports is the same class Lattice built, soinstanceofand hexok’s checks hold; - the contract’s types are ts-pf’s own, so every ts-pf client,
@ts-pf/openapiand@ts-pf/mcpread them; - a schema the app writes is the Zod Lattice parses with;
- the OpenTelemetry SDK the app registers is the one Lattice’s spans reach.
@latticecms/core runs on Node only: it imports node:util and node:async_hooks at load. A server bundle may inline it. Then it must also inline every package that imports core, such as store-mongo: one left external would import the copy of core in node_modules, a second copy. Vite’s SSR build inlines a package it cannot resolve from the app’s root, such as one npm nested in a workspace; see Upgrading. A browser bundle imports it type-only, with import type. To share a schema or a rule with a client, put it in a module that does not import Lattice, and import that module from both sides. A value import that reaches core may build, but the built bundle can fail at load.
@ts-pf/docs and @ts-pf/mcp carry the per-procedure descriptions; Lattice imports only docs() and the dependency-free @ts-pf/mcp/meta. Serve the result with @ts-pf/server-http, and call it with @ts-pf/client. A store adapter, such as @latticecms/store-mongo, is its own package.
Upgrading
Section titled “Upgrading”A minor of core comes with a minor of store-mongo and the cli, whose peer ranges take only the new core. Upgrade them in one npm install, with @latticecms/cli@latest too if the app uses the cli, then check that the app has one copy of core:
npm install @latticecms/core@latest @latticecms/store-mongo@latestnpm ls @latticecms/core --parseable --allThe second command prints one path for each copy on disk, and should print one.
- In an npm workspace, upgrade with
-win each workspace that uses core, the one with store-mongo first. Then run a plainnpm install, which removes a copy the lockfile no longer names, and check again. Raising the ranges by hand and runningnpm installinstead can leave a copy of core in each workspace. If the check still prints more than one path,npm dedupemerges them. Read the lockfile’s diff afterwards, because dedupe can move other packages too. - Upgrading core alone breaks the pair. In a one-package app, npm warns and leaves store-mongo on a core outside its peer range. In a workspace, it installs a second core next to the old one, without a warning.
Quick start
Section titled “Quick start”One collection, one family, an in-memory store and an in-process client. It runs as is, with Node 24 (node quickstart.ts).
import { NoopLogger } from '@hexok/logger';import { collection, family, framework, MemoryStore } from '@latticecms/core';import { createLocalClient } from '@ts-pf/server';import { z } from 'zod';
const Notes = collection('notes', { schema: z.object({ title: z.string().min(1), done: z.boolean().default(false), }),});
const AppUseCase = family({ actor: z.object({ userId: z.string() }), actorId: (actor) => actor.userId,});
const { app } = framework({ family: AppUseCase }) .collection(Notes, { access: { read: () => true, create: () => true, update: () => true, delete: () => true, }, }) .build({ store: new MemoryStore(), // Where collection events go: nowhere, here. events: { async publish(_event: { readonly payload: unknown }) {} }, });
const client = createLocalClient(app, { context: { actor: { userId: 'ann' }, logger: new NoopLogger() },});const note = await client.notes.create({ title: 'Write the docs' });await client.notes.update({ id: note.id, done: true });const { docs } = await client.notes.find({ where: { done: { eq: true } } });console.log(docs.map((doc) => doc.title));It prints [ 'Write the docs' ]. The client is typed from the contract: client.notes.find takes a typed where, and returns typed documents with id, createdAt and updatedAt. Over HTTP, the same app is served by @ts-pf/server-http’s FetchHandler; see The auth edge.
The agent skill
Section titled “The agent skill”Core ships an agent skill in skills/lattice: a SKILL.md with the steps from a collection to an override, and one reference per concept (collections, access, tenancy, relations, masking, overrides, methods, event handlers, testing and the CLI), each quoting the crm. In an app that installs core, link it into the agents’ skill directories with:
npx skills experimental_sync -y -rIt links .agents/skills/lattice to node_modules/@latticecms/core/skills/lattice, beside hexok’s hexok skill and the ts-pf-* skills. -r also reads the dependencies of each workspace package, where a monorepo’s app keeps them.
Concepts
Section titled “Concepts”The examples come from examples/crm: a CRM with tenanted companies, contacts, deals, activities and tasks on MongoDB, served to signed-in members of an organization.
Collections
Section titled “Collections”A collection is a slug and a z.object() schema. Hooks transform data and nothing else.
import { collection, ref } from '@latticecms/core';import { z } from 'zod';
export const Contacts = collection('contacts', { schema: z.object({ // The messages are what a form shows at the field. name: z.string().min(1, 'Enter a name'), email: z.email('Enter an email address, like ana@example.com'), phone: z.string().optional(), // The contact's job title. title: z.string().optional(), // A company with contacts cannot be deleted: restrict, the default. // Like every ref, it refuses '': "Choose the company". companyId: ref('companies'), }), tenant: 'organizationId',}).hooks({ // One spelling per address, so a where on email finds it. beforeChange: ({ data }) => ({ ...data, email: data.email.toLowerCase() }),});Lattice adds id, createdAt and updatedAt to every document, and the tenant field to a tenanted one. collection()’s options are in the reference.
.hooks({ beforeChange?, afterRead? }) returns the same collection with those hooks. A later call replaces a hook it names.
beforeChange({ data, operation, previous? })runs after validation, before the write, on create and update.datais the whole document after the change, without system fields. It returns the data to store. On a collection with server fields, create’sdatahas only the ones an override gave, and create checks the whole document after the hook. On create and update, a server field the hook leaves out keeps its value. On update,undefinedremoves an optional one. On create, a key set toundefinedis left out of the row, the result and thecreatedevent. A server field is checked first:undefinedbecomes its default, and create fails if its schema refusesundefined.afterRead({ doc })runs on every document a generated operation returns. It does not change what is stored or what events carry.
The family
Section titled “The family”The app has one use case family. Generated and hand-written use cases extend it, and share its guards, logging and spans. tenantOf has an entry for each tenant field. Here it gives each call its organization, or a read-only bypass for support staff.
import { family, tenancy } from '@latticecms/core';import type { UseCase } from 'hexok';import { z } from 'zod';import { role } from '../../domain/collections/memberships.js';import { DomainError } from '../../domain/errors/domain.js';
/** A member acting in one organization, with its role there; the edge checked both. */const memberSchema = z.strictObject({ userId: z.string().min(1), organizationId: z.string().min(1), role,});
/** * Support staff: they read every organization's rows and change none. The * edge sets this from server config, never from the request, and a support * actor has no organization. */const supportSchema = z.strictObject({ userId: z.string().min(1), support: z.literal(true),});
/** * Who is calling. The edge builds it from the session and the * organization header. Strict, so an actor with both an organization and * the support flag is invalid rather than read as either. */export const actorSchema = z.union([memberSchema, supportSchema]);
export type Actor = z.output<typeof actorSchema>;
/** What an edge passes: the schema's input, which Lattice parses once per call. */export type ActorInput = z.input<typeof actorSchema>;
/** The app's one use case family. Generated and hand-written use cases share it. */export const AppUseCase = family({ actor: actorSchema, actorId: (actor) => actor.userId, tenantOf: { organizationId: (actor) => 'support' in actor ? tenancy.bypass : actor.organizationId, }, // Its domain errors are refusals; any other error is logged as a failure. refusals: [DomainError],});
export type AppCtx = UseCase.Ctx<typeof AppUseCase>;family({ actor, actorId, tenantOf?, refusals? }) builds a hexok UseCase.context family.
A caller passes { actor, logger } (CallContext<ActorInput>): the actor as the schema’s input, and a @hexok/logger Logger for the call. Lattice parses the actor once per call and adds access, the call’s access, so a use case receives { actor, logger, access } (FamilyContext<Actor>) with the parsed actor. A transform runs once, and a field with a default can be left out. ActorInput is the app’s own z.input<typeof actorSchema>; for a schema with no transform or default it equals Actor.
- Before
execute, the actor must parse againstactor, and access must allow the use case’s action. A bad actor isUNAUTHORIZED, and a refusal isFORBIDDEN. - A transport parses a client’s input against the procedure’s input schema, once: HTTP, the local client and MCP. Bad input is
VALIDATION, andexecutereceives the parsed value, with defaults filled and transforms run (0065). No guard parses it again, so a method’s input may use defaults and transforms. Server code that callsexecutepassesexecute’s declared type, and Lattice passes that value on as is, unchecked: a type cannot say.min(1)or.email(), so code that holds data it has not checked, such as a queue message, parses it first. A transport whose input validation is off (validation: { input: false }) leaves input unchecked. - A generated operation’s body parses its own input, so a direct call may leave a default out. Through a transport this is a second parse, which changes nothing, since a collection schema has no transforms; an
.overwrite()runs once per parse. - An override cannot tell a value a client sent from a default it got. A field no client may send belongs in
serverFields, and the override sets it. - The actor is parsed once per call, and everything after sees the parsed value: access functions,
tenantOf’s entries,actorId, log lines,execute’sctx.actorand events. Keys the schema strips never reach them, and a transform’s output does. Make an actor union ofz.strictObjects when a key changes meaning, such as asupportflag, so an actor that mixes the shapes is refused rather than read as one of them. actorIdnames the id that log lines and collection events carry. The family exposesactor,actorIdandtenantOf, so hand-written code callsAppUseCase.actorId(ctx.actor).tenantOfis a map keyed by tenant field. Each entry returns the actor’s tenant id,tenancy.bypassortenancy.none. Each tenanted collection’s field needs an entry; see Tenancy.refusalslists the app’s hexokErrorscatalogs whose members are refusals, such as[DomainError]. A refusal is logged at info, and its span’s status stays unset. ALatticeErrorand a hexokVALIDATIONalways are refusals. Any other error is a failure, logged at error, a member of an unlisted catalog included. A library’s catalog, such asMongoStoreError, names the app’s mistakes, so it stays off the list. hexok has no mark for an expected error, so the app says which ones are.- List each catalog that
errors.mapsends to clients, and only a catalog that a Lattice use case throws on purpose for the caller. A wiring guard, such as a missing dependency, is a failure. A member of a catalog the family does not list still reaches the client with its code, but its log line and both spans record a failure. - Every call writes one line through a child of
ctx.loggerwithcollection,action,actorId,tenantId(ortenancy: 'bypass'or'none'),outcomeanddurationMs. The tenant is the one for the call’s own collection. No other entry oftenantOfruns for the line, and a call on a global collection has no tenant in it. - A hand-written use case extends the family with a
collectionstatic, andinputandoutputschemas for a method. Its token is<slug>.<name>. - A method also says what it does, in
summary, and how it affects data, ineffect:read,writeordestructive. They become its procedure’sdocsandmcpmeta, so MCP tools, OpenAPI and the admin describe it from one place. An override declares neither: it keeps the meta of the operation it replaces.
export class CloseDeal extends AppUseCase('deals.close', { collection: Deals, input: z.object({ id: z.string(), outcome: z.enum(['won', 'lost']) }), // As a client receives a deal: the amount is withheld from a member. output: Deals.clientOutput, // What MCP tells a model, and the admin shows for the action. summary: 'Close a deal as won or lost, by its id. A deal closes once; closing it again is AlreadyClosed.', effect: 'write',}) {FamilyContext<Actor> is the context type a use case receives, and CallContext<ActorInput> the one a caller passes. Family<Actor, TenantFields, ActorInput> is the family’s type; TenantFields is the keys of tenantOf, and ActorInput defaults to Actor.
The framework
Section titled “The framework”framework({ family, errors? }) starts a definition, and .collection() adds each collection with its access rules, and its methods and overrides. The definition holds no ports, so a client or a codegen script imports contract without the server.
import { framework } from '@latticecms/core';import { LogActivity } from '../../app/use-cases/activities/log-activity.js';import { AppUseCase } from '../../app/use-cases/context.js';import { ArchiveDeal } from '../../app/use-cases/deals/archive-deal.js';import { CloseDeal } from '../../app/use-cases/deals/close-deal.js';import { CreateDeal } from '../../app/use-cases/deals/create-deal.js';import { UpdateDeal } from '../../app/use-cases/deals/update-deal.js';import { Activities } from '../../domain/collections/activities.js';import { Companies } from '../../domain/collections/companies.js';import { Contacts } from '../../domain/collections/contacts.js';import { Deals } from '../../domain/collections/deals.js';import { Memberships } from '../../domain/collections/memberships.js';import { Organizations } from '../../domain/collections/organizations.js';import { Tasks } from '../../domain/collections/tasks.js';import { clientErrors, toRpcError } from './errors.js';
/** Any signed-in caller may do this. The edge has already checked the actor. */const anyone = () => true;
// An archived deal is hidden from every read and can no longer change.const live = () => ({ archived: { eq: false } });
// A closed deal can no longer change either. Like an archived one, it// answers update with NOT_FOUND. It closes through deals.close, which// refuses a second close as AlreadyClosed.const editable = () => ({ archived: { eq: false }, closedAt: { exists: false },});
/** The CRM's API: seven collections, three overrides and two methods. No ports. */export const crm = framework({ family: AppUseCase, errors: { declared: clientErrors, map: toRpcError },}) .collection(Companies, { access: { read: anyone, create: anyone, update: anyone, delete: anyone }, }) .collection(Contacts, { access: { read: anyone, create: anyone, update: anyone, delete: anyone }, }) .collection(Deals, { access: { read: live, create: anyone, update: editable, delete: live, close: live, }, // A member sees every deal of the organization, without its amount. fields: { amount: { read: ({ actor }) => 'support' in actor || actor.role === 'manager', }, }, methods: { close: CloseDeal }, // A deal closes only through deals.close: create and update refuse to. // Create also numbers the deal. overrides: { create: CreateDeal, update: UpdateDeal, delete: ArchiveDeal }, }) .collection(Activities, { // Any member reads the timeline. Only the author changes or removes an // activity, as a filter: another member's is NOT_FOUND. No create: log // is the only way in, so the author is always the caller. operations: ['find', 'count', 'countBy', 'get', 'update', 'delete'], access: { read: anyone, update: ({ actor }) => ({ authorId: { eq: actor.userId } }), delete: ({ actor }) => ({ authorId: { eq: actor.userId } }), log: anyone, }, methods: { log: LogActivity }, }) .collection(Tasks, { access: { read: anyone, create: anyone, update: anyone, delete: anyone }, }) .collection(Memberships, { // A member reads the memberships of the organization it acts in: its // team, for a team list or an owner picker. Support reads every one. // An organization switcher uses /auth organizations instead, since /rpc // needs an organization first. Only trusted code writes them. operations: ['find', 'count', 'countBy', 'get'], access: { read: ({ actor }) => 'support' in actor ? true : { organizationId: { eq: actor.organizationId } }, }, }) .collection(Organizations, { // A member reads the organization it acts in, and support every one. // Only trusted code writes them. operations: ['find', 'count', 'countBy', 'get'], access: { read: ({ actor }) => 'support' in actor ? true : { id: { eq: actor.organizationId } }, }, });
/** What clients and codegen import. */export const contract = crm.contract;
export { Activities, AppUseCase, Companies, Contacts, Deals, Memberships, Organizations, Tasks,};framework({ family, errors? }) starts a definition. errors is the app’s { declared, map }; an app with no domain errors leaves it out.
.collection(C, { access, operations?, fields?, methods?, overrides? }) adds a collection. Its slug becomes a contract slice with find, count, countBy, get, create, update and delete, or only the operations it lists. access is required; see Access.
-
operations: ['find', 'get']exposes only those generated operations; see Exposing fewer operations. -
fields: { amount: { read } }gives each maskable field its read rule, and is required exactly whenChas one; see Field masking. -
methods: { name: Class }adds a procedure.overrides: { action: Class }replaces a generated one. -
Each class must name
Cand its token, and itsexecutemust take and return the procedure’s types. A mismatch, a reserved name, or a slug added twice is a compile error and a runtime throw. -
A slug, relation or method may not be one of
reservedNames:$context,use,useAfter,middlewareandrouter, the ts-pf implementer’s own keys. A relation or method may not beupserteither, which Lattice keeps for a generated operation (Reserved names). -
A method without
summaryandeffect, and an override with either, is a compile error and a runtime throw. The error names the method or override. A blanksummarythrows.
.contract is the ts-pf contract, built once on first read. Contract<E, D> is its type.
Exposing fewer operations
Section titled “Exposing fewer operations”operations lists the generated operations that clients can call. Leave it out to expose all seven. An operation nobody may call is better left out than refused: it costs no types, no MCP tool and no OpenAPI path. The crm’s activities, above, have no generated create, since an activity is created only with log.
-
An operation left out does not exist for a client. It is not in the contract,
useCases, the catalog, OpenAPI, MCP or the admin. Over HTTP it is the same404as an unknown procedure. On a local client the property is missing. -
A relation’s
listis exposed withget, and itssetwithupdate: the operations whose access they run. -
operations: []exposes only the methods. With no methods either, the collection has no slice. It is still registered. -
accesstakesread,create,update,deleteand the methods, whatever the list. Any other key is a compile error. Access says who may do a write by any path; the list says which procedures clients can call. A method or override that writes through a repo runs the write’s rule withctx.access.scope(C, 'create', data), whether or notcreateis listed.readruns for populating a ref to the collection, too. -
An override of an operation that is left out is a compile error and a throw at
.collection(). So is a name that is not a generated operation. -
Repos, refs, population,
onDelete, events, methods and scopes do not change. A scope for an action with no access function isFORBIDDEN, listed or not. A cascade deletes a collection’s rows whether or not it exposesdelete. Method names still may not be any generated operation’s name. -
The list is a literal. Inline, it is one. Declare a shared list with
as const:import type { Action } from '@latticecms/core';const reads = ['find', 'count', 'countBy', 'get'] as const satisfies readonly Action[];api.collection(Notes, { access: { read }, operations: reads });api.collection(Tags, { access: { read, update }, operations: [...reads, 'update'] });A list typed
Action[], or chosen with a condition, is a compile error: its type would hold more than the value, so a client could compile a call that is a404. So is a list passed through a generic helper, whose type Lattice cannot see; call.collection()with the list itself.
Leaving an operation out removes its types too, such as Contract['notes']['get']. Use the output of an operation that is still exposed. If there is none, Doc<C> is the stored document and ClientDoc<C> the one a client receives. Neither has populated refs. Browser code imports them with import type.
Object.keys(api.contract.notes) gives what notes exposes at runtime: its operations, methods and relations. A collection that exposes nothing is not a key of the contract. To test what an app exposes, see Testing what a collection exposes.
build()
Section titled “build()”build() wires the definition to a store, and a publisher or an outbox. The method and override instances get the typed repos and transaction, and the overrides the generated operations they replace.
import type { CollectionStore, Outbox } from '@latticecms/core';import type { DomainEventPublisher } from '../app/ports/events/domain-event-publisher.js';import { LogActivity } from '../app/use-cases/activities/log-activity.js';import { ArchiveDeal } from '../app/use-cases/deals/archive-deal.js';import { CloseDeal } from '../app/use-cases/deals/close-deal.js';import { CreateDeal } from '../app/use-cases/deals/create-deal.js';import { UpdateDeal } from '../app/use-cases/deals/update-deal.js';import type { DomainEvents } from '../domain/events/domain-events.js';import { crm } from './rpc/contract.js';
export type AppPorts = { readonly store: CollectionStore; /** The outbox in the servers. A publisher in the scripts and most tests. */ readonly events: DomainEventPublisher | Outbox<typeof DomainEvents>;};
/** The implemented router, use cases and repos over these ports. */export function createApp({ store, events }: AppPorts) { return crm.build({ store, events, methods: ({ transaction }) => ({ deals: { close: new CloseDeal({ transaction }) }, activities: { log: new LogActivity({ transaction }) }, }), overrides: ({ repos, generated, transaction }) => ({ deals: { create: new CreateDeal({ transaction }), update: new UpdateDeal({ update: generated.deals.update }), delete: new ArchiveDeal({ deals: repos.deals }), }, }), });}
export type CrmApp = ReturnType<typeof createApp>;build({ store, events, access?, methods?, overrides? }) wires the definition and returns:
| Output | What it is |
|---|---|
app |
The implemented ts-pf router, for FetchHandler and createLocalClient |
useCases |
The hexok instance that serves each procedure: generated, override or method, each typed precisely. Server code: it returns whole documents, unmasked. A second gateway that serves clients from it must call through createLocalClient(app), or withhold maskable fields itself |
repos |
A Repo<C> per collection: the objects the factories received |
transaction |
transaction(async ({ repos, events }) => …): runs repo writes, and the events they cause, as one unit. See Transactions |
onError |
onError(logger) for FetchHandler |
clientError |
clientError(error): the error a client receives for a LatticeError, as the procedures send it, or undefined for any other. See Errors |
context |
context({ actor, logger }): the context for a direct useCases.*.execute call |
ensure |
ensure(): creates the outbox’s index if the app has one, then each collection’s declared indexes, in definition order. It never drops one |
methodsandoverridesare factories,({ repos, transaction }) => instances, keyed by slug and then name. Each is required exactly when a collection declared one.overridesalso receivesgenerated; see An override that adds a rule.accessreplaces the functions given at.collection()with anotherAccessadapter.appadds a freshaccessto each call’s context. A direct caller gets one fromcontext(). Access answers are kept on the context, so make one per call or per job.eventsis a publisher oroutbox(catalog). It must take every collection’s events. One that cannot is a compile error that names each refused token. When it may be either, both are checked.- Await
ensure()after the store has started, after migrations and before serving, as the CRM’sserver.tsdoes.ensure()never drops or changes an index. To change one, a migration drops the old one, thenensure()creates the declared one. An existing index that differs from the declared one makesensure()throw, naming the collection and the fields; the store’s README says how it matches them. A migration that needs an index to run fast creates that index itself. Framework<Actor, D, E, TenantFields, ActorInput>is the definition’s type. Name it by reference, astypeof app; its parameters are not part of the API.
An override that adds a rule
Section titled “An override that adds a rule”An override that only adds a rule checks the input, then returns the generated operation through generated. The crm’s deals close only through deals.close, so its create and update refuse a won or lost stage, then do what the generated ones do. Update’s is only that:
export class UpdateDeal extends AppUseCase('deals.update', { collection: Deals,}) { constructor( private readonly deps: { update: ( ctx: AppCtx, input: UpdateInput<typeof Deals>, ) => Promise<Doc<typeof Deals>>; }, ) { super(); }
async execute( ctx: AppCtx, input: UpdateInput<typeof Deals>, ): Promise<Doc<typeof Deals>> { refuseClosing(input); return this.deps.update(ctx, input); }} overrides: ({ repos, generated, transaction }) => ({ deals: { create: new CreateDeal({ transaction }), update: new UpdateDeal({ update: generated.deals.update }), delete: new ArchiveDeal({ deals: repos.deals }), }, }),generated.<slug>.<operation>(ctx, input)runs that generated operation: it parses the input, takes the call’s access scope, runs the hooks, writes, and publishes the event. A relation’s isgenerated.<slug>.<relation>.<op>. It holds only the operations the app overrides:generated.deals.updateexists because deals overrides update, andgenerated.companies.createdoes not.- Each body checks what its own action needs: create’s access, with the data it writes; a field withheld from the caller in an update patch, in a read’s
whereorsort, or as countBy’sfield; and a read’spopulatekeys. So a call from another override, such as a create override that callsgenerated.deals.update, skips nothing. - It runs no guards, logging or spans. The override’s own use case has run them, so they run once, and the access function runs once.
- A create body takes the collection’s server fields as a third argument.
- It is typed as a direct caller sees the generated use case: it takes the schema’s input type and returns the stored document. The router masks the override’s result, as it masks every result.
- An override that changes what the operation does, such as
ArchiveDeal, writes throughreposinstead, and publishes its own events.
The server starts the store, runs the migrations, creates the indexes, then serves:
const crm = createApp({ store, events: deps.events });await store.start();await migrate(store, migrations, { logger });await crm.ensure();A client needs no annotations. Input, output and declared errors come from the contract, so the client narrows on the app’s AlreadyClosed and its data:
const deal = await local.deals.create({ title: 'Big one', companyId: 'c1', amount: 1000,});
const won = await local.deals.close({ id: deal.id, outcome: 'won' });expect(won).toMatchObject({ stage: 'won', closedAt: expect.any(String) });const again = await asResult( local.deals.close({ id: deal.id, outcome: 'lost' }),);if (again.ok) throw new Error('expected AlreadyClosed');if (again.error.code !== 'AlreadyClosed') throw new Error(again.error.code);expectTypeOf(again.error.data).toEqualTypeOf<{ id: string }>();expect(again.error.data).toEqual({ id: deal.id });expect(again.error.status).toBe(409);Access
Section titled “Access”Access decides what a call may see and change. It is a filter in the query: Lattice never loads a row and then decides whether the caller may see it.
.collection(C, { access }) takes one function per action: read (find, count, countBy, get, and populating a ref to C), create, update, delete, and one per method. It takes every write whatever operations lists, because a method or override that writes through a repo runs the write’s rule; see Exposing fewer operations.
- Each function receives
{ actor }, typed by the family’s actor schema.createalso receivesdata, its parsed input, which has no server fields. read,update,deleteand a method returnbooleanor aWhereonC’s documents, or a promise of one.createreturnsboolean.trueallows every row.falserefuses the call withFORBIDDEN. AWherelimits the call to the rows that match: a row outside it isNOT_FOUNDon get, update and delete, andfindnever returns it.- A missing function denies.
access: {}denies everything. An override uses the function of the action it replaces. - A
Whereon a fieldClacks, a key that is not an action or a method, a write thatoperationsleaves out, and a method with no function are compile errors. - An access
Whereis ANDed with the caller’swhere, so a caller can only narrow it. - Lattice checks every access
Whereat runtime, from a function or from abuild({ access })adapter, before the query runs. An undefined value, a field with no operator, an unknown field or operator, or an operand of the wrong type throws anErrorthat names the path. The call fails, and the filter is never widened. So{ organizationId: { eq: actor.orgId } }with noorgIdfails closed, whatever the types said. An emptyoris allowed, and matches nothing.
A family guard checks access before every execute: generated operations, overrides and methods. The refusal is logged once. Each function runs once per call. Create’s function receives the parsed data. It runs again when that data differs: an override hands create’s body other data, or a direct caller’s input gets a default that differs per parse, such as a random id. The last answer is for the data create writes, before server values and beforeChange. Do not decide on such a default.
A hand-written use case gets its filter with ctx.access.scope(C, action), and passes the Scope to its repo calls. It may ask for another collection’s scope too, such as ctx.access.scope(Posts, 'find'). Create’s function also needs its data, parsed: ctx.access.scope(C, 'create', data), where data is C.clientInput.parse(input). scope does not parse it.
const scope = await ctx.access.scope(Deals, 'close');return this.deps.transaction(async ({ repos: { deals }, events }) => { // The condition is checked in the same write, so two closes cannot // both win: the second finds the deal closed and gets null. const closed = await deals.update( input.id, { stage: input.outcome, closedAt: new Date().toISOString() }, scope, { if: { closedAt: { exists: false } } }, );Hide rows with a read filter, such as soft-deleted ones. The CRM’s live filter above hides an archived deal from find and get, and keeps it from changing.
Access is the hexok port behind this. build({ access }) takes another adapter of it. Its check({ actor, collection, action, data? }) returns boolean or a Where; action is find, count, countBy, get, create, update, delete or a method’s name, and data is passed for create only. Its readable({ actor, collection, fields }) returns which of a collection’s maskable fields the actor may read; a field it leaves out is withheld, so an adapter that forgets one withholds it.
Tenancy
Section titled “Tenancy”A collection with tenant: 'organizationId' keeps each tenant’s rows apart. Lattice adds the field to the output, stamps it on create, and filters every call by the caller’s tenant. A collection without tenant is global: no call is filtered by tenant.
const AppUseCase = family({ actor: z.object({ userId: z.string(), organizationId: z.string(), support: z.boolean().optional() }), actorId: (actor) => actor.userId, tenantOf: { organizationId: (actor) => (actor.support === true ? tenancy.bypass : actor.organizationId), },});
const Notes = collection('notes', { schema: z.object({ title: z.string() }), tenant: 'organizationId',});family({ tenantOf })is a map from a tenant field to the function that gives the actor’s tenant for it. A collection whose tenant field has no entry is a compile error and a throw.- An entry returns a non-empty tenant id,
tenancy.bypassortenancy.none. Anything else fails the call. An entry’s answer for access is kept for the call; log lines ask again, so keep entries pure. - The tenant field is in
DocandWhere, never in create or update input. Create stamps it afterbeforeChange, update never writes it, and a client cannot set or change it. - In the output’s JSON Schema, and so in OpenAPI and MCP, the tenant field carries
x-lattice-tenant: true, so a client such as the admin shows it read-only. - Every scope is the tenant clause ANDed with the access
Where. Another tenant’s row isNOT_FOUNDon get, update and delete, andfindnever returns it, page after page. - A schema field with the tenant’s name, or a reserved name, is a compile error and a throw.
An app with two kinds of tenant, such as a marketplace, has an entry for each. An actor may have both, either or neither:
tenantOf: { organizationId: (actor) => actor.organizationId ?? tenancy.none, professionalId: (actor) => actor.professionalId ?? tenancy.none,},tenancy.none is for an actor with no tenant of that kind, such as an anonymous one. On TypeScript 5.9, write an entry that ignores the actor as (_actor) => tenancy.none: with no parameter, it does not compile there. Every valid call on that field’s collections is FORBIDDEN, methods and relations included, and no access function runs. Invalid input can still be VALIDATION. A populated ref into one is { id }. Other collections are unaffected. See Anonymous reads.
tenancy.bypass is for a platform actor, such as support staff. The actor schema validates the flag, and the edge sets it per request. A bypass covers the collections of its own field, not those of another.
- A bypassed call reads across the field’s tenants. It can filter
findby the tenant field. - It is read-only on those collections: generated create, update and delete are
FORBIDDEN, and so is a repo write through its scope. - Its log line carries
tenancy: 'bypass', and each bypassed scope writes onetenancy.bypassline with the actor, collection and action.
Server code says which tenant it works in. An event handler uses tenancy.scope(C, tenantId): the tenant clause and no access. An insert through it is stamped with that tenant. tenancy.scope takes only a tenanted collection, and throws on a tenantId that is not a non-empty string.
await repos.notes.update(id, patch, tenancy.scope(Notes, event.payload.tenantId));unscoped still reads and writes every tenant, but it cannot insert into a tenanted collection, since the row would belong to no tenant. That is a compile error and a throw.
Relations and population
Section titled “Relations and population”Refs and onDelete
Section titled “Refs and onDelete”ref(slug, { onDelete? }) marks a string field as the id of a document in another collection. It names the collection by its slug, so two collections can refer to each other. z.array(ref(slug)) is a list of ids.
const Projects = collection('projects', { schema: z.object({ name: z.string(), companyId: ref('companies', { onDelete: 'cascade' }), reviewerId: ref('users', { onDelete: 'nullify' }).optional(), }), tenant: 'organizationId',});- A ref is a string: Zod’s methods work on it, and
ref('users').max(64).optional()is still a ref. - A ref refuses an empty id with
VALIDATIONat its path: no document has one. The message is “Choose the company”, from the slug’s label, or “Choose one” when the label has no singular core can find, such aspeople. An optional ref may still be left out. - A slug that is not a collection of the framework is a compile error and a throw at
build(), and on.contract. Collections may be added in any order. - A write does not check that the referenced document exists. Deleting it is where refs are kept whole.
- Each ref gets an index in
ensure(), led by the tenant field, unless the collection declares one that starts with the same keys. An index withpresentdoes not count, because MongoDB does not use it for the lookup. When one has exactly the lookup’s keys, the lookup index addsid. - A ref’s JSON Schema says where it points, as
x-lattice-ref: 'companies': in inputs, outputs, the id branch of a populated field, each item of a list of ids, and a join collection’s ids. OpenAPI and MCP carry it, and the admin links and picks documents by it.
onDelete says what the generated delete of the referenced document does to the documents that refer to it:
onDelete |
When a referenced document is deleted |
|---|---|
restrict (default) |
The delete is refused with REFERENCED (409), { collection, id, by: { collection, field, relation? } }, while any document refers to it, even one the read filter hides, such as an archived row |
cascade |
The referring documents are deleted too, and their own refs are followed in turn. A cycle stops at a document already deleted. A list of ids cannot cascade |
nullify |
The ref is cleared: an optional field is removed, a nullable one set to null, and the id pulled from a list. A required ref cannot nullify |
- These are system steps: they skip access functions, because the caller was allowed to delete the parent. They stay inside the parent’s tenant, so another tenant’s row that stores this id is neither counted nor touched. A global parent’s children are found across tenants.
- Any
onDeletebetween two tenant fields throws atbuild(),restrictincluded, for amany()target too. The other field may hold another kind of id, so the parent’s tenant clause would match nothing: arestrictwould pass and leave the ref dangling. If both fields hold the same tenant id, use one field name. Otherwise store the id withoutref()ormany(), and do the work in a handler of<parent>.deleted. The handler finds the rows withunscoped, and writes each one undertenancy.scopewith that row’s own tenant. Writes do not check refs, so any tenant may have stored the id: the handler decides which rows to change. Repo writes publish no events, andRepo.removedoes not runonDelete, so the handler also does any work those rows need below them. - A cascade from a tenanted collection to a global one, directly or through other global ones, throws at
build()if any tenanted collection refers to that global one, whatever that ref’sonDelete. A global document has no tenant to pass on, so the last step would reach every tenant’s rows. Give each global collection on the path a tenant, or do not cascade along it. The check reads the declared refs, not access or overrides, so it also refuses an app where nobody may delete the tenanted document. - A cascade from a global document fails when it reaches a tenanted document whose tenant is missing or not a string, if a tenanted collection refers to that document’s collection. Otherwise the next steps would reach every tenant’s rows.
- Everything runs in one
store.transaction(), with the parent deleted last. Restrict is checked before anything is written. Each cascaded document emits itsdeletedevent and each nullified one itsupdatedevent. A publisher gets them after the commit, never inside it, and an outbox stores them in the transaction. A failure rolls the whole delete back, and nothing is published. restrictcounts rows the read filter hides. An archived child blocks its parent’s delete, because it can be restored. To let the parent go, override the parent’sdeleteto archive it too, or make an optional refnullify. A child collection that overridesdelete, as an archiving one does, cannotcascade.- A collection that overrides
deletecannot have a cascading ref: the cascade would hard-delete rows its override keeps, such as soft-deleted deals. It is a compile error and a throw at.collection(); userestrictornullify. onDeleteruns in the generated delete only. An override ofdelete, such as a soft delete, keeps the row, so its children stay valid; an override that removes rows handles their refs itself.Repo.removeis trusted and does not run it.
many() relations
Section titled “many() relations”many(target, { through, fields?, onDelete? }) relates each document to many of another collection, through a join collection Lattice derives:
const Posts = collection('posts', { schema: z.object({ title: z.string() }), tenant: 'organizationId', relations: { categories: many('categories', { through: 'post_categories', fields: z.object({ sortOrder: z.number().int().default(0) }), }), },});- The join collection is
Posts.relations.categories.through, with slugthrough. Its documents are{ postsId, categoriesId, ...fields }plus the system fields and the parent’s tenant field.postsIdcascades from the post;categoriesIdtakesonDelete(restrictby default, orcascade). A category the join restricts isREFERENCEDwithby: { collection: 'post_categories', field: 'categoriesId', relation: { collection: 'posts', name: 'categories' } }: the join collection is not in the catalog, sorelationnames the relation a client can show. It has its own events, which the app lists in its catalog like any collection’s, and it is inrepos(repos.post_categories), but it has no slice: links change only throughset. - It gets a unique index on the pair, and one on
categoriesId, both led by the tenant field. posts.categories.list({ id, where?, sort?, limit?, after? })pages the post’s links, with find’swhere,sortand cursor over the link documents. It runs the post’sreadaccess: a post outside it isNOT_FOUND.posts.categories.set({ id, links })replaces the post’s links: each link is{ categoriesId, ...fields }, at most 1000, and a target repeated isVALIDATION. It runs the post’supdateaccess. It diffs, in onestore.transaction(): links no longer listed are deleted, new ones inserted, and changed fields updated; an unchanged link keeps its id andcreatedAt. Each change emits its own join event, delivered as a delete’s events are. It returns the links in the order given. A tenant bypass cannot set.- Both are use cases in the family (
useCases.posts.categories.set), and can be overridden:overrides: { categories: { set: ReorderCategories } }. Withoperations,listis exposed withget, andsetwithupdate. - A relation name may not be a schema field, an operation,
read, a method, a ts-pf implementer key orupsert, andthroughmay not be another collection’s slug, start with_or end with_versions. A collection cannot relate to itself withmany(). A link field may not be named like the two ref fields, a reserved name or the tenant field. Method names may not contain a dot. Each is a compile error and a throw.
Population
Section titled “Population”A read takes populate, a list of what to replace with documents. The output type follows the list on every ts-pf client, and on useCases, through ts-pf’s expandable outputs:
const got = await local.contacts.get({ id: ada.id, populate: ['companyId'],});
expectTypeOf(got.companyId).toEqualTypeOf< Doc<typeof Companies> | Withheld>();With the Posts above, and an authorId ref to users:
const post = await client.posts.get({ id, populate: ['authorId', 'categories'] });post.authorId; // Doc<typeof Users> | Withheldpost.categories; // { sortOrder: number; doc: Doc<typeof Categories> | Withheld }[]const plain = await client.posts.get({ id });plain.authorId; // stringconst page = await client.posts.find({ populate: ['authorId'] });const links = await client.posts.categories.list({ id, populate: ['categoriesId'] });getpopulates ref fields andmany()relations.findpopulates ref fields only, so one page cannot fetch up to 1000 links per document; a relation onfindis a compile error andVALIDATION. A relation’slistpopulates its links’ refs, which is how a page of links gets its documents.- A ref populates as the target document. A list of ids populates element-wise. A nullable or optional ref keeps its
nullorundefined. A relation populates as its links, each{ ...fields, doc }, and is in the output only when populated. - A populated document the caller may not read, or one that no longer exists, is
Withheld:{ id }only. Narrow with a system field:'createdAt' in post.authorId. Every populated document has one, and no rule withholds it. A schema field can be maskable or optional, and differs between collections. - Each target collection is read once per call, with
getMany, for all the documents and fields that refer to it. It runs under the caller’sreadaccess there, which carries the tenant, and through itsafterRead. A relation’s links are read in onefindon the join collection, inside the parent’s tenant, under the parent’sread. - A
read: falseon a target does not fail the read: every document of that target is{ id }. - A target populates whatever operations it exposes, even none. Its
readaccess decides. - One level deep: a populated document’s own refs stay ids.
- A
populatelist held in aK[]variable gives the wide type, where each ref is the id or the document, because it could hold any subset. - An overridden
get,findorlistis plain: it takes nopopulate, because the override serves it and population runs in the generated read.
Server fields
Section titled “Server fields”serverFields names the fields only the server writes, such as a ticket’s number or a deal’s closedAt (0049):
// Set by create, delete and close. No client writes them. serverFields: ['number', 'archived', 'closedAt'],A server field is not in create or update input. One a client sends anyway is dropped, as an unknown key is. Everything else treats it as any field: clients read, filter, sort and count by it, and it can be indexed.
The server sets it in one of these ways:
| Set by | When |
|---|---|
The schema’s default, such as z.enum(statuses).default('draft') |
The generated create, Repo.insert, and a generated update of a document that lacks the field. Repo.update does not parse, so it fills in nothing |
| An override of create | generated.deals.create(ctx, input, { number }) |
beforeChange |
Create and update |
| A repo write | Repo.insert and Repo.update, in a method, an override or a handler |
- Give server values as the third argument. Never spread them into
input. It takes server fields only, and only create has it.executecan receive the caller’s raw object, which may hold a server field.generated.deals.createparsesinput, so it drops that field.repos.deals.insert({ ...input, number })would store any other server field in it, such asarchived. An override that writes through a repo names each field it takes frominput, such asrepos.deals.insert({ title: input.title, number }, scope), and never passes the rest on. Do not parse beforeinsert, which parses: a second parse may change a value that access approved. - Create’s access function receives the parsed input. An override of create that asks for the scope parses
inputonce, then gives the same data toctx.access.scopeand to the generated create. The server values are added after access is asked. beforeChangethen sees those values and may change them. It does not see a server field’s default on create.- After the hook, create checks the whole document against the schema. So a default fills a server field nothing set, and an object-level
.refine()can read one. A failed check isVALIDATION. The check changes only server fields: the rest are stored as the hook returned them. So on create an object-level.overwrite()does not change a client’s field. The check parses each client field again, so write each.overwrite()to give the same value when it runs twice. On update, the document is parsed before the hook and not after it. So a wrong server value the hook returns is stored, and the next update of that document fails. - A server field whose value is missing or invalid is a plain
Errorthat names the field and never its value, since no client can fix it. Over HTTP it isINTERNAL. Update also checks a stored one, so add a required server field with a migration that fills it. .collection()throws when it exposescreate, a server field is required, and there is no default, override ofcreateorbeforeChangeto set it.- On update, a
beforeChangethat returns only the fields it knows does not remove a server field. Returnundefinedfor an optional one to remove it. Return a changed object or list as a new one: a change made inside the old one is kept. - A collection that clients never create in can have server fields too. The crm’s activities have
serverFields: ['authorId']:activities.logsets the author, andactivities.updatecannot change it. - Server fields are not hidden. To withhold one from some callers, add it to
maskabletoo; see Field masking. To withhold it from every client, list it inhiddeninstead ofserverFields; see Hidden fields.
A new schema field is one that clients can write, unless serverFields lists it. To catch one that should be listed, test the fields that create takes, in a list written by hand:
expect(Object.keys(Tickets.clientInput.shape)).toEqual(['title', 'body']);The admin’s forms leave server fields out. For one that counts up, see Numbering documents.
Field masking
Section titled “Field masking”A collection names the fields a caller’s rules may withhold, with maskable. Composition gives each a read rule, in .collection(C, { fields }); see Masking by role. The rule receives { actor } and is asked once per call per collection.
export const Deals = collection('deals', { schema: z.object({ // The messages are what a form shows at the field. title: z.string().min(1, 'Enter a title'), // Counted up in each organization, from 1: see CreateDeal. number: z.int().positive(), // An archived deal still refers to its company, so it restricts too. companyId: ref('companies'), amount: z .number({ error: 'Enter an amount' }) .nonnegative('An amount cannot be negative'), stage: z.enum(dealStages).default('lead'), // deals.delete archives: the row stays, with archived set. archived: z.boolean().default(false), closedAt: z.iso.datetime().optional(), // The user who works the deal. A deal may be unassigned. ownerId: z.string().min(1).optional(), expectedCloseDate: z.iso.date().optional(), }), tenant: 'organizationId', // The people on a deal, and what each is to it. A contact on a deal // cannot be deleted: restrict, the default. relations: { contacts: many('contacts', { through: 'deal_contacts', fields: z.object({ role: contactRole }), }), }, // Set by create, delete and close. No client writes them. serverFields: ['number', 'archived', 'closedAt'], // Only managers and support see amounts: the contract's fields rule. maskable: ['amount'],- A withheld field is left out of what a client receives:
get,find,create,updateanddelete, a relation’slist, and documents populated into another collection’s read, under the caller’s rule for that collection. It is masked where every procedure returns to a client (HTTP,createLocalClient, MCP), so overrides and methods are masked too. - A client’s type has the field optional:
deal.amountisnumber | undefined, for every caller, since types cannot follow the actor.ClientDoc<C>names that document;Doc<C>stays the stored one. - A
whereor asorton a field the caller may not read, at any depth, onfind,countorcountBy, or countBy’sfield, isVALIDATIONnaming its path. So no filter, count, order or cursor reveals it. A caller who may read it filters and sorts as usual. - An
updatewhose patch names a field the caller may not read, with a value ornull, isVALIDATIONat its path:"amount" is not readable, so it cannot be changed. A caller cannot see what the write would destroy. The family’s guard checks it, so an override ofupdateis refused too.createstill takes the field, so a caller who may not read a required maskable field can create the document. A field inserverFieldstoo is in neither input, so one a client sends is dropped before this check. - A method that returns a collection’s documents declares
output: Deals.clientOutput, or a schema built from it (.extend(),.pick(),shape.amount). An output that holds a maskable field where it is required, such asDeals.output, throws atbuild(). - In an app with a maskable or hidden field, a client receives only the keys each output declares, as a Zod parse would give, so an output that leaves a field out never sends it. A union or an intersection keeps every key any branch declares. A record, or an object’s
.catchall(), keeps every key whose value its schema allows, so do not return a document throughz.record(z.string(), z.string()). A key anafterReadhook adds, or a stored field the schema no longer has, is cut unless the output declares it. The cut walks every output once and copies only the objects it changes, so afindpage whose documents hold such keys is copied on every read. An output Lattice cannot see through throws atbuild():z.lazy(), a transform,z.custom(),z.unknown(),z.any(),z.map(),z.set(), a recursive schema, or an object that passes unknown keys through (z.looseObject(),.loose(),.passthrough()). - Server code sees whole documents: repos, direct
useCases.*.executecalls and events’doc. A page rendered for a user calls throughcreateLocalClient. Masking for a webhook happens where the webhook maps the event. - In JSON Schema, and so in OpenAPI and MCP, the field is optional, with
x-lattice-maskable: trueand the description “Withheld when the caller may not read it.” Itswhereentry says “Refused (VALIDATION) when the caller may not read amount.”, and asortthat could name it says the same. Meta the app gave the field, such as atitle, stays.
Masking covers the named field only. These can still reveal it:
- An object-level
.refine()that reads a maskable field can fail a non-reader’s update depending on the hidden value. Don’t refine across a maskable field. - An access
Wherethat filters rows by a maskable field, such asread: () => ({ amount: { lt: 1000 } }), reveals a bound through which rows exist. - An
afterReadhook that derives another field from a masked one, or a method that computes a field of its own from it, is not masked.
Hidden fields
Section titled “Hidden fields”hidden lists fields no client reads or writes, such as the lists an access rule reads to decide who sees a row (0064):
const Talent = collection('talent', { schema: z.object({ name: z.string(), blocked: z.array(z.string()).default([]) }), hidden: ['blocked'],});
framework({ family: AppUseCase }).collection(Talent, { access: { read: ({ actor }) => ({ blocked: { nhas: actor.userId } }) },});- A hidden field is a server field: it is in
serverFields, and set as one is. It needs nofieldsrule. - It is left out of
ClientDoc<C>,CreateInput<C>, the client’swhere,sortand countByfield, and their JSON Schema. Awhere,sortorfieldthat names it anyway isVALIDATION, and a write that sends it drops it. - No client receives it: not from generated operations, methods, overrides or populated documents.
clientOutputholds it at runtime as an optionalnever, marked, so the mask removes it wherever an output declares it. An output that leaves it out, such asTalent.clientOutput.pick({ name: true }), cuts it with every other key the output does not declare. Its JSON Schema, and so OpenAPI and MCP, shows it as optional, never sent, withx-lattice-hidden: true. The admin leaves it out. Doc<C>, repos, directuseCases, events and accessWheres read it, as any field.- It cannot be a ref, and cannot also be maskable or a server field. It may be in a unique index: no client writes it.
- Use
maskablefor a field some callers may read. Its type stays in every client, optional, because types cannot follow the actor.
Events
Section titled “Events”collection() derives three hexok Event classes: Contacts.events.created, .updated and .deleted, with tokens contacts.created and so on. Payloads are { doc, actorId }, and { doc, previous, actorId } on update, typed from the schema. doc is the stored document. A tenanted collection’s payloads also carry tenantId.
The app lists them in its own catalog, next to its hand-written events:
export class DomainEvents extends EventCatalog('domain-events', { companiesCreated: Companies.events.created, companiesUpdated: Companies.events.updated, companiesDeleted: Companies.events.deleted, contactsCreated: Contacts.events.created, contactsUpdated: Contacts.events.updated, contactsDeleted: Contacts.events.deleted, dealsCreated: Deals.events.created, dealsUpdated: Deals.events.updated, dealsDeleted: Deals.events.deleted, activitiesCreated: Activities.events.created, activitiesUpdated: Activities.events.updated, activitiesDeleted: Activities.events.deleted, tasksCreated: Tasks.events.created, tasksUpdated: Tasks.events.updated, tasksDeleted: Tasks.events.deleted, membershipsCreated: Memberships.events.created, membershipsUpdated: Memberships.events.updated, membershipsDeleted: Memberships.events.deleted, organizationsCreated: Organizations.events.created, organizationsUpdated: Organizations.events.updated, organizationsDeleted: Organizations.events.deleted, dealContactsCreated: Deals.relations.contacts.through.events.created, dealContactsUpdated: Deals.relations.contacts.through.events.updated, dealContactsDeleted: Deals.relations.contacts.through.events.deleted, dealClosed: DealClosedEvent,}) {}- Generated writes publish through
build({ events }). A publisher gets the event after the store write succeeds: a publish failure reaches the caller, and the write stays. An outbox stores it with the write. Reads publish nothing. An override that callsgeneratedpublishes what the generated operation does. Other overrides and methods publish their own events. - A write through
repospublishes nothing. A use case that writes throughrepospublishes the collection’s events itself, such asPosts.events.created, withevents.publishin atransaction. - Collection events stay inside the product. Another product or a customer gets a mapping of its own: an integration event or a webhook. See A worker.
Tracing
Section titled “Tracing”Lattice traces through @opentelemetry/api. With no OpenTelemetry SDK registered, the API is a no-op, and that is the switch: there is no option. An app that registers an SDK, with a context manager such as @opentelemetry/context-async-hooks, gets these spans. Their tracer is @latticecms/core, at the package’s version.
| Span | Kind | Where | Attributes |
|---|---|---|---|
deals/find, one per procedure |
server | Lattice’s router middleware, on every caller: HTTP, createLocalClient, MCP |
rpc.system (ts-pf), rpc.service (deals), rpc.method (find; a relation’s is categories/list), lattice.outcome, lattice.code |
deals.find, one per use case |
internal | the family’s hooks, on every path, useCases too |
lattice.use_case, lattice.collection, lattice.action, lattice.actor_id, lattice.tenant_id or lattice.tenancy: 'bypass', lattice.outcome, lattice.code |
- The procedure span is active while the procedure runs. The use case span is its child, or the caller’s span’s on a direct
useCases.*.execute. - A store’s spans, such as MongoStore’s, are children of the active span: the procedure’s, or the caller’s. hexok has no hook around
execute, so the use case span cannot be made active: a store call is its sibling, not its child. lattice.outcomeisok,refusedorfailed. A refusal setslattice.codeand leaves the status unset: it is the caller’s, not a failure. On the use case span, a refusal is aLatticeErrorsuch asFORBIDDENorNOT_FOUND, aVALIDATION, or a member of a catalog infamily({ refusals }). On the procedure span, it is a declared code the client receives, unless the family recorded the error as a failure. An unexpected throw sets status ERROR anderror.type, the error’s name. It records no exception event, because an error’s message and stack can quote a value. The log line carries the error.- A guard’s refusal, and ts-pf’s own input check, happen before the use case’s hooks: they show on the procedure span only.
- A span carries no input, no document and no masked value: only names, ids, codes and outcomes.
To export these spans, register an SDK at startup; see Tracing with an SDK.
MCP and OpenAPI
Section titled “MCP and OpenAPI”Each generated procedure carries docs({ summary }) and mcp({ effect }) in its .meta(), so @ts-pf/openapi, @ts-pf/codegen and @ts-pf/mcp describe it with no code in the app. The summary names the collection by its label; see the reference.
| Procedure, when exposed | effect |
Summary, for deals |
|---|---|---|
find |
read |
Find deals. Filter with where, order with sort, and page with limit and after (the previous page’s next). populate expands companyId into documents. |
count |
read |
Count deals. Filter with where. |
countBy |
read |
Count deals by each value of one field, most first. Filter with where. |
get |
read |
Get one deal by id. populate expands companyId into documents. |
create |
write |
Create one deal. |
update |
write |
Update one deal by id. Send only the fields to change, and null to clear an optional one. |
delete |
destructive |
Delete one deal by id. |
a relation’s list |
read |
List the categories of one post, by its id. … |
a relation’s set |
destructive |
Replace the categories of one post, by its id. Links not given are removed. |
- The
populatesentence appears only when the read can populate. @ts-pf/mcpturnsreadintoreadOnlyHint: true, anddestructiveintodestructiveHint: true. The effect is a literal in the contract’s type too, soall(tk.deals, { effect: 'read' })selects in types what it selects at runtime.- A method’s meta comes from its
summaryandeffectstatics; see The family. An override keeps its procedure’s meta. - Every procedure also carries a
latticekey: its collection, the collection’s label, and its operation. A relation’slistandsetname the relation and itstargetcollection, and a method names itself:{ collection: 'deals', label: { singular: 'deal', plural: 'deals' }, operation: 'method', method: 'close' }.LatticeMetais its type. A client such as the admin reads it fromcatalog(), instead of guessing from a procedure’s path.
A maskable field says in its JSON Schema that it may be withheld, and that a query on it may be refused; see Field masking. A populated read has ts-pf’s x-ts-pf-expand in OpenAPI. The crm serves both; see Serving MCP and OpenAPI.
Recipes
Section titled “Recipes”Most recipes quote examples/crm, and name the file, or link to the root README’s Getting started. A test in the crm checks that each quote that names its file matches it, and the walkthrough runs Getting started as written.
The smallest edge
Section titled “The smallest edge”The root README’s Getting started has the smallest edge that keeps these rules: a fixed token from @hexok/auth’s StaticTokenAuthenticator, a membership check on every call, and the actor built only after both. A test runs it as written. The crm’s edge below is the same shape with sessions, support actors and MCP.
The auth edge
Section titled “The auth edge”Lattice never imports auth. The edge decides who the actor is, and passes it in the call context. In the crm, a @hexok/auth session proves the user, and a membership lookup checks the organization the request names, on every request:
export async function signedIn( deps: HttpDeps, request: Request, logger: Logger, edge: Edge,): Promise<{ readonly userId: string; readonly token: string } | undefined> { const refused = (reason: string) => { logger.info(edge, { outcome: 'refused', code: 'UNAUTHORIZED', reason }); return undefined; }; const token = bearerToken(request.headers.get('authorization')); // The reason hexok's sessions give for no token. if (token === undefined) return refused('missing'); const found = await deps.sessions.authenticate(token); if (!found.ok) return refused(found.code); return { userId: found.value.userId, token };}export function actorContext(deps: HttpDeps) { const memberships = deps.crm.repos.memberships; return async ( userId: string, request: Request, logger: Logger, edge: Edge, ): Promise<CallContext<ActorInput>> => { if (deps.support.has(userId)) { return { actor: { userId, support: true }, logger }; } const organizationId = request.headers.get(organizationHeader); // Trusted edge code: it decides who the actor is, so no actor's access // applies yet. A missing organization and one that does not exist look // the same as one the user is not a member of. const [member] = organizationId === null ? [] : ( await memberships.find( { where: { userId: { eq: userId }, organizationId: { eq: organizationId }, }, limit: 1, }, unscoped, ) ).docs; if (organizationId === null || member === undefined) { logger.info(edge, { outcome: 'refused', code: 'FORBIDDEN', reason: organizationId === null ? 'no-organization' : 'not-a-member', }); throw deps.crm.clientError(LatticeError.FORBIDDEN()); } return { actor: { userId, organizationId, role: member.role }, logger }; };}FetchHandler serves the app at /rpc with that context, and onError from build() logs what the family did not:
const onError = deps.crm.onError(deps.logger); const api = new FetchHandler(deps.crm.app, { onError }); const auth = new FetchHandler(createAuthRouter(deps), { onError }); const contextOf = actorContext(deps); const apiContext = async (request: Request) => { const logger = deps.logger.child({ requestId: requestIdOf(request) }); const user = await signedIn(deps, request, logger, 'rpc'); if (user === undefined) throw deps.crm.clientError(LatticeError.UNAUTHORIZED()); return contextOf(user.userId, request, logger, 'rpc'); };| Case | Answer |
|---|---|
| No token, a bad or expired one, or an ended session | 401 UNAUTHORIZED, one body for all |
| No organization header, not a member, or no such organization | 403 FORBIDDEN, one body for all |
| A support user | Reads every organization, changes nothing |
The reason is logged, never sent. A switched or revoked membership takes effect on the next request, because the check runs on each one.
Anonymous reads
Section titled “Anonymous reads”A public page, such as a job board, has callers with no account. Give them an actor of their own, and keep what they read in a global collection:
const member = z.strictObject({ userId: z.string(), organizationId: z.string() });const anonymous = z.strictObject({ anonymous: z.literal(true) });
const AppUseCase = family({ actor: z.union([member, anonymous]), actorId: (actor) => ('anonymous' in actor ? 'anonymous' : actor.userId), tenantOf: { organizationId: (actor) => ('anonymous' in actor ? tenancy.none : actor.organizationId), },});
const Jobs = collection('jobs', { schema: z.object({ title: z.string(), notes: z.string() }), tenant: 'organizationId',});
/** What anyone may read of a job. A row has its job's id. */const PublicJobs = collection('public_jobs', { schema: z.object({ title: z.string() }),});
const lattice = framework({ family: AppUseCase }) .collection(Jobs, { access: { read: () => true, create: () => true } }) .collection(PublicJobs, { access: { read: () => true } });- The edge passes
{ anonymous: true }only when the request has no credential. A bad or expired one is still 401. - Every call an anonymous actor makes on
jobsisFORBIDDEN, even though itsreadis() => true. - Check the access of every global collection. It has no tenant to refuse an anonymous actor, so
read: () => trueopens it to everyone. This includes its methods. public_jobshas nocreate,updateordeleteaccess, so only server code writes it. An event handler on the job’s events copies the public fields, withunscoped.repos.public_jobs.insert(data, unscoped, { id })gives the row its job’s id.- Do not return
tenancy.bypassfor an anonymous actor. Only each collection’s access would stand between it and every tenant’s rows. - Limit the request rate in front of the app.
Login on its own router
Section titled “Login on its own router”Sign-in is not a Lattice procedure: every Lattice procedure has an actor, and a caller signing in has none yet. The crm serves it at /auth, beside /rpc, as a plain ts-pf router, with sign-out and the caller’s organizations:
export const authContract = router({ login: procedure .input(loginInput) // The user's id too, so a client can find its own membership and tasks. .output(z.object({ token: z.string().min(1), userId: z.string().min(1) })) .errors({ UNAUTHORIZED: { status: 401, message: 'The credentials are not valid' }, }), logout: procedure.input(z.object({})).output(z.null()), /** * The organizations the signed-in user is a member of, by name, for an * organization switcher. It needs a session and no organization header: * the caller has not picked one yet. Support acts in none, so it gets none. */ organizations: procedure .input(z.object({})) .output(z.array(z.object({ id: z.string(), name: z.string() }))) .errors({ UNAUTHORIZED: latticeErrors.UNAUTHORIZED }),}); login: impl.login.handler(async ({ context, input }) => { try { const { userId } = await deps.login.execute( { logger: context.logger }, input, ); return { token: await deps.sessions.open({ userId }), userId }; } catch (error) { if (!LoginError.is(error)) throw error; throw new PFError({ code: 'UNAUTHORIZED', status: 401, message: error.message, cause: error, }); } }),- The
Loginuse case checks the password and the lockout; the router opens the session. The use case never sees a token. organizationslists the signed-in user’s organizations,{ id, name }, sorted by name, for an organization switcher. It needs a session and no organization header, since the caller has not picked one yet. It runs the edge’s own session check, and reads memberships and organizations through their repos as trusted edge code, as the membership check does. Support gets none.- Password hashes and failed attempts live in store collections Lattice never registers,
credentialsandlogin_attempts, so no procedure, MCP tool or OpenAPI document can reach them. - The crm’s README gives the hashing and lockout rules.
Mounting beside other routers
Section titled “Mounting beside other routers”build().app is a ts-pf router whose context is CallContext<ActorInput>. It nests in a router whose context has at least that. A router with no context can sit beside it there, but one handler then serves both, and builds an actor for every call to either.
A router with no context cannot hold the app. With the implementer’s router(), that is a compile error. Do not cast it away: the app’s calls would have no actor. A plain object of routers has no such check. Give each its own FetchHandler and prefix, and check matched after each, as the crm does for /rpc and /auth in handler.ts. If you do give a handler a plain object, set its context type: FetchHandler<CallContext<ActorInput>>.
- Use prefixes where none starts with another, such as
/rpcand/auth. Once its prefix matches, a handler answers every request under it, with a 404 for a procedure it does not have and a 405 for a method it does not take. It never passes one on. - If one prefix is inside another, try the longer one first. With
/rpcfirst,/rpc/public/pingis a 404 from the app. With/rpc/publicfirst, it reaches the public router. A procedure of the app underpublicis then never reached. - A prefix matches whole path segments, so
/rpcdoes not match/rpcx.
Numbering documents
Section titled “Numbering documents”A number such as a ticket’s or a deal’s is a server field that counts up in each tenant. repos.deals.next('number', scope) returns the next one: 1, then 2, and so on. Two calls get the same number only if the counter went back, such as after a rollback, a failover or a restore. The crm’s create takes one, and gives it to the generated create as its third argument:
constructor( private readonly deps: { transaction: Transaction< { deals: Repo<typeof Deals> }, { deals: { create: ( ctx: AppCtx, input: CreateInput<typeof Deals>, server: { number: number }, ) => Promise<Doc<typeof Deals>>; }; } >; }, ) { super(); } async execute( ctx: AppCtx, input: CreateInput<typeof Deals>, ): Promise<Doc<typeof Deals>> { refuseClosing(input); // A direct call's input is raw. Access and create get the same data. const data = Deals.clientInput.parse(input); const scope = await ctx.access.scope(Deals, 'create', data); return this.deps.transaction(async ({ repos: { deals }, generated }) => { const number = await deals.next('number', scope); return generated.deals.create(ctx, data, { number }); }); }new CreateDeal({ transaction }) takes the overrides factory’s transaction, as in build(). The repos and generated that its work receives are both in the transaction.
nexttakes the name of a server field. Each field counts on its own. A global collection has one counter for each field, and takesunscopedtoo.nextstores nothing in a document. Write the number in the field.- In an override of create, take the scope from
ctx.access.scope(Deals, 'create', data), with the parsed data. Areadscope refuses a caller who can create and not read.nextthrough a bypass isFORBIDDEN, as a write is. - Use the transaction’s repos. Then a create that fails gives its number back. A call outside a transaction, or on a store without them, leaves a gap when the insert fails. After a rollback, another call can get the same number, so do not use it outside the database, such as in an email or a file name, until the transaction commits. On MongoDB, a failover can undo any write or commit that no majority has confirmed, a
nextincluded: see write concern. - Keep a unique index on the tenant field and the number, such as
{ fields: { organizationId: 1, number: 1 }, unique: true }.nextdoes not look at the documents: the index refuses a number written without it. - Every insert takes its number from
next, seeds, scripts and tests included. One that writesnumber: 1itself does not move the counter, so the firstnextis also 1, and that create is aCONFLICT. Trying again cannot fix a counter that was never started: each rollback gives the number back, so the next try gets the same one. - Never run code that numbers another way beside code that uses
next. The old code does not move the counter. Stop the old version before the new one writes. If you roll back and the old code writes documents, stop writes and start the counters again before you return tonext. Do that in a new migration:migrate()does not run an applied one again. - Transactions that count on the same counter at the same time wait for each other or run again. Keep slow work, such as an HTTP call, out of them. Where gaps are allowed, call
nextbefore the transaction. - To number documents that exist, or to start a counter above 1, write a migration. The store’s README has both:
@latticecms/store-mongo.
A method that takes a file
Section titled “A method that takes a file”Lattice has no file field. The app owns a storage port, which signs URLs and checks, copies and removes objects. A collection holds each file’s metadata, so access and tenancy cover it. Upload with a presigned URL by default, and always when a guest or an anonymous caller can upload. A small file from a signed-in caller can be a method’s input instead.
A presigned upload
Section titled “A presigned upload”prepare signs a URL that the client PUTs the file to. confirm checks the stored bytes and makes the file ready. AppUseCase is the app’s family, and AppCtx is UseCase.Ctx<typeof AppUseCase>. Its actor has a userId and an organizationId.
import { randomUUID } from 'node:crypto';import { collection, framework, LatticeError, type Repo,} from '@latticecms/core';import { Port } from 'hexok';import { z } from 'zod';import { type AppCtx, AppUseCase } from './app-use-case.js';The storage port:
export abstract class FileStorage extends Port('FileStorage') { /** A URL that takes PUTs to `key`, for a few minutes. */ abstract signPut(key: string): Promise<string>; /** A URL that downloads `key` as an attachment, with this name and type, for a few minutes. */ abstract signGet( key: string, file: { name: string; type: string }, ): Promise<string>; /** The object's size and first 4 KB, as stored, or null when there is none. */ abstract inspect( key: string, ): Promise<{ size: number; start: Uint8Array } | null>; /** * Copies the bytes of `from`, and none of its metadata. Does nothing when there is no `from`. * Sends one request and never retries it: a late first attempt could change a checked copy. */ abstract copy(from: string, to: string): Promise<void>; abstract put(key: string, bytes: Uint8Array): Promise<void>; abstract remove(key: string): Promise<void>;}export const Files = collection('files', { schema: z.object({ name: z.string().min(1).max(200), uploaderId: z.string(), status: z.enum(['pending', 'ready']), key: z.string(), // Read from the stored bytes, once the file is ready. type: z.string().optional(), size: z.number().int().optional(), }), tenant: 'organizationId',});const nameInput = z.object({ name: z.string().min(1).max(200) });
export class PrepareFile extends AppUseCase('files.prepare', { collection: Files, input: nameInput, output: z.object({ id: z.string(), url: z.string() }), summary: 'Start an upload. PUT the file to the url, then confirm it by its id.', effect: 'write',}) { constructor( private readonly deps: { files: Repo<typeof Files>; storage: FileStorage }, ) { super(); }
async execute(ctx: AppCtx, { name }: z.output<typeof nameInput>) { const scope = await ctx.access.scope(Files, 'prepare'); const key = `staged/${randomUUID()}`; const url = await this.deps.storage.signPut(key); const { id } = await this.deps.files.insert( { name, key, uploaderId: ctx.actor.userId, status: 'pending' }, scope, ); return { id, url }; }}The type a client declares, in the PUT or anywhere else, is only a claim. confirm reads the type from the first bytes, and allows only the types it lists:
const signatures = [ { type: 'application/pdf', bytes: [0x25, 0x50, 0x44, 0x46, 0x2d] }, { type: 'image/png', bytes: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], }, { type: 'image/jpeg', bytes: [0xff, 0xd8, 0xff] },];
/** The type the first bytes show, or undefined when it is not allowed. */export function sniff(start: Uint8Array): string | undefined { return signatures.find(({ bytes }) => bytes.every((byte, i) => start[i] === byte), )?.type;}const maxSize = 20 * 1024 * 1024;
export class ConfirmFile extends AppUseCase('files.confirm', { collection: Files, // Only the id. A client could forge a type or a size. input: z.object({ id: z.string() }), output: Files.clientOutput, summary: 'Finish an upload, by its id. Refuses a missing or large file, and a type that is not allowed.', effect: 'write',}) { constructor( private readonly deps: { files: Repo<typeof Files>; storage: FileStorage }, ) { super(); }
async execute(ctx: AppCtx, { id }: { readonly id: string }) { const { files, storage } = this.deps; const scope = await ctx.access.scope(Files, 'confirm'); const file = await files.get(id, scope); if (file === null) throw LatticeError.NOT_FOUND({ collection: Files.slug, id });
// Refuse a bad file before copying it. await this.check(file.key); // The client can still write to file.key, so keep a copy that it cannot // write to, and check that. Each call has its own copy. const key = `files/${randomUUID()}`; await storage.copy(file.key, key); const checked = await this.check(key);
const ready = await files.update( id, { ...checked, key, status: 'ready' }, scope, { if: { status: { eq: 'pending' } } }, ); if (ready === null) { // Another confirm won, with its own copy. await storage.remove(key); throw LatticeError.NOT_FOUND({ collection: Files.slug, id }); } return ready; }
private async check(key: string) { const object = await this.deps.storage.inspect(key); if (object === null) throw refused('No file was uploaded'); const type = object.size <= maxSize ? sniff(object.start) : undefined; if (type === undefined) { await this.deps.storage.remove(key); throw refused('The file is too large, or its type is not allowed'); } return { type, size: object.size }; }}
const refused = (message: string) => LatticeError.VALIDATION({ issues: [{ path: ['id'], message }] });The client’s URL works until it expires, even after confirm. So a check of the uploaded object proves nothing about what is there later. confirm copies it to a key that no client has a URL for, and checks the copy.
A computer usually picks the program that opens a saved file by its extension. A file can pass the check and still be named resume.html, so a download takes its extension from the checked type:
const extensions = new Map([ ['application/pdf', '.pdf'], ['image/png', '.png'], ['image/jpeg', '.jpg'],]);
/** The client's name, with the extension of the type that was checked. */export function downloadName(name: string, type: string): string { const base = name .replace(/\.(pdf|png|jpe?g)$/i, '') // At most 240 bytes of UTF-8. Many file systems allow 255 in a name. .slice(0, 80) // A dot left in the name could be taken for an extension. .replace(/[^\p{L}\p{M}\p{N} _-]+/gu, '_') .trim(); return `${base || 'file'}${extensions.get(type) ?? ''}`;}export class DownloadFile extends AppUseCase('files.download', { collection: Files, input: z.object({ id: z.string() }), output: z.object({ url: z.string() }), summary: 'Get a short-lived URL that downloads a file, by its id.', effect: 'read',}) { constructor( private readonly deps: { files: Repo<typeof Files>; storage: FileStorage }, ) { super(); }
async execute(ctx: AppCtx, { id }: { readonly id: string }) { const file = await this.deps.files.get( id, await ctx.access.scope(Files, 'download'), ); if (file?.type === undefined) { throw LatticeError.NOT_FOUND({ collection: Files.slug, id }); } const { key, name, type } = file; // The extension decides what opens a saved file, so the client cannot set it. const download = { name: downloadName(name, type), type }; return { url: await this.deps.storage.signGet(key, download) }; }}const ready = () => ({ status: { eq: 'ready' } }) as const;
export const lattice = framework({ family: AppUseCase }).collection(Files, { // No create, update or delete: only the methods write. operations: ['find', 'count', 'countBy', 'get'], access: { read: ready, download: ready, prepare: () => true, // Only its uploader, and only while it is pending. confirm: ({ actor }) => ({ uploaderId: { eq: actor.userId }, status: { eq: 'pending' }, }), }, methods: { prepare: PrepareFile, confirm: ConfirmFile, download: DownloadFile, },});const { app } = lattice.build({ store, events, methods: ({ repos: { files } }) => ({ files: { prepare: new PrepareFile({ files, storage }), confirm: new ConfirmFile({ files, storage }), download: new DownloadFile({ files, storage }), }, }),});The client uses the presigned URL between the two calls:
const { id, url } = await client.files.prepare({ name: file.name });const put = await fetch(url, { method: 'PUT', body: file });if (!put.ok) throw new Error('The upload failed');await client.files.confirm({ id });// Later, for anyone who can read the file:const download = await client.files.download({ id });If the answer to confirm is lost, or it is NOT_FOUND, call get. A file that it returns is ready. If get is NOT_FOUND, call confirm again, and then get if you need to. If both stay NOT_FOUND, start again with prepare.
On MongoDB, set write concern majority on every client that writes these rows, scripts included, even if you run no cleanup jobs. When its update finds no pending row, confirm deletes its copy. Without majority, a failover can undo the write that the update lost to, and bring back a ready row that needs that copy. A failover can also undo a ready file that get returns, unless its store also has read concern majority. Such a read can be behind.
A browser also needs the bucket’s CORS rule to allow a PUT with a Content-Type header from the app’s origin.
Who can do what
- Everyone in the organization can download every ready file here. For private files, such as resumes, narrow
readanddownloadtogether. Keepstatusin the rule, or pending rows can be read, and let in the uploader, who callsgetafter a lost answer. With the same rule, a caller gets a URL only for a file they can read. The URL works for anyone who has it, until it expires. - Limit how often a caller can call
prepare, or how many pending files each can have. A PUT URL does not limit the size by itself. To limit it, havepreparetake the file’s size, asz.number().int().nonnegative().max(maxSize), and pass it tosignPut, which signs it asContent-Length. DeclaremaxSizeabovenameInput, and sendfile.sizefrom the client. The signed length is an exact size, not a maximum. Check thatcontent-lengthis in the URL’sX-Amz-SignedHeaders, and that your storage refuses a PUT of another size.confirmstill checks the size. - An anonymous caller has no user id for
confirmto match, so the upload comes before any identity.- To start, the server makes a random token, stores it with an expiry, and signs a PUT to a key bound to it. The server chooses the key, under a prefix that a lifecycle rule expires. Rate-limit this call at the edge.
- To submit, check the input and read the token before you copy anything. If the token is used, answer that the submission was already made, without its data. If it is missing or expired, refuse. Rate-limit this call too.
- Then copy the file from the key in the token’s row, and check the copy, as
confirmdoes. If that fails, the token still works. In onetransaction, mark the token used with a conditional write that also checks its expiry, and insert the row that has the new key. This needs a store with transactions. - If the conditional write finds no usable token, throw so that nothing is written. Delete the copy, and read the token again to choose the answer. After any other error, keep the copy: the write may have committed.
- Keep a used token for a while after it expires. If an answer is lost, a retry then learns that the submission was made, and the caller does not submit twice.
- The server sets the tenant, from the document that the submission is for, such as a job. Never take it from the input.
- If the key is not in this collection, put the copy under a different prefix. Otherwise the cleanup below deletes it.
What the storage adapter must do
- Keep the bucket private. A
keyis in what clients read, and is not a secret. copyreplaces the object’s metadata, and does not keep the client’sContent-Encoding. S3 keeps it by default, so setMetadataDirective: 'REPLACE'. Otherwise a browser can decode the download into bytes that nothing checked.copysends one request, and nothing retries it. The AWS SDK makes up to 3 attempts by default. If the first one’s answer is lost, it can finish after a retry’s copy was checked, and replace it with bytes that nothing checked. Givecopyits own client withmaxAttempts: 1. Do not setretryStrategy, which overridesmaxAttempts, orfollowRegionRedirects, which can send a second request. Nothing else may retry the request either, such as a proxy or a wrapper in the app. Ifcopythrows, never use its key again: the copy can still arrive. The next call makes a new key, asconfirmdoes. A brief storage error then failsconfirm, and the client can call it again. In a flow of your own, copy before you use up anything that works once, such as a token.copythrows if its result has no ETag. S3 can answer 200 with an error in the body, and the AWS SDK can miss it. With the SDK, throw ifCopyObjectResult.ETagis missing, and use a storage service that returns it. An ETag does not show which bytes were stored, so still check the copy.inspectis one ranged GET of the bytes as stored, not decoded by the HTTP client. ItsContent-Rangehas the object’s full size. S3 refuses a range of an empty object: return a size of 0 and no bytes. It also answers 403 for a missing object unless the app hass3:ListBucket. Grant that, and return null only for a 404.signGetsets two response headers.Content-Typeis the storedtype.Content-Dispositionis`attachment; filename*=UTF-8''${encodeURIComponent(name)}`. If the app serves the bytes itself, also sendX-Content-Type-Options: nosniff.- Test every method on the storage you use, and
signPutfrom a browser. Services that are compatible with S3 can differ. Some versions of the AWS SDK add the checksum of an empty body to a presigned PUT, and the upload then fails. On the client that signs, setrequestChecksumCalculation: 'WHEN_REQUIRED'. A signedContent-Typemust match the one the browser sends. - A conditional PUT is no substitute for the copy. A signed
If-None-Match: *refuses a second PUT only while the object exists, and only if the storage enforces it. After a delete, the same URL can write again. A PUT that started before the URL expired can finish after it. The client must send the header too, and the bucket’s CORS rule must allow it. A 412 can mean that the first PUT worked and its answer was lost. The client above throws on it, so handle a 412 before!put.ok, and callconfirm, which checks the object.
What the check does not show
- The first bytes show how a file starts, and no more. The rest can be anything, including a virus or a second format. Serve files only as attachments, except images as below, and scan them if people open them.
- To show images inline, use a fixed list of types, such as PNG and JPEG, and never HTML, SVG or PDF. Show only a checked copy, with its stored
typeasContent-Type, from an origin that is not the app’s. Sign its URL with a separate storage method. The server uses it only when the storedtypeis in the list, never because the client asks. If the app serves the bytes itself, sendnosniff. Everything else stays an attachment. - If any type is allowed, a file that
sniffdoes not know has no checked type. Incheck, remove and refuse a file overmaxSizefirst: there,undefinedmeans too large as well as unknown. Only then store an unknown type asapplication/octet-stream.UploadFilebelow must also store an unknown type asapplication/octet-stream. Always serve these files as attachments, and scan them.downloadNamegives them no extension, so they may not open directly. Do not put the client’s extension back: a file saved asinvoice.htmlopens as HTML. - Text has no signature. Check it only after
snifffinds nothing, and pass the object’ssizeto the check. Do not add it tosignatures: an entry with no bytes matches every file. Refuse an empty file and a NUL byte, then decode withnew TextDecoder('utf-8', { fatal: true }).decode(start, { stream: size > start.length }).streamallows a character cut off at 4 KB. This checks only those bytes, and HTML passes. Store it astext/plain, and add.txtfor it toextensions. - A zip’s first bytes do not say which format it is, such as DOCX, XLSX or ODT. Use a parser for the format. A zip’s directory is at its end, which
inspectdoes not read, so give the port a method that reads the checked copy. Limit how many entries the parser reads and how far each one expands. A DOCM, which can hold macros, is a zip too.
Cleaning up
- Expire
staged/with a lifecycle rule.confirmleaves the upload there when it succeeds. In a versioned bucket, expire the old versions there too, with a rule limited tostaged/. - Delete an old
pendingrow only if it is still pending.confirmhas no age limit, so its uploader can confirm it while the job runs.files.remove(id, unscoped, { if: { status: { eq: 'pending' } } })never removes a ready file. Aconfirmthat loses to it isNOT_FOUND, and deletes its copy. - An object under
files/can have no row, after a crash or an error. A copy or aputcan also arrive after it throws, even after a cleanup.confirmkeeps its copy whenupdatethrows, since the write may have committed. A job that deletes these must delete an object only if it is at least a day old and no row in any tenant has its key. Look the key up withunscoped: one tenant’s rows would make every other tenant’s files look unused. - Give each collection that holds keys its own prefix. If two share
files/, a job that checks one collection deletes the other’s files. Put no lifecycle rule on a collection’s own prefix, such asfiles/, except one that expires only noncurrent versions in a versioned bucket. - Give each database its own bucket, including each environment’s. A job sees only its own database’s rows, so in a shared bucket it deletes the other database’s files. A new prefix is not enough: every row holds its full key, and the code writes to
staged/andfiles/. A restored copy needs its own bucket too, with the objects under the same keys, before its app or jobs start. Give each app and its jobs credentials for only their own bucket. - The job that deletes objects is optional. Without it, unused files stay: they cost storage, and can hold personal data. With it, a needed file is deleted when its row is lost, removed by mistake, or out of date after a restore, such as
pendingagain with its oldstaged/key. Restoring the row does not bring the file back. Run the job only in a versioned bucket, and only with the rules above and the next two. Keep old versions underfiles/for at least the age of the oldest backup you may restore, plus the time a recovery can take, counted from when each one became old. The cleanup jobs and the adapter’sremovemust never name a version: that delete is permanent. Only erasing a file for good, below, does. Give it its own credentials, and give the app and its cleanup jobs no permission to delete versions. - Count the rows for each key:
files.count({ key: { eq: key } }, unscoped). Do not look up many keys with onefind: it returns 20 rows by default, so a key in use can look unused. A count cannot see a later write. So while the job can run, or an object that no row names can be erased, do not give a row a new key whose object is at least a day old. A method must finish writing the key to its row, retries included, within a day of making the object. The age of an upload instaged/does not matter. To put an old key back, first stop the job and any erase, and make sure that none is still running. Check that the object is a current one. Start them again only after the write succeeds, with write concernmajorityon MongoDB. After a restore, also follow the rules below. - On MongoDB, make that count in a transaction. Otherwise it can miss a row: a failover can still undo a removal or a key change that it sees. Every client that writes these rows needs write concern
majority, as above. Run the job’stransactionon a store with read and write concernmajority, even if the job writes no rows. Count with thereposthatworkreceives. No other repos join the transaction, so a count with them is not safe. Delete the object only after the transaction resolves with 0. If it throws, keep the object. The store’s README has the settings. - If rows are lost or wrong, stop everything that deletes files or rows, at once. Do the same before you restore a database in place, or as a copy that may replace it. For a copy, do it for both databases and both buckets, before you copy any files. Cancel both cleanup jobs, and do not let a run finish. Stop
confirmtoo: it can delete an upload, or change an out-of-date row’s key. Stop the outbox relay, and event handlers that delete files or rows. Before either starts again, deal with queued and failed events, and with the rows in a restored_outbox, which the relay publishes. These events may have run before, or be about changes that the restore undid. Turn off the buckets’ lifecycle rules, and leave them off in a new bucket. Keep every bucket and old version. A copy of a bucket usually has only its current objects. Start nothing again, lifecycle rules included, until every row you need in the database you keep has its current key and status, and its file is a current object in that database’s bucket. A check of onlyreadyrows misses one that ispendingagain. These rules are not a full restore procedure: write one for your storage, and test it. - To erase a file for good, delete all its versions by name, the current one included, and then its row. Its upload can stay in
staged/until the lifecycle rule has expired it and its old versions. Delete its copies in other buckets too. A failedconfirm,UploadFileor similar method can also leave an object that no row names, and it can arrive after the method fails. Before you delete one, check that it is at least a day old, that it has the same bytes, and that its row was not lost. Follow both count rules above to check that no row in any tenant has its key, even if you do not run the job. Keep a list of erased files outside the database. After a restore, erase any that came back, with their rows.
A small file in the input
Section titled “A small file in the input”A method can take a Blob. This one stores the bytes first, so its row never names an object that was not stored. The server makes the id, never the client. insert takes it as a given id, and the key uses it:
const uploadInput = z.object({ name: z.string().min(1).max(200), file: z.instanceof(Blob),});
export class UploadFile extends AppUseCase('files.upload', { collection: Files, input: uploadInput, output: Files.clientOutput, summary: 'Upload a small file.', effect: 'write',}) { constructor( private readonly deps: { files: Repo<typeof Files>; storage: FileStorage }, ) { super(); }
async execute(ctx: AppCtx, { name, file }: z.output<typeof uploadInput>) { const scope = await ctx.access.scope(Files, 'upload'); const bytes = new Uint8Array(await file.arrayBuffer()); // Not file.type, which the client sets. const type = sniff(bytes); if (type === undefined) { throw LatticeError.VALIDATION({ issues: [{ path: ['file'], message: 'Its type is not allowed' }], }); } const id = randomUUID(); const key = `files/${id}`; await this.deps.storage.put(key, bytes); return this.deps.files.insert( { name, key, type, size: bytes.length, uploaderId: ctx.actor.userId, status: 'ready', }, scope, { id }, ); }}Add upload: () => true to the collection’s access, upload: UploadFile to its methods, and upload: new UploadFile({ files, storage }) to the methods in build().
A file needs @ts-pf/file’s MultipartCodec on both the server and the client. FetchHandler, HandlerPlugin and RequestLimitPlugin are from @ts-pf/server-http, and PFError is from @ts-pf/protocol. Give the upload its own handler and prefix, such as /uploads, and only this procedure. Every other call then keeps its own smaller limit, and can be a stream procedure, which this codec cannot serve:
const maxFileSize = 2 * 1024 * 1024;
/** Refuses a caller with no session before the body is read. */const signedInOnly: HandlerPlugin = { name: 'signed-in-only', async onRequest({ request }) { if (await isSignedIn(request)) return undefined; throw new PFError({ code: 'UNAUTHORIZED', status: 401 }); },};
// Only this procedure. Any other is a 404, before its body is decoded.const uploads = new FetchHandler<CallContext<ActorInput>>( { files: { upload: app.files.upload } }, { codec: new MultipartCodec({ maxFiles: 1, maxFileSize }), plugins: [ signedInOnly, // The file, and room for the rest of the body. new RequestLimitPlugin({ maxBodySize: maxFileSize + 64 * 1024 }), ], },);Keep the CallContext<ActorInput>: a plain object of procedures has no context type of its own, so without it handle would take any context. uploads takes the same context as /rpc, which checks the session again and builds the actor. The client uses new FetchLink({ url: '/uploads', codec: new MultipartCodec(), headers }), only for this call. Give it the same headers or fetch as the /rpc link, with the organization if the app sends one. Without them, a caller with a bearer token is refused. Install @ts-pf/file at the same version as the app’s other @ts-pf/* packages.
- The handler reads the body before it builds the context. There is no actor yet, so without
signedInOnlyanyone can make the server read up tomaxBodySize, even with no session.isSignedInis the app’s own function. It checks the session, not only that a header is there, and reads only the headers. If browsers on another origin call this, listCORSPluginfirst. - If the session is in a cookie, also check
OrigininonRequest, on every handler. Allow only a list of origins: the app’s, and any other front end that you trust. Refusenull. Choose what to do when there is noOrigin: browsers send one with a POST, but other clients may not. A form on another site can send multipart ortext/plainwith no preflight. A handler for JSON readstext/plaintoo.SameSitecookies stop many of these requests, but not all. A bearer token that the client adds itself is not sent this way. maxFileSizedoes not limit what is read. The codec checks it afterformData()has read the whole body.RequestLimitPluginstops sooner. Give every handler one: without it, even a JSON handler reads a whole multipart body before it refuses it.- Leave it out of the MCP tools.
all()makes it a tool with no declared inputs, and a model cannot send it aBlob. Exclude it, and tell$coverage:all(tk, { exclude: [tk.files.upload] })andtk.$coverage({ toolsets, exclude: [tk.files.upload] }). - The descriptions cannot show its input. The catalog marks it
unavailable, with a reason. OpenAPI says “Schema unavailable” under anapplication/jsonbody, though the call is multipart. The admin does not show the method.
Masking by role
Section titled “Masking by role”The edge puts the member’s role on the actor (The auth edge), and the collection’s fields rule reads it:
// A member sees every deal of the organization, without its amount. fields: { amount: { read: ({ actor }) => 'support' in actor || actor.role === 'manager', }, },A member’s deals.find has no amount, and a where or sort on it is VALIDATION. A manager and support read it, and a manager filters by it. A member may still set it on create, and the response leaves it out. An update that names it is VALIDATION. The crm tests this over HTTP in masking.test.ts.
Testing what a collection exposes
Section titled “Testing what a collection exposes”Write down what the app should expose, and compare the whole contract with it:
const exposed = Object.fromEntries( Object.entries(api.contract).map(([slug, slice]) => [ slug, Object.keys(slice).sort(), ]),);
expect(exposed).toEqual({ files: ['open'], staff: ['get', 'search'],});toEqual checks both directions. It fails when a slug or a procedure is missing, and when one is added. Do not build the expected list from the contract: it would change with the contract, and never fail. A relation shows by its name, so check its operations with Object.keys(api.contract.posts.categories). A test that calls every procedure calls only what each collection exposes.
Testing access without find
Section titled “Testing access without find”A test that used find to check access can read the repo under the action’s scope instead. Here staff exposes only get and a search method:
const visible = async (action: string) => { const ctx = context({ actor, logger }); const scope = await ctx.access.scope(Staff, action); const { docs } = await repos.staff.find({ sort: ['name'] }, scope); return docs.map(({ name }) => name);};
expect(await visible('read')).toEqual(['Ada', 'u1']);expect(await visible('search')).toEqual(['Ada']);- Test each action by its own key. A method has its own rule, so a test of
readsays nothing aboutsearch. Test create by calling it: its function needs the data. contextandreposcome frombuild(). Make one context per call.- This tests the rule. It does not test that a method uses it, so call the method too.
- The repo returns whole documents, so it cannot test masking. Call a procedure, such as
getor a method, throughcreateLocalClient, once as a caller who may read the field and once as one who may not.
A worker: webhooks and integration events
Section titled “A worker: webhooks and integration events”Collection events stay inside the product. In the crm, the HTTP process stores each domain event in the outbox. The worker process runs the relay, which publishes them to a @hexok/queue queue, and it maps the ones that leave: a customer webhook through @hexok/webhooks, and an integration event for the company’s other products through @hexok/integration-events.
const integration = new IntegrationPublisher(CrmDeals, { queue: deps.integrationQueue, });
const handlers = [ new SendDealClosedWebhook({ deals: repos.deals, webhooks, logger }), new PublishDealClosed({ deals: repos.deals, integration, logger }), ];A handler is system code. It reads inside the event’s own tenant, with tenancy.scope, never with an actor’s access, and maps the document field by field, so a new field on the collection reaches no one outside until it is added to the mapping:
async handle(event: DealClosedEvent): Promise<void> { const { dealId, outcome, tenantId } = event.payload; const deal = await this.deps.deals.get( dealId, tenancy.scope(Deals, tenantId), ); if (deal === null || deal.closedAt === undefined) { this.deps.logger.warn('deal.closed integration skipped', { dealId, tenantId, reason: deal === null ? 'not-found' : 'not-closed', }); return; } await this.deps.integration.publish( new DealClosedV1(dealClosedV1(deal, tenantId, outcome, deal.closedAt)), // A deal closes once: a redelivery publishes the same id, and a // consumer dedupes on it. { id: `deal.closed:${deal.id}`, subject: deal.id }, ); }- Each handler subscribes in its own consumer group, inside a consumer span, through
subscribe.ts. - The webhook leaves out
amount, a field only managers read. The integration contract,src/integration/deals.ts, carries it: it is internal to the company. - Masking applies where a document leaves for a client. Events and repos carry whole documents, so each mapping decides what leaves.
Tracing with an SDK
Section titled “Tracing with an SDK”Lattice’s spans and the store’s need an SDK and a context manager registered once, before the app serves. The crm’s tests register one with an in-memory exporter; an app does the same at startup with its exporter, such as @opentelemetry/sdk-node and OTLP:
const exporter = new InMemorySpanExporter();beforeAll(() => { context.setGlobalContextManager( new AsyncLocalStorageContextManager().enable(), ); trace.setGlobalTracerProvider( new BasicTracerProvider({ spanProcessors: [new SimpleSpanProcessor(exporter)], }), );});A deals/find over HTTP is then a procedure span with the use case span and the store call under it. The crm’s production processes register no SDK, so they record nothing.
Serving MCP and OpenAPI
Section titled “Serving MCP and OpenAPI”The crm turns the contract into MCP tools with @ts-pf/mcp. Every tool describes itself, generated or a method. An operation that a collection’s operations leave out is not a tool. To keep an exposed operation on /rpc but not as a tool, give all an exclude. The crm needs none:
const tk = createToolkit(contract).$context<CallContext<ActorInput>>();
/** * The API's procedures as MCP tools, each named by its path. Every one * carries its summary and effect from the contract: Lattice writes them for * generated operations, and a method declares them on its use case. */export const crmTools = tk.$toolset({ tools: [all(tk)],});
// A procedure the toolset leaves out fails this line, until this line// excludes it.tk.$coverage({ toolsets: [crmTools] });The tools run in process through the implemented router, so access, tenancy, masking, errors and spans are the same as on /rpc. The edge checks the session before the MCP SDK reads the request, and the tool context reuses the auth edge’s actorContext:
const tools = bindTools(crmTools, { app: deps.crm.app, onError, async context(info) { const userId = info.authInfo?.extra?.userId; const requestId = info.authInfo?.extra?.requestId; const request = info.requestInfo; // The edge sets all three before the SDK runs: this is a bug guard. if ( typeof userId !== 'string' || typeof requestId !== 'string' || request === undefined ) { throw deps.crm.clientError(LatticeError.UNAUTHORIZED()); } return contextOf( userId, request, deps.logger.child({ requestId }), 'mcp', ); }, });The OpenAPI document is a projection of the contract’s catalog, with ts-pf’s codegen profile for generators in other languages:
export function openapiDocument() { return openapi(catalogDocument(), { info: { title: 'Lattice CRM', version: '0.0.0' }, profile: 'codegen', });}The crm serves it at GET /openapi.json, and the catalog itself at GET /catalog.json, to signed-in users only, since both say which fields are masked. The catalog carries each procedure’s lattice meta and the x-lattice-* keys; the admin builds its views from it. A TypeScript client in another repo uses @ts-pf/codegen on the same catalog instead; the crm’s codegen.test.ts is that client, with no casts.
Mounting the admin
Section titled “Mounting the admin”@latticecms/admin renders the app from the catalog it serves. The crm’s page signs in through /auth, lists the user’s organizations for a switcher from /auth organizations, which needs no organization header, and calls the API with the picked one:
const auth = useMemo( () => authClient(sessionFetch(signed.token, undefined, onSignedOut)), [signed.token, onSignedOut],);// A 401 signs out through the session's fetch. Anything else, such as a// dropped connection, can be tried again.const load = useCallback(() => { setFailed(false); auth.organizations({}).then(setOrganizations, () => setFailed(true));}, [auth]);useEffect(load, [load]);const organization = organizations?.find(({ id }) => id === picked) ?? organizations?.[0];const fetch = useMemo( () => sessionFetch(signed.token, organization?.id, onSignedOut), [signed.token, organization, onSignedOut],);Every page, <Admin> among them, sits under a cache keyed by the organization, so a switch remounts them with an empty cache and never shows another organization’s rows:
<SWRConfig key={organizationId ?? 'support'} value={{ provider: () => new Map(), shouldRetryOnError: retryable }}> <ListsProvider>{children}</ListsProvider></SWRConfig>The edge checks the organization header on every call, as in The auth edge. The admin’s README has its props, the catalog route and what it renders. The smallest page, a token form, is in the root README’s Getting started.
Reference
Section titled “Reference”collection() options
Section titled “collection() options”collection(slug, { schema, tenant?, indexes?, relations?, maskable?, serverFields?, hidden?, label? })
Returns a Collection with slug, label, schema, tenant, indexes, output, clientOutput, clientInput, queryOutput, maskable, serverFields, hidden, events and hooks(). output is the stored document’s schema: the collection’s schema plus id, createdAt, updatedAt and the tenant field. clientOutput is the document a client receives: output, with each maskable field optional and each hidden field left out of its type. clientInput is what create takes: the collection’s schema without its server fields. queryOutput is what a client’s where, sort and countBy field name: output without its hidden fields.
- A slug may not start with
_: Lattice keeps those names for its own collections, such as_outboxand_sequences. A slug may not end with_versionseither, one ofreservedSlugSuffixes. Each is a compile error and a throw at.collection(), and a throw for amany()relation’sthrough. schemais az.object(). Unknown keys are stripped.id,createdAt,updatedAt,and,orandifare reserved field names, listed inreservedFields, and so is any name that starts with_. The tenant field and a link field may not be one either.- No
z.date()and no transforms, anywhere in the schema. Store ISO strings (z.iso.datetime()). Normalize in abeforeChangehook.collection()throws at definition time, and a top-level Date or reserved name fails to compile. - A field that may have no value is optional. A store keeps a value as JSON would: a key set to
undefinedis left out, at any depth, and anundefinedarray element is stored asnull(0059). Socollection()throws on a required key that takesundefined, at any depth, such asz.unknown(),z.any(),z.custom(),z.void(),z.undefined()or a union withz.undefined(): usez.unknown().optional(). It also throws on an array or tuple element that takesundefinedand refusesnull, such asz.array(z.string().optional()): use.nullish(). A default that replacesundefinedis fine. createdAtandupdatedAtare ISO 8601 strings.tenant: 'organizationId'makes the collection tenanted; see Tenancy. Without it, the collection is global.- A field name may not contain
., start with$, or be_id: MongoDB would read it as a path, an operator or the id. maskable: ['amount']names schema fields a caller’s rules may withhold; see Field masking. A maskable field may not be a ref or in a unique index.serverFields: ['number']names schema fields only the server writes; see Server fields. Each may be any schema field, a ref or a maskable one included. A name that is not a schema field, or is there twice, throws.label: { singular: 'person', plural: 'people' }says how the collection reads mid-sentence, in generated summaries and the admin. Without it, the label comes from the slug:deal_stagesreads “deal stage” and “deal stages”. Declare it when the slug’s singular would be wrong, as forpeopleornews, or when the words matter: a label derived from a slug may change in a minor.Collection.labelis the label a collection has.- A field’s label in a client such as the admin is its name in words, or its JSON Schema
title:amount: z.number().meta({ title: 'Deal value' }). Zod’s.meta()reaches the catalog, OpenAPI and MCP. indexeslists the indexes the store creates at startup, throughbuild().ensure():[{ fields: { stage: 1, createdAt: -1 } }, { fields: { email: 1 }, unique: true }]. Fields are named from the stored document, so the system fields and the tenant field count; any other name is a compile error and a throw. Key order is the index’s order.present: ['emails']makes a unique index cover only rows where each listed field has a value: not missing or null, and for an array, an element that is neither null nor an array. So two contacts without emails, or two rows whose optionalexternalIdis unset, do not clash. A row the index covers is keyed by every element, null included, as withoutpresent.presentneedsunique: true, and each listed field must be one of the index’s.idneeds no index. A tenanted collection’s indexes usually lead with the tenant field, because every call filters by it; Lattice does not add it for you. A unique one must include it, anywhere in its keys. Without it, two tenants could not hold the same value, and aCONFLICTwould tell one tenant what another holds. Leaving it out is a compile error and a throw.
Reserved names
Section titled “Reserved names”Lattice keeps these names for generated code it may add later (0067). Putting one to use is then a minor release, not a breaking one.
| Name | Kind | Kept for |
|---|---|---|
A name that starts with _ |
Field, tenant field, link field | Later system fields, such as a version number or a soft delete |
if |
Field | A condition a client sends beside an update’s or a delete’s fields |
A slug that starts with _ |
Collection, many()’s through |
Lattice’s own collections, such as _outbox and _sequences |
A slug that ends with _versions |
Collection, many()’s through |
A collection’s versions and drafts, and their operations, such as publishing a draft (0052) |
upsert |
Method or relation | A generated upsert operation |
Catalog facts
Section titled “Catalog facts”catalog(contract) from @ts-pf/docs carries what a client such as the admin needs, so it reads them instead of guessing from paths and names:
| Fact | Where | What it says |
|---|---|---|
lattice meta |
Each procedure’s meta | Its collection, the collection’s label, and its operation; a relation’s name and target; a method’s name. LatticeMeta is its type |
docs and mcp meta |
Each procedure’s meta | Its summary and its effect: read, write or destructive. A method’s come from its summary and effect statics |
x-lattice-ref |
A ref’s JSON Schema | The slug of the collection it points to |
x-lattice-maskable |
A maskable field’s JSON Schema | That a caller’s rule may withhold it |
x-lattice-tenant |
The tenant field’s JSON Schema | That Lattice stamps it, so a client shows it read-only |
x-lattice-hidden |
A hidden field’s entry in clientOutput’s JSON Schema: an optional never |
That no client receives it |
title |
A field’s JSON Schema, from .meta({ title }) |
Its label; without one, a client uses its name in words |
Where and Sort
Section titled “Where and Sort”find takes { where?, sort?, limit?, after? } and returns { docs, next }. Where<Doc> and Sort<Doc> are typed from the document, system fields included.
| Field kind | Operators |
|---|---|
| string | eq, ne, in, nin, gt, gte, lt, lte, contains, exists |
| number | eq, ne, in, nin, gt, gte, lt, lte, exists |
| boolean, enum | eq, ne, in, nin, exists |
| array of strings, numbers or enum values | has, nhas, exists |
| array of anything else, object, anything else | exists |
- Several fields or operators must all match.
andandornest. A client’sandandorneed at least one filter, or the call isVALIDATION; for an unfiltered list, send nowhere. Server code may pass empty ones: an emptyandmatches everything, and an emptyormatches nothing. Null and missing follow MongoDB’s semantics. containsis a case-insensitive substring, never a regex.hasmatches an array with an element equal to its value.nhasmatches an array with no such element. A missing or null array has none, sonhasmatches it; addexists: trueto require the array.sortis an array such as['-createdAt', 'title']. String, number and enum fields sort, optional and nullable ones too. The default is['-createdAt'], andidis always the last tiebreak. Its JSON Schema lists every key it accepts, so a client sees the valid keys.- A document with no value for a sort field, missing or null, comes after every document with one, ascending or descending. Documents with no value order by the remaining keys, then
id. The cursor records that its document had no value, so pages stay stable across that boundary. limitis 1 to 100, default 20.nextis an opaque cursor forafter, or null on the last page.- A field or operator the schema does not allow is a type error and
VALIDATION. - A field needs at least one operator, and an operator set to
undefinedisVALIDATION: either would match more rows than the caller named, such as{ ownerId: { eq: user?.id } }. Over JSON,{ eq: undefined }arrives as{}, which is refused too. A field set toundefinedis left out, as a missing one is.
count takes { where? } and returns { count }: how many documents find would return across every page. It runs read access and the tenant clause, as find does, validates where the same way, and writes one log line. A list that needs a total calls find and count side by side; find never counts.
countBy takes { field, where?, limit? } and returns { groups: { key, count }[], more }: how many matching documents hold each value of field. It runs read access and the tenant clause, as count does, and writes one log line (0046).
// Open tickets per project, for a list of projects, in one call.const { groups } = await client.tickets.countBy({ field: 'projectId', where: { projectId: { in: projectIds }, status: { eq: 'open' } },});const openIn = new Map(groups.map(({ key, count }) => [key, count]));fieldis a string, number, enum or boolean field, or an array of strings, numbers or enum values. The system fields are not. Any other name is a type error andVALIDATION; its JSON Schema lists the fields it accepts.- An array counts each distinct element once per document. A missing or null value,
[]and a null element count underkey: null. A project with no tickets has no group: read it as 0. - Groups are sorted by count, highest first, then by key,
nullfirst.limitis 1 to 1000, default 1000. Past it, the result is cut andmoreistrue, so a screen keeps working as data grows. keyisstring | number | boolean | nullon a client, since one output serves every field.Repo.countBytypes it from the field.- The tenant field is
VALIDATIONunless the call bypasses tenancy: any other caller sees one tenant, so its count by tenant is its total.
update takes { id } and the fields to change. A field left out keeps its value, and a patch never applies a default.
nullclears an optional field with no default: the key is removed, and theupdatedevent’sdoclacks it. Its JSON Schema, and so its client type, takesnull:expectedCloseDate?: string | null.- A nullable field stores
null. A required or defaulted field refusesnullwithVALIDATIONat its path. - The document after the change is validated with the whole schema, so an object-level
.refine()holds on update too.
Errors
Section titled “Errors”Every procedure declares UNAUTHORIZED (401), FORBIDDEN (403), NOT_FOUND (404 with { collection, id }), CONFLICT (409 with { collection, id, fields }, where fields are the clashing unique index’s fields as declared, ['id'], or [] when the store cannot tell) and REFERENCED (409 with { collection, id, by }), plus the app’s declared errors. VALIDATION is ts-pf’s protocol code, with { path, message }[] issues.
LatticeErroris the hexokErrorscatalog behind those codes. Overrides and methods throw it, so they answer as the generated operations do:LatticeError.NOT_FOUND({ collection: 'deals', id }).- The app’s errors are a hexok
Errorscatalog, its client map and its mapper, as in hexok’s app-template:framework({ errors: { declared, map } }). An app code that collides with Lattice’s is a compile error. - An error that is neither Lattice’s nor mapped by the app reaches an HTTP client as
INTERNAL. An in-process caller gets the original error. - Lattice’s errors are final at the client boundary. The app’s
mapnever sees aLatticeError, so every app sends the same code, status and data for it, and typed clients and the admin read one shape. - An app’s own router, such as one for sign-in or public reads, sends Lattice’s errors as the procedures do.
build().clientError(error)returns the ts-pf error a client receives for aLatticeError, or undefined for any other, so a middleware throws what it returns. That middleware logs the refusal, as Lattice’s procedures do:onErrorlogs onlyINTERNAL. A hexokVALIDATIONis not aLatticeError, soclientErrorleaves it to the router.latticeErrorsis the table of declared errors and statuses, for that router’s.errors(). Given aLatticeError,clientError’s type has no undefined.
// Lattice's errors, such as a repo's, go out as /rpc sends them. A // refusal is logged here, as /rpc logs it: onError logs only INTERNAL. const impl = createImplementer(authContract) .$context<AuthRpcCtx>() .use(async ({ context, next, path }) => { try { return await next(); } catch (error) { const sent = deps.crm.clientError(error); if (sent === undefined) throw error; context.logger.info(`auth.${path.join('.')}`, { outcome: 'refused', code: sent.code, }); throw sent; } });- A client’s
CONFLICTleaves out the collection’s tenant field, which the client cannot change, unless it is the index’s only field, as in one row per tenant. Server code that catches theLatticeError, such as an override or a repo call, gets every field. CONFLICT’sidis the document being written, never the one it clashed with, so it reveals nothing about another row.
Repo and Doc
Section titled “Repo and Doc”Repo<C> is a typed view of the store for one collection: get, getMany, find, count, countBy, insert, next, update and remove. Use it in hand-written use cases and event handlers. It is trusted: it runs no hooks, no events and no access check.
inserttakes the schema’s input type and parses it, as create does: defaults apply, unknown keys are dropped, and a failed check throwsLatticeErrorVALIDATIONwith create’s issues. Then it stampsid,createdAtandupdatedAt. A key set toundefinedis left out of the row and the result, as in a generated create.updatetakes a typed patch of the schema’s output and writes it as given, with no parse and no read: it does not check the merged document. It bumpsupdatedAt. A key set toundefinedremoves the field. Unless it throws first, for a bad scope orif, it always sends its write, even with an empty patch or no matching row.updateandremovetake{ if }, aWherethe row must meet. It is checked in the same store call as the write, so nothing can change the row between the check and the write. A row that fails it is left alone and the call returns null, as a missing row does.inserttakes{ id }, for a row that shares another’s id, such as a projection of it. The id is any non-empty string, not only a UUID, so${eventId}:${field}works as a deterministic id. An id that exists isLatticeErrorCONFLICT. Without it, the id is a new UUID. Generated create always uses a new UUID. Never pass an id a client sent: aCONFLICTwithfields: ['id']would tell the client that id exists, in any tenant.next(field, scope)counts up a server field’s numbers; see Numbering documents.countBy({ field, where?, limit? }, scope)groups and orders as the generated countBy does. It is trusted: it counts by the tenant field or a withheld one.limitdefaults to 1000 and has no upper bound. Itskeyis typed from the field:'open' | 'closed' | nullfor an enum, the element type or null for an array.- Each
Wherea repo takes, infind,count,countByandif, is checked at runtime as an access answer is. An undefined operand or a field with no operator throws, instead of dropping a clause.
// Book a slot once: a second booking that read the same version gets null.const booked = await slots.update(id, { status: 'booked', version: slot.version + 1 }, scope, { if: { status: { eq: 'open' }, version: { eq: slot.version } },});if (booked === null) throw DomainError.SlotTaken({ id });Every call takes a scope as its last argument: the call’s Scope from ctx.access.scope(), a tenant’s from tenancy.scope(), or unscoped. A row outside the scope acts as missing. unscoped reads and writes every row; trusted code that acts for no caller passes it, such as a script. A Scope for another collection throws.
On a tenanted collection, insert stamps the scope’s tenant, next counts for it, and neither takes unscoped. update never writes the tenant field. scope.tenantId is the tenant, for a method’s own events.
Doc<C> is the collection’s stored document type.
export class ArchiveDeal extends AppUseCase('deals.delete', { collection: Deals,}) { constructor(private readonly deps: { deals: Repo<typeof Deals> }) { super(); }
async execute( ctx: AppCtx, input: { id: string }, ): Promise<Doc<typeof Deals>> { const deal = await this.deps.deals.update( input.id, { archived: true }, await ctx.access.scope(Deals, 'delete'), ); // The same refusal the generated delete gives for a missing id. if (deal === null) { throw LatticeError.NOT_FOUND({ collection: Deals.slug, id: input.id }); } return deal; }}Transactions
Section titled “Transactions”transaction(work) runs work as one unit: every write commits, or on a throw, none does. work receives { repos, generated, events }, all bound to the transaction, and returns the value transaction resolves to. It is on build() and in both factories’ wiring.
// Closes a deal and logs an activity on it: both rows, or neither.class CloseAndLog extends AppUseCase('deals.closeAndLog', { collection: Deals /* … */ }) { constructor( private readonly deps: { transaction: Transaction< { deals: Repo<typeof Deals>; activities: Repo<typeof Activities> }, Record<never, never>, DealClosedEvent >; }, ) { super(); }
async execute(ctx: AppCtx, input: { id: string }) { const scope = await ctx.access.scope(Deals, 'closeAndLog'); const now = new Date().toISOString(); return this.deps.transaction(async ({ repos: { deals, activities }, events }) => { const deal = await deals.update(input.id, { stage: 'won', closedAt: now }, scope, { if: { closedAt: { exists: false } }, }); if (deal === null) throw LatticeError.NOT_FOUND({ collection: Deals.slug, id: input.id }); await activities.insert( { dealId: deal.id, kind: 'note', body: 'Closed as won', occurredAt: now, authorId: AppUseCase.actorId(ctx.actor) }, tenancy.scope(Activities, deal.organizationId), ); await events.publish(new DealClosedEvent({ dealId: deal.id /* … */ })); return deal; }); }}
// the wiringmethods: ({ transaction }) => ({ deals: { closeAndLog: new CloseAndLog({ transaction }) } }),-
Transaction<R, G, E>names only what a use case needs: its repos, the generated operations it calls, and the events it publishes.GandEdefault to none. Thetransactionthat Lattice gives fits it, whenbuild({ events })takes those events. -
Only calls through what
workreceives join the transaction. A call through the outerreposorgenerated, or to another use case, does not. -
Repos publish no events.
events.publishtakes the app’s own events, and collection events such asActivities.events.created. They are held until the end ofwork. An outbox then stores them in the transaction, and a publisher publishes them after it commits. A rollback drops them. -
workmay also return its events, for the caller to publish oncetransactionresolves. They go out only after the commit, as a publisher’s do, but no outbox stores them: if the process stops in between, they are lost. An event the app keeps out ofbuild({ events })goes out this way. -
Await each call. Calls that do not depend on each other can share a
Promise.all: a store runs them one at a time if its database needs that. Do not change a call’s arguments until it settles, because it may wait its turn.events.publishthrows onceworkhas ended. A repo call, even a read, or a generated operation that is still running then fails the transaction, because a write could commit without its event: Lattice waits for it to settle, however long that takes, then rolls back. One that starts later throws and writes nothing. Lattice sees only its own calls. Ifworkends while a helper it did not await is between two of them, the transaction commits, and the helper’s later calls throw. So a write can commit without the event the helper was about to publish. When a call that was not awaited rejects, nothing handles it, and by default Node ends the process. -
Some failures end the transaction, even when
workcatches them. One is a generated operation that failed after it wrote, such as a cascade that stopped partway: its writes would commit without their events. The other is any write, through a repo orgenerated, that failed with something other than aLatticeError, such as a lost connection: it may have written. The transaction then rejects with that error, and the store may retry on it. A refusal that wrote nothing, such asNOT_FOUNDorREFERENCED, can be caught. -
workmay run more than once: MongoDB retries a transaction on a transient error. Keep side effects out of it. Only the events of the attempt that commits go out. -
How atomic it is depends on the store (
CollectionStore.transaction).MongoStoreneeds a replica set or a mongos. On a standalone server, the writes run in order, with no rollback: a throw keeps the writes made before it and drops their events.MemoryStorerolls back and runs transactions one at a time. It is for tests and development. -
A
CONFLICTinsideworkends the transaction. MongoDB aborts a transaction on a duplicate key. Code that catches theCONFLICTand carries on never commits: the driver runsworkagain until it times out.MemoryStorethrows at once instead. Let theCONFLICTendwork. -
A guarded write that misses returns null, inside
worktoo.updateorremovewith{ if }leaves the row alone. To give up, return. To try again, throw: any throw rolls the transaction back. A hand-madeCONFLICTcarries{ collection, id, fields: [] }: the shape of a clash whose fields the store cannot name, so a caller cannot tell the two apart. -
To try again, run the whole
transactionagain, a limited number of times. Lattice does not retry it (0063). In each run,workreads again, through what it receives, every row its writes depend on, and uses nothing read before it. Do not number documents this way:nextdoes not clash.for (let attempt = 1; ; attempt += 1) {try {return await transaction(work);} catch (error) {if (!(LatticeError.is(error) && error.code === 'CONFLICT') || attempt >= 5) throw error;}} -
Let a store’s error leave
workas it was thrown, not wrapped and not as acause. The store gives the database driver its own error back, so the driver can decide whether to runworkagain. A wrapped error ends the transaction instead. -
A throw does not prove nothing was written. When a commit’s result is unknown, the transaction may have committed.
MongoStorethen throws aMongoStoreCallErrorwhoseerrorLabelsincludeUnknownTransactionCommitResult. A single write outside a transaction, or on a standalone server, may also have been written when it throws, such as on a write concern timeout. Do not undo a side effect on a throw, such as an email already queued. Make the next attempt find what the last one wrote, asinsert({ id })with a deterministic id does. -
Do not call
transactioninsidework. It starts a separate transaction: its writes commit on their own, and on MongoDB a write to a row the outer one wrote conflicts, so the driver retries it, and the outer one stalls until the driver gives up. Code that runs inside a transaction takes whatworkreceived as arguments.
In the overrides factory, generated holds the operations the app overrides, bound to the transaction. An override runs the generated operation and its own writes as one unit:
// Replaces tickets.update: the generated update and an audit row per field, both or neither.class UpdateTicket extends AppUseCase('tickets.update', { collection: Tickets }) { constructor( private readonly deps: { transaction: Transaction< { audits: Repo<typeof Audits> }, { tickets: { update: (ctx: AppCtx, input: UpdateInput<typeof Tickets>) => Promise<Doc<typeof Tickets>> } } >; }, ) { super(); }
async execute(ctx: AppCtx, input: UpdateInput<typeof Tickets>) { return this.deps.transaction(async ({ repos: { audits }, generated }) => { const ticket = await generated.tickets.update(ctx, input); for (const field of Object.keys(input).filter((key) => key !== 'id')) { await audits.insert({ ticketId: ticket.id, field }, tenancy.scope(Audits, ticket.organizationId)); } return ticket; }); }}
// the wiringoverrides: ({ transaction }) => ({ tickets: { update: new UpdateTicket({ transaction }) } }),generatedinworkholds the same operations as the factory’sgenerated. Their writes join the transaction, and a generated delete’sonDeletewrites join it too.build()’stransactionand the methods factory’s have none.- Their events and those of
events.publishgo out in the order the calls finish, which is the order of calls awaited one by one. With a publisher, a failure after the commit reaches the caller, the writes stay, and the events after it are not published. - The whole operation runs inside
work, hooks included, so on MongoDB it may run more than once. Hooks only transform data (beforeChange), so that is safe. Access answers are kept on the context, so another run uses them again. Only create’s function can run again, when its data differs; see Access.
An outbox
Section titled “An outbox”With a publisher, a crash between a write and its publish loses the event, and a publish failure reaches the caller although the write happened. An outbox closes that gap. It is opt-in: pass outbox(catalog) as events, and each event is stored in the same transaction as its write.
import { outbox } from '@latticecms/core';
const { app, ensure } = createApp({ store, events: outbox(DomainEvents) });DomainEvents is the app’s EventCatalog. A relay reads the stored events and publishes each one. @latticecms/store-mongo has it, for a MongoStore. With an outbox and no relay, nothing is published and the events pile up.
- What is stored. The events of generated writes, and those a use case passes to
events.publishin atransaction. There is nooutbox.publish(): it would store an event apart from its write. An event an app publishes another way is not in the outbox. - What it promises. On a replica set or a mongos, an event is stored exactly when its write commits. It stays stored until the relay’s
publishresolves. After that, delivery is up to the app’s queue. A standalone MongoDB has no transactions, so the gap stays there.MemoryStorerolls back but keeps nothing after a restart, and no relay reads it. Use a publisher with it, except in a test of what is stored. - At least once. An event can arrive more than once, always with the same id. Make a handler idempotent with an id from the event’s own data, such as
deal.closed:<deal id>. Where the data has none, use the outbox id: the app’s subscriber can pass it as a second argument,handler.handle(event, { id }). The handler declares it as optional,delivery?: { id: string }, since hexok’s ownhandletakes only the event. A required one is a compile error. The subscriber’s own type for a handler must have the argument,handle(event: E, delivery: { id: string }): Promise<void> | void, and also takes a handler that has only the event. A handler that needs the id throws when it is missing. If handlers share a dedupe store, put the handler’s token in the key: every handler of an event gets the same id. - Order is approximate. Retries, clocks and queue consumers can each change it. A handler that keeps a projection reads its source row again, or compares versions. It does not rely on the order events arrive in.
- Each generated write runs in a transaction, with one insert for each event. Writers that compete for one document may be retried by the driver. For an operation called on its own, access, hooks and update’s first read stay outside, so a retry does not repeat them.
- An event that cannot be stored fails the call and rolls back its write: one that is not in the catalog, or whose payload
JSON.stringifyrefuses, such as one with a bigint. On a standalone MongoDB the write stays. Any other value is stored as JSON writes it: aDatebecomes a string,NaNbecomesnull, and aMapbecomes{}. A row must fit in MongoDB’s 16 MB, and an update event holds bothdocandprevious. - Payloads are stored as plain JSON until a relay publishes them, and the relay passes them to
publishas they are. Encryption in the app’s publisher does not apply: the outbox does not use that publisher. A deleted row can still be in the database’s backups. Collection events carry whole rows, and anupdatedevent the previous one too, so_outboxholds copies of those fields. - Leave an event that carries a secret, such as a token, out of the outbox’s catalog. Then
events.publishrefuses it at compile time. If one gets past that,publishresolves, and the transaction rejects whenworkends, as for any event that cannot be stored. Publish it directly aftertransactionreturns, and accept that a crash can lose it. This works only for an app’s own events. The catalog must take every collection’s, so a secret in a collection’s row cannot be kept out this way. ensure()also creates the outbox’s index. Run it before the first write.- Rows are in
_outbox, a collection with no repo, procedures or access rules.
To move an app from a publisher to an outbox:
- Choose what the relay’s
publishsends. With the payload alone, the subscribers need no change ifpublishkeeps the app’s topics and its encoding, with any encryption; they just do not see the id. It gets an event’stoken, not its key in the catalog. If the topics are the keys, map each token to its key, or first deploy subscribers that read both topics. The payload has already been JSON, so aDateis a string: an encoding that keeps dates needs a change too. To send the id too, as the crm does with{ id, payload }, first deploy subscribers that read both that and the payload alone. - Run
ensure()from a build that uses the outbox, before any write uses it. - Start the relay.
- Switch
eventsto the outbox. This moves generated writes, and what atransactionalready publishes through itsevents. - Move the app’s other publishes. A method that publishes after
transactionreturns keeps the gap. Publish insidework, withevents.publish, name the events inTransaction<R, G, E>, and remove the later publish, or the event is sent twice.
To go back, switch events to the publisher. Keep the relay running until _outbox is empty. If it sent the id, or used new topics, keep the subscribers that read both until the queue holds no message with an id or on a new topic.
CollectionStore and MemoryStore
Section titled “CollectionStore and MemoryStore”CollectionStore is the hexok port every collection uses: ensure, find, count, countBy, get, getMany, insert, update, next, remove and transaction. A where on a single-row call limits the rows it can touch; a row outside it acts as missing. MemoryStore is the in-memory adapter, for tests and examples. It stores copies and enforces unique indexes.
ensure(collection, indexes)creates the indexes a collection lacks and never drops one. AnIndexis{ fields: { status: 1, createdAt: -1 }, unique?, present? }. A unique index treats a missing field as null, as MongoDB does, and keys each element of an array field, so two documents that share one element clash. A write that breaks one isCONFLICT, with the index’s fields.insert(collection, doc)storesdocasstored(doc)gives it, and does not changedoc: a key set toundefinedis left out, at any depth, and anundefinedarray element isnull, as JSON writes them.updateremoves a top-level key set toundefined, and stores each other value asstoredgives it.collection()refuses the schemas this would break; seecollection()options.- Every call that takes a
wherethrows a plainError, naming the field, when a field has no operator or an operator isundefined. Core never sends one. A field set toundefinedis left out. count(collection, where?)counts the documents that match.countBy({ collection, field, where?, limit })returns{ groups: { key, count }[], more }, with countBy’s rules for arrays, null, order and the cut. The conformance cases check each.next(sequence, tenantId?)adds one to a counter and returns it: 1 the first time. Each pair ofsequenceandtenantIdis one counter, and no tenant is a counter of its own. Two calls get the same number only if the counter went back, such as after a rollback, a failover or a restore. A transaction’s rollback gives its numbers back.MemoryStorekeeps a counter where it is when a call outside the transaction has taken a later number, so it never gives that number out twice.transaction(work)runsworkwith a store whose calls join one unit: a commit, or on a throw, nothing. Each store makes it as atomic as it can, and a store without transactions runsworkon itself, in order. Atransactionon the storeworkreceives joins the outer one. Calls on that store may be made together, the first ones too. Core makes some calls together. A store whose database cannot run them together runs them one at a time.MemoryStorehandsworka store of its own, as MongoDB binds calls to a session, and undoes that store’s writes on a throw. It runs one transaction at a time; one started on the root store from insideworkruns beside it, as a separate one. A call on the root store runs at once, sees writes not yet committed, and is kept on a rollback. ACONFLICTaborts the transaction, as on MongoDB, and a call on the transaction’s store after it ends throws.
Writing a store adapter
Section titled “Writing a store adapter”@latticecms/core/store has what an adapter needs: the CollectionStore port, its types (StoredDoc, Patch, FindQuery, Page, CountByQuery, Groups, Group, Index), the parsed filter (AnyWhere, with FieldOps for each field’s operators), stored, which keeps a value as a store must, and the cursor helpers (orderOf, Order, after, encodeCursor). A store receives values Lattice has parsed. Filters follow MongoDB’s null and missing rules, and the keyset of after is itself an AnyWhere, so a store applies it like any filter.
FindQuery.optional names the sort fields a document may lack. Pass it to orderOf(query.sort, query.optional): each Order key then says whether it is optional, and after and encodeCursor handle a missing value. The store must order a document with no value for a key, missing or null, after every document with one, in either direction, and tie such documents on that key. A plain sort is enough wherever no ascending key is optional.
@latticecms/core/store/conformance has storeCases: the cases every store passes, asserted with node:assert, so any test runner runs them. Give each case a fresh store:
import { storeCases } from '@latticecms/core/store/conformance';
describe('MongoStore conformance', () => { let store: MongoStore; beforeEach(async () => { store = await freshStore(); }); afterEach(() => store.stop());
it.each(storeCases)('$name', ({ run }) => run(store));});A case that needs a capability some stores lack says so in needs. A store without transactions runs the rest:
it.each(storeCases.filter((c) => !c.needs?.includes('transactions')))('$name', ({ run }) => run(store));Other types
Section titled “Other types”Actionis the name of a generated operation, such as'find'. An app’s declarations name it. A sharedoperationslist isas const satisfies readonly Action[]; a list typedAction[]is a compile error.Withheldis{ id: string }: a populated document the caller may not read.GroupableField<D>is a fieldcountBycan group by: a top-level string, number, enum, boolean or array field that is not a system field.LatticeMetais thelatticekey of each procedure’s meta; see MCP and OpenAPI.ClientDoc<C>is a collection’s document as a client receives it, each maskable field optional and each hidden field left out.CreateInput<C>is what create takes: the schema’s input, so a defaulted field may be left out.UpdateInput<C>is what update takes: theid, and each field to change, withnullon each field it clears. An override of create or update declares them as its input. Neither has the tenant field or a server field.Built,UseCasesandReposare whatbuild()returns, itsuseCasesand itsrepos.Contractis the contract’s type.CollectionEvent<Write, Slug, Shape, Tenant>is a collection’screated,updatedordeletedevent class: a hexokEventClass<Token, Schema>, the typeEvent()returns. An app does not write these: its declarations name them, soexport const contract = app.contract, the built app, its use cases and a catalog of collection events emit with no annotation, at about one copy of the app’s collections per export. A populating read inuseCaseshas anexecutegeneric in thepopulatelist, typed withExpandResultfrom@ts-pf/contract.Ref<Slug, OnDelete>,Many<Target, Through, Fields, OnDelete>,RelationsOfandJoinShapeare the types of refs, relations and join collections.OnDeleteandManyOnDeleteare theironDeletevalues. An app names them only when it exports its collections from a package with declarations.CallAccessis the type ofctx.access.AccessRequest<Actor>is whatAccess.checkreceives.Scopeis whatctx.access.scope()andtenancy.scope()return.
Stability
Section titled “Stability”From 1.0, core follows semver (0058): a breaking change to anything this section calls public is a major release. The one exception is dropping a TypeScript version or Node line that has left its window, under Runtimes below. Until 1.0, it is a minor whose changeset starts with Breaking (0039). Anything this section does not call public can change in a minor.
Public
Section titled “Public”- The exports of
@latticecms/core, with the signatures this README shows. An exported type is public for naming: an app’s declarations printFramework,Built,Contract,Collectionand the others. The type parameters ofFramework,Built,UseCases,Repos,Contract,Collection,RelationsOf,JoinShape,RefandManyare not public: name those types throughtypeof, as declarations do. Every other type’s parameters are public as this README writes them, such asRepo<typeof Deals>,Transaction<…>andFamilyContext<Actor>. - Stores, to call.
MemoryStore, and calling aCollectionStorefrom app code, such asbuild({ store })andensure(), are public. Implementing the port is not; see below. - The contract. Each generated procedure’s name (
find,count,countBy,get,create,update,delete,<relation>.list,<relation>.set), its input and its output. A method’s procedure is the app’s. - Client types. A maskable field stays in every client type, optional, and the server refuses a query on it per caller. A hidden field is in no client type (0064).
Collection.queryOutputis public for its type, whichwhere,sortand countBy’sfieldread. Its runtime schema is not: do not parse with it. - Errors: each code, status and data shape in Errors. A new code is a minor, so a
switchover codes needs a default. - Events: the tokens
<slug>.created,.updatedand.deleted, and the payloads in Events. - The catalog: the
latticemeta and thex-lattice-*JSON Schema keys in Catalog facts. A later feature adds keys and never changes what one means. A label derived from a slug, rather than declared, may change in a minor. - Reserved names:
reservedNames,reservedFields,reservedSlugSuffixesand the rules in Reserved names. Until 1.0, a minor may add to them. After 1.0, adding one is a major, and putting one to use is a minor. Access,AccessRequestandCallAccess.scope(0068):checkanswersbooleanor aWhere, andreadablethe maskable fields an actor may read.- Guarantees, and these behaviors:
- a server field a client sends is dropped, with no error;
- a transport parses a client’s input once, and
executereceives the parsed value; server code that callsexecutepasses its declared type, unchecked; a generated operation’s body parses its own input (0065); - in an app with a maskable or hidden field, each output a client receives is cut to the keys it declares, so a key a method returns but does not declare is not sent (0064). A later release may cut more, never less;
Repo.update, unless it throws first, writes its patch as given, does not check the merged document, and always stampsupdatedAtand sends its write, an empty patch included (0061). A directCollectionStore.updatewith an empty patch writes nothing;- a
Wherewith a field that names no operator, or an undefined operand, throws, in an access answer, in a repo’sfind,countandcountBy, and in theifof a repo’supdateandremove; - a client’s
andororneeds at least one filter, or the call isVALIDATION. A filter built in code may have an empty one; repos.X.next(field, scope)counts from 1, per collection, field and tenant; Numbering documents says when a number is skipped;MemoryStorematches MongoDB on a unique index over an array field, and its transactions roll back;- what
transaction’sworkpromises, in Transactions; onDelete:restrictcounts rows the read filter hides, and anyonDeletebetween two tenant fields throws atbuild()(0062). Relaxing either is a minor; tightening either is a major.
- Peer dependencies:
hexok^2.3.1,@ts-pf/*^1.2.0,zod^4.1.0,@hexok/logger^0.2.0and@opentelemetry/api^1.3.0. Dropping a supported major of one of them is a major. - Runtimes, by window (0058): TypeScript from the oldest version CI checks through the repository’s own, today 5.9 and 6, where a version leaves the window about two years after its release; and Node 22.11 or later, on a line in active or maintenance LTS. CI type-checks the built declarations and the crm on both TypeScript versions. Dropping a TypeScript version that has left the window, or a Node line after its end of life (Node 22: April 2027), is a minor whose changeset starts with Breaking. On 5.9, see the
tenantOfnote in Tenancy.
Not public
Section titled “Not public”- The store port:
@latticecms/core/store,@latticecms/core/store/conformance, implementingCollectionStore, andWhereandSortas a store reads them (AnyWhere,FindQueryand the rest). They are outside semver until a second store ships, which will likely change the port. - Generated OpenAPI component names. Stable ids can come in a minor.
- Span names and attributes, log fields and messages, and the text of any error message.
MemoryStore’s isolation. It is a test store: how its concurrent transactions see each other is not promised.- How a repo’s refusals are logged. Inside a use case,
Repo.insert’sVALIDATION, andFORBIDDENfor a write through a tenant bypass scope, are logged as refusals, though the app’s own code caused them. That may change. - The type parameters named above, and any type that is not exported.
Deprecations
Section titled “Deprecations”None.
Guarantees
Section titled “Guarantees”The tests prove each of these.
- A client of the contract needs no type annotations at the call site.
- An override keeps the contract’s types, and a method adds a typed procedure.
- Each call writes one log line. Each refusal is logged once, whether the call came over RPC, in process, or through
useCases. A refusal is aLatticeError, a hexokVALIDATION, or a member of a catalog the family lists inrefusals. Anything else is a failure, logged at error. - No use case runs when access says
false, and no row outside an accessWhereis read, changed or returned. - Each access function runs once per call. Create’s runs again only when its data differs; see Access.
- No call reaches another tenant’s rows through its scope, and every bypassed call is logged.
onDelete’s system steps cross tenants only where Refs andonDeletesays so. - Events publish only after a successful write.
- A populated document passes its collection’s
readaccess and tenant, or comes back as{ id }. - A field a caller may not read never reaches it through a procedure’s output, a filter, a count, a sort or a cursor, and the caller’s update cannot change or clear it.
- A client never sets a server field through a generated create or update.
- An update patch never resets a field to its default.
- On a generated update, the merged document is validated with the whole schema.
Repo.updatedoes not check it.
Not yet
Section titled “Not yet”These are not built. docs/architecture.md lists the known limits of what is.
- An adapter for another decision engine. hexok’s authz is shelved;
Accessis Lattice’s port, andbuild({ access })takes any adapter of it. entity: a collection backed by a hexokEntityinstead of a schema.- A store per collection. One
build({ store })serves every collection. - File uploads: a file field. An app stores files through its own storage port, and keeps their metadata in a collection. See A method that takes a file.