Duolith docs

0164. Domain files generate an API's models, validators, client and server wiring

  • Status: Accepted (Mik, 18 Nov 2026)
  • Date: 2026-11-18
  • Decided by: Mik asked for it on 18 Nov 2026 ("generate API client and models from defined yaml … the same type of stuff we have in our workstable api … a separate extension that can be utilized across different applications … our code becomes a definition of our domains and we generate all the wiring"). He chose our own domain format over OpenAPI by card the same day. The rest of the design is the integrator's, approved by Mik on 18 Nov 2026 with the answers recorded at the end.
  • Planning item: none (after version 1, beside decision 0163)

Context

IDX-Studios/work-stable-api already works this way, using tools assembled by hand:

  • Each domain's HTTP contract is an OpenAPI file (schemas/http/v1/skills.yaml, about 30 of them, with shapes in components/), merged into one document with yaml-merge.
  • openapi-generator 6.6 (a Java tool), driven by a Makefile and custom Mustache templates (schemas/api-gen/), writes the server's Elysia route interfaces, TypeBox validators and models, and a typed client package (packages/api-client).
  • A controller maps each operation to a command or a query (CQRS-lite), which holds the business logic. Wiring (src/setup/) assembles the services by hand.
  • Who may call an operation is code inside a string: x-auth-rules: ["allowAuthenticatedUser({ validateUserParam: false })"]. Nothing checks it until a request arrives.

It is the shape Mik wants everywhere. What it costs: OpenAPI says how HTTP looks, not what the domain is, so every file repeats parameters, error responses and $refs; there is a Java tool and its templates to maintain; a misspelt auth rule, a missing controller method or a changed response is found late; validators come from a schema library at run time; and none of it can be reused by another app without copying.

Duolith already reads OpenAPI for pages: duolith api generate writes types that typedApi checks calls against (decision 0104).

Decision

Domains is an extension of its own, usable by any TypeScript or Rust server or app, Duolith or not. It has two parts. The generator lives in the duolith command (duolith domains generate, run by every build and by duolith dev). A small runtime package goes with it (@duolith/domains, @duolith/domains after the rename, and a duolith-domains crate for Rust).

1. A domain is a file that says what the domain is

Each domain is a domains/<name>.domain.yaml file. It names the domain's shapes, its queries (which read) and commands (which change something), who may call each one, and what each command publishes. How that looks over HTTP comes from conventions, written once, not per operation:

# domains/skills.domain.yaml
domain: skills

shapes:
  UserSkill:
    identity: [userId, id]            # what makes one UserSkill that one
    keep: 1h                          # a store rule, on the model (decision 0165)
    userId: id
    id: id
    name: text(1..80)
    level: one of [beginner, practised, expert]
    note?: text(..500), personal      # a mark: stored encrypted, masked in logs
    addedAt: time

queries:
  searchSkills:
    input: { search: text(1..80), limit: count(..20) = 20, offset: count = 0 }
    returns: list of text
    allow: signed in

  userSkills:
    input: { userId: id, search?: text, limit?: count(..100), offset: count = 0 }
    returns: page of UserSkill
    allow: self(userId), admin

commands:
  addUserSkills:
    input: { userId: id, skills: list(1..50) of { name: text(1..80), level: UserSkill.level } }
    returns: list of UserSkill
    allow: self(userId)
    fails: [skillLimitReached]
    publishes: skillsChanged
    changes: UserSkill                # which models it changes; never a key
    limit: 30 per minute per caller

events:
  skillsChanged: { userId: id }
  • Types are words with limits: text(1..80), count(..20), id, time, money, email, url, one of [...], list of, page of (the paged answer the data core's pagedList reads), optional fields with ?, and defaults with =. A shape can name another domain's shape (users.User).
  • HTTP is derived, and can be overridden. A query is a GET and a command a POST on /<domain>/<operation> by default, or an operation says at: GET /users/{userId}/skills to keep an existing address. A move from work-stable-api keeps every address it has today.
  • Who may call it is data. allow: names rules the project defines once, in TypeScript or Rust, with typed parameters (self(userId) checks that the caller is the user in userId). An unknown rule, or a parameter the input does not have, is a build error. An operation with no allow: is an error, not open: public must be written.
  • Failures are named. fails: lists the domain's own errors; each one has a stable code and status, and the client gets them as a typed union.
  • Keys are derived from the models, never typed (Mik, 18 Nov 2026).
    • A shape with identity: is a model, and one of them has the key skills.UserSkill(userId, id).
    • A query's answer has the key skills.userSkills(<its input>). The build knows which models it returns, and which of the query's inputs are the model's identity fields.
    • A command says which models it changes:. From that the build works out every query answer, kept page (decision 0163) and browser copy that could hold one. Each is refreshed when the command succeeds, narrowed by the identity fields the command's input has. addUserSkills(userId: 7) refreshes userSkills for user 7 and nobody else.
    • The generated client carries the same keys, so a page writes state.load(skills.userSkills({ userId })) and never a key string. These are the data core's keys (decision 0019), now made by the build.
  • Store rules sit on the model and its fields. keep:, stale:, ifDown: and the field marks secret and personal are written where the model is defined, and apply wherever that model is cached, kept or logged (decision 0165, section 3).

The format has a schema in spec/schemas/domain.schema.json, so editors complete and check it as it is typed.

1a. A name from the domain can never be mistyped

Mik's rule (18 Nov 2026): nothing that refers to the domain models or the system may be something a typo can break. So every such name is a reference the build resolves, never free text:

Where a name is writtenHow it is checked
In a domain file (a shape, field, operation, rule, failure, event or another domain's model)Resolved when built. An unknown name is an error at that line, with the nearest real name suggested. The language server completes and renames them as it does in page files.
In duolith.yaml (a store, a kind of state, a domain, an environment value)The same: resolved, completed, and an error when unknown
In TypeScript and Rust (pages, server files, implementations, rules, hooks)Only through generated symbols: skills.userSkills, skills.UserSkill, skills.fails.skillLimitReached, rules.self. A wrong name is a type error.
In a replaced templateA placeholder the generator does not provide is a build error, never empty output

There is no text-taking way in. The run-time packages have no function that accepts a key, an operation, a model, a field, an event, a rule or a store by its name as a string. That includes the generated client, the cache, the store seam, the pipeline and the hooks. If a name can be typed wrong, the only places to type it are the ones above, where the build reads it. Renaming a model or field in a domain file is one rename in the editor, and everything that used the old name fails to build until it follows.

2. What is generated

Everything is written into generated/ folders, carries the generated header, and is never edited (repository rule 2).

  1. Models. A type for each shape and input, in TypeScript and, for Rust servers, as serde types. Each comes with a validator written out as plain code: there is no schema library at run time and no new Function, so validation is fast and needs no unsafe-eval.
  2. Server wiring. Each domain gets an interface of its operations (SkillsDomain in TypeScript, a trait in Rust). Each method takes the validated input and a context (the caller, the request's id, the services) and returns the result or one of its named failures. The generated router does the rest: An implementation that lacks an operation, or returns the wrong type, fails the type check.
    • runs the request pipeline of decision 0165 around the method;
    • parses and validates the request;
    • checks allow: against the caller and applies the limit:;
    • calls the method;
    • in development, checks the answer against its shape;
    • publishes the command's events and writes errors in one shape (application/problem+json).
  3. Services. Implementations declare what they need (needs: { db, payments }), and the generated createServer({ domains, services }) assembles them. A missing service is a type error. This replaces the hand-written src/setup/.
  4. The client. The same types for typedApi in Duolith pages (decision 0104). Any other TypeScript app or native shell gets a small generated client. Both send through the same errors, retries and idempotency keys.
  5. An OpenAPI document, written from the domains and served at /openapi.json, for outside tools, other teams and the docs.
  6. A mock server and fixtures, from examples the domain file may give, for tests and for duolith dev before the real server exists.

The author writes the domain files, one method per operation, the rules and the services. Nothing else.

3. Where it runs

  • On the server companion. The generated router is a standard fetch(request) → response handler, so it runs inside the server companion (decision 0163) on Bun, Node and Cloudflare Workers, or on its own.
  • On Axum. For Rust servers it is an Axum router over each domain's trait.
  • Inside Elysia. A thin adapter mounts it in an existing Elysia app, so a project like work-stable-api can move one domain at a time.
  • In the same process as a site. When the API and a Duolith site share a server, a page's server loader calls the domain's method directly, with no HTTP round trip, and keeps the same types.

4. Moving existing APIs over

duolith domains import <openapi files> writes domain files from OpenAPI. It reads operations, shapes, parameters, the x-auth-rules strings it can parse into allow: and the existing addresses as at:. What it cannot read is reported per operation, never guessed. For work-stable-api this turns about 30 files into domain files that keep every address. Comparing the old and new OpenAPI documents then proves that nothing a client sees has changed.

5. Checked when built

  • allow: rules, fails: names, the models a command changes:, publishes: events and shapes named across domains must all exist, with the right parameters.
  • A command that changes nothing must say changes: nothing. A query that returns a model with no identity: cannot be cached per record. The build says so, and refreshes the whole query's answers instead.
  • An at: address whose parameters do not match the input is an error, and so are two operations on the same address and method.
  • duolith domains diff compares the domain files with the main branch and fails on a breaking change unless the domain's version changes. A breaking change is a removed operation or field, a narrowed type, or a new required input. CI runs it.

Stages

  1. The format, its schema, models, validators and the client; domains import.
  2. Server wiring, allow:, fails:, services and createServer, on the fetch handler, Axum and the Elysia adapter. Prove it by moving one work-stable-api domain (skills) and running its existing tests against it.
  3. limit:, model identities, changes: and the derived keys (shared with the server companion's cache and the data core), the mock server, the OpenAPI writer, domains diff.
  4. events: and publishes: with pub/sub adapters (Google Cloud Pub/Sub first, as work-stable-api uses).

Alternatives considered

OptionWhy not
OpenAPI with typed x- extensionsMik chose our own format (18 Nov 2026). OpenAPI describes HTTP rather than the domain, so every file repeats parameters, errors and references. It is still written out for outside tools, and read in by domains import
Keep openapi-generator with our templates, as work-stable-api doesA Java tool and Mustache templates to maintain, nothing checked at build, and output shaped by a generator written for other languages
Define domains in TypeScript (as tRPC or Elysia's own types do)Ties the contract to one language; Rust servers, native apps and other teams read the domain file
TypeBox, Zod or Ajv validators at run timeA dependency in every server, and Ajv compiles with new Function, which a strict policy refuses. Generated validators cost nothing to load
Auth rules as code strings, as todayWrong ones are found only when a request arrives

Consequences

  • One definition serves the server, the browser, native apps and documentation. A contract change shows up as a type error everywhere it matters, at build time.
  • New context in tools/boundaries.yaml: packages/domains (the runtime: router, validation helpers, problem responses, the Elysia adapter) and its Rust crate, neither depending on Duolith's client.
  • The generator grows from crates/cli/src/api_client (decision 0104). The format gets its schema, a reference page, diagnostic codes and conformance fixtures, and its words go in the glossary (domain, shape, query, command, event).
  • work-stable-api can adopt it domain by domain. That move is a change to its own repository, and Mik's call.

Mik's answers (18 Nov 2026)

  • A name from the domain can never be mistyped: every one is a reference the build resolves (section 1a).
  • Our own domain format, not OpenAPI with extensions.
  • The generated router runs on our fetch handler and mounts inside Elysia from the first server stage, with Axum beside them.