From aa9e5c6f118cc9196f9b066d4af2fc5c42702dee Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 03:18:21 -0500 Subject: [PATCH 1/7] feat(codegen-ts): add the service generator and its Fastify transport (ADR-0067 part 1) `service` writes one module per metadata package: a function per derived list, get, create, update and delete of each concrete, table-backed, single-key entity. Each write runs in one transaction (a savepoint inside a caller's), loads the row under a row lock, and validates and stamps the body with the declared write rules (ADR-0045). `service-routes` writes the thin Fastify transport over it. Both are ejectable reference generators written through TsWriter. runtime-ts gains the `./service` and `./service/fastify` entries they import, and `meta eject` copies them. The shared generator list gains the `service` layer label in every port. A new api-contract lane runs the shared corpus against the service behind its transport, in both layouts, and a compile gate builds the tier in every dialect. --- .claude/rules/cross-language-porting.md | 2 +- CHANGELOG.md | 12 + .../skills/metaobjects-codegen/SKILL.md | 3 +- docs/features/business-rules.md | 57 ++- docs/ports/typescript.md | 11 + .../generator-registry-conformance/README.md | 21 +- .../registry.json | 15 + .../GeneratorRegistryConformanceTests.cs | 8 +- .../MetaObjects.Codegen/GeneratorRegistry.cs | 6 +- .../GeneratorRegistryConformanceTest.kt | 8 +- .../generator/GeneratorRegistry.java | 6 +- .../GeneratorRegistryConformanceTest.java | 4 +- .../metaobjects/codegen/generator_registry.py | 5 +- .../test_generator_registry_conformance.py | 4 +- .../packages/cli/src/lib/install-set.ts | 2 +- .../packages/cli/src/lib/runtime-eject.ts | 3 + .../packages/cli/test/eject-contract.test.ts | 3 +- .../cli/test/eject-templates-contract.test.ts | 4 +- .../packages/codegen-ts/src/engine-surface.ts | 1 + .../packages/codegen-ts/src/engine.ts | 1 + .../codegen-ts/src/generator-registry.ts | 43 +- .../codegen-ts/src/generators/index.ts | 2 + .../codegen-ts/src/generators/service-file.ts | 41 ++ .../src/generators/service-routes-file.ts | 35 ++ .../packages/codegen-ts/src/owned-runtime.ts | 5 + .../codegen-ts/src/reference-templates.ts | 3 + .../src/reference/service-routes.ts | 62 +++ .../codegen-ts/src/reference/service.ts | 68 ++++ .../packages/codegen-ts/src/service-walk.ts | 173 ++++++++ .../codegen-ts/src/templates/service-file.ts | 369 ++++++++++++++++++ .../test/generator-registry.test.ts | 11 +- .../generator-registry-conformance.test.ts | 8 +- .../test/reference-byte-identical.test.ts | 8 + .../test/reference-templates.test.ts | 2 +- .../codegen-ts/test/service-file.test.ts | 146 +++++++ .../src/api-contract-generated-lane.ts | 72 ++++ .../src/api-contract-generated-server.ts | 34 +- .../test/api-contract-generated.test.ts | 60 +-- .../test/api-contract-service.test.ts | 11 + .../test/service-compile.test.ts | 114 ++++++ .../packages/runtime-ts/package.json | 10 + .../runtime-ts/src/service/fastify.ts | 26 ++ .../packages/runtime-ts/src/service/index.ts | 265 +++++++++++++ .../packages/runtime-ts/test/service.test.ts | 197 ++++++++++ .../ADR-0067-layering-and-the-service-seam.md | 8 +- 45 files changed, 1843 insertions(+), 106 deletions(-) create mode 100644 server/typescript/packages/codegen-ts/src/generators/service-file.ts create mode 100644 server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts create mode 100644 server/typescript/packages/codegen-ts/src/reference/service-routes.ts create mode 100644 server/typescript/packages/codegen-ts/src/reference/service.ts create mode 100644 server/typescript/packages/codegen-ts/src/service-walk.ts create mode 100644 server/typescript/packages/codegen-ts/src/templates/service-file.ts create mode 100644 server/typescript/packages/codegen-ts/test/service-file.test.ts create mode 100644 server/typescript/packages/integration-tests/src/api-contract-generated-lane.ts create mode 100644 server/typescript/packages/integration-tests/test/api-contract-service.test.ts create mode 100644 server/typescript/packages/integration-tests/test/service-compile.test.ts create mode 100644 server/typescript/packages/runtime-ts/src/service/fastify.ts create mode 100644 server/typescript/packages/runtime-ts/src/service/index.ts create mode 100644 server/typescript/packages/runtime-ts/test/service.test.ts diff --git a/.claude/rules/cross-language-porting.md b/.claude/rules/cross-language-porting.md index 1adc6c31c6..182197d49e 100644 --- a/.claude/rules/cross-language-porting.md +++ b/.claude/rules/cross-language-porting.md @@ -26,7 +26,7 @@ Preserve the following contracts exactly across all language ports: - Relationship subtypes: `association`, `aggregation`, `composition`. Cardinality via `@cardinality: one|many`; target via `@objectRef`. **M:N (FR-018) slim vocabulary:** `@cardinality: "many"` + `@objectRef` (target) + `@through` (the junction/through entity — a third entity that MUST declare two `identity.reference` children, one per FK side). The relationship's FK fields are **derived** from those references (the `identity.reference` SSOT for FK direction), never restated. `@sourceRefField` (optional) disambiguates a *directed* self-join by naming the source-side FK field on the junction (the other reference is the target side); on a `@cardinality: one` relationship it instead names which of several `identity.reference` nodes onto the same target this relationship navigates, short-circuiting the unique-candidate/`@sourceRefField`/name-pairing ladder (#368, [ADR-0029](spec/decisions/ADR-0029-entity-child-extends-and-via-inference.md) Amendment 1) — an unresolvable 1:N reference set is `ERR_INVALID_RELATIONSHIP` at load. `@symmetric` (optional boolean) marks an *undirected* self-join (union-on-read) — valid only when `@objectRef` == the declaring entity, and mutually exclusive with `@sourceRefField`. The pre-FR-018 `@joinEntity`/`@joinFields` attrs are REMOVED. Validation errors: symmetric-on-hetero / symmetric+sourceRefField → `ERR_BAD_ATTR_VALUE`; junction-missing-two-references / sourceRefField-not-matching / M:N-attr-on-1:N / **junction-unpairable** → `ERR_INVALID_RELATIONSHIP`. **Unpairable means the junction declares its two references but neither resolves to the navigating entity, or neither to the `@objectRef` target** — declaring two references is NOT enough, and the loader now checks WHAT they point at (owner ruling 2026-09-20). It does so by running the real FK derivation and converting its failure, never a parallel re-implementation, so the loader and the derivation cannot drift; scope mirrors codegen's own iteration exactly — every CONCRETE, non-projection object crossed with its EFFECTIVE relationships, NOT deduped by declaration, because pairing is a property of the navigating entity and an inherited M:N can pair from one subtype and not another. Before the ruling this loaded clean and then diverged: TS and C# warned and emitted no traversal route (a silent 404), while Java, Kotlin and Python failed the build. Gated by `fixtures/conformance/error-relationship-m2m-junction-unpairable/`. - Index subtypes: `index.lookup` (non-unique retrieval index; uniqueness is encoded in the **type**: `identity.secondary` = unique alternate key, `index.lookup` = non-unique; `@unique` is REMOVED from `identity.secondary` — `ERR_UNKNOWN_ATTR` on any legacy `@unique`). RDB-physical escapes `@using`/`@expr`/`@where`/`@orders` are registered by the db provider on **both** `identity.secondary` and `index.lookup`. `index.fulltext` / `index.vector` / `index.spatial` are reserved on the subtype axis — documented, NOT registered (YAGNI + 1.0 vocab freeze). See [ADR-0040](spec/decisions/ADR-0040-index-type-and-secondary-key-purity.md). - Layout subtypes: `dataGrid` -- API subtypes: `api.base` / `api.operational` (request/response surface, a root child; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `binding.rest` (`@method`, `@path`) now, `messaging`/`grpc` reserved; the event/streaming sibling of `api.operational` is reserved). Children: `operation.query` (`@outputRef`, `@many`) / `operation.command` (`@inputRef` → `object.value`, `@transitions`, `@errors`); both take `@inputRef`, `@outputRef`, `@objectRef` (only when the target cannot be derived), `@permission`, `@public`. Derived CRUD (FR-008/009) stays the zero-config default; declared `api` extends it. Org-tier modeling (application/service/network/deployment) stays OUT of core — provider SPI, FQN references. See [ADR-0030](spec/decisions/ADR-0030-declared-api-surface-and-org-tier-boundary.md). **Registered in all five ports since 1.3.0, experimental** (may change in a MINOR) ([ADR-0066](spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)), with the loader rules (`error-rules-*` fixtures) and the `verify` rules gate (`fixtures/rules-check-conformance/`); the flat generators generate nothing from it (`fixtures/codegen-noop/rules/`); the ADR-0067 layer generators do (C# `rules-names` and `contract-types` so far). +- API subtypes: `api.base` / `api.operational` (request/response surface, a root child; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `binding.rest` (`@method`, `@path`) now, `messaging`/`grpc` reserved; the event/streaming sibling of `api.operational` is reserved). Children: `operation.query` (`@outputRef`, `@many`) / `operation.command` (`@inputRef` → `object.value`, `@transitions`, `@errors`); both take `@inputRef`, `@outputRef`, `@objectRef` (only when the target cannot be derived), `@permission`, `@public`. Derived CRUD (FR-008/009) stays the zero-config default; declared `api` extends it. Org-tier modeling (application/service/network/deployment) stays OUT of core — provider SPI, FQN references. See [ADR-0030](spec/decisions/ADR-0030-declared-api-surface-and-org-tier-boundary.md). **Registered in all five ports since 1.3.0, experimental** (may change in a MINOR) ([ADR-0066](spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)), with the loader rules (`error-rules-*` fixtures) and the `verify` rules gate (`fixtures/rules-check-conformance/`); the flat generators generate nothing from it (`fixtures/codegen-noop/rules/`); the ADR-0067 layer generators do (`rules-names` and `contract-types` in TypeScript and C#, and the TypeScript `service` and `service-routes` for derived CRUD so far). - Transition subtypes: `transition.action` (a child of `field.enum` on an `object.entity`: `@from`, `@to`, `@condition` in the validators' grammar, `@permission`, `@public`); `transition.base` is the abstract root and `transition.timed` is reserved, not registered. An enum with a transition IS a lifecycle — states, initial state (`@default`), terminal states and each unclaimed transition's command are derived, never declared (ADR-0066). A transition's `@from` lists enum members, not object references: every port's ref-bearing-attr check excludes `transition.*` nodes. A lifecycle belongs to the declaring entity and its `extends` descendants, NEVER to an entity whose field merely `extends` the lifecycle field (filter by the declaring field's owner); a command claims a transition NODE for its target and every entity extending it. Transition and operation names compare case-insensitively; operation names are unique per PACKAGE across its APIs, except one operation declared identically in two APIs (a versioned API). A lifecycle on an entity with no source loads and is inert (no derived command, no permission checks); the writable-source check applies once a source exists. A `@permission` is a dotted identifier path (a package prefix may use `::`); an absent one derives `.` for an operation and `..` for a transition's command. - Currency attrs: `@currency` (ISO 4217), `@locale` (BCP 47) - Schema attrs: `@schema` on `source.rdb` (DB schema name; Postgres default `public`, SQLite rejects non-default values) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1deba5648e..420429abf8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,18 @@ here.** ## [Unreleased] +- **codegen-ts: the service layer, part 1 (ADR-0067 layers 4 and 5).** Two new generators, neither + scaffolded. `service` (the new `service` layer label, shared by every port's catalog) writes one + module per metadata package: a function per derived list, get, create, update and delete of each + concrete, table-backed, single-key entity, every write in one transaction (a savepoint inside a + caller's `opts.tx`) that loads the row under a row lock and then validates and stamps the input + with the declared write rules (ADR-0045), and `createService(deps)`. `service-routes` writes + the thin Fastify transport over it, one plugin per package. A new api-contract lane runs the + shared corpus against the service behind its transport, in both layouts, and passes as the flat + routes do; a compile gate builds the tier in every dialect. `@metaobjectsdev/runtime-ts` gains + the `./service` and `./service/fastify` entries they import, and `meta eject` copies them. + Write-through, TPH, many-to-many, projections, reports, transitions and declared operations stay + on the flat generators for now: [docs/features/business-rules.md](docs/features/business-rules.md#the-service-layer-typescript). - **runtime-ts: a list with no `limit` answers 50 rows (breaking).** A generated entity or projection list in a project that sets no `api.pagination` returned every matching row when the request carried no `limit`; it now answers the first 50, the default of every port. An explicit diff --git a/agent-context/skills/metaobjects-codegen/SKILL.md b/agent-context/skills/metaobjects-codegen/SKILL.md index c30d6fc156..5331ea6a0a 100644 --- a/agent-context/skills/metaobjects-codegen/SKILL.md +++ b/agent-context/skills/metaobjects-codegen/SKILL.md @@ -344,12 +344,13 @@ A library row also carries `provides` (what is in the box) and, under `--probe`, added here, which of your entities `extends` into it, and any generator the library implies that you have not wired. -### The six layers, and what picks them +### The seven layers, and what picks them | layer | what it is | chosen by | |---|---|---| | `model` | entity/DTO/value-object modules and the constants beside them | app shape | | `persistence` | how rows are read and written | app shape | +| `service` | one module per package that runs each operation in a transaction with the write rules (ADR-0067); its transport is on `api` | app shape | | `api` | the HTTP surface — pick one framework | app shape | | `client` | the browser tier | app shape | | `docs` | model pages, api reference, agent pages, requirement ledger — each its own generator entry, like any other | app shape | diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index a6c67805dc..0bcd8f5e30 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -21,8 +21,12 @@ TypeScript it writes the shapes and errors an operation takes and returns (see [The contract types layer](#the-contract-types-layer-typescript)), and in C# so far each entity's create and update records ([C# port](../ports/csharp.md)). The TypeScript runtime makes the guarded update a transition writes, `ObjectManager.guardedUpdate`, held to the shared -persistence scenario `guarded-update.yaml`. The service shells that -enforce these rules at run time are later work. A lifecycle in a project +persistence scenario `guarded-update.yaml`. The service layer starts in TypeScript: `service` writes +each package's derived list, get, create, update and delete, every write in one transaction with the +declared write rules, behind a thin Fastify transport (`service-routes`) that answers the shared API +tests as the flat routes do (see [The service layer](#the-service-layer-typescript)). Transitions, +declared operations, the policy, the bodies and events interfaces, and the checks that enforce these +rules at run time are later work. A lifecycle in a project that wires none will be advised by `verify` once that check lands; today the flat routes enforce nothing and `verify` says nothing about it. Every flat generator writes byte-identical code for a model with this vocabulary and the same model without it. The design is [ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md). @@ -336,6 +340,55 @@ export type OpenRequestsError = ErrorBody/service/.ts`: one function per operation, `(deps, ...args, opts) => + OpResult`. Each concrete entity with a writable table and a single-field key gets five: + `list`, `get`, `create`, `update` and `delete`. +- `/service/index.ts`: `ServiceDeps` (the database), the `Service` interface, + `createService(deps)` that binds the operations to it, and each entity's wire mapper. + +Every write runs in one transaction, in ADR-0067's order: load the row under a row lock (`not_found` +when there is none), validate the input and stamp what the model declares (ADR-0045: `@autoSet`, +write-once fields, server-owned and unknown keys), then write it. A caller that runs several +operations atomically passes its own transaction as `opts.tx`, and each operation runs in a +savepoint inside it. A refusal rolls the transaction back. A query opens no write transaction. +An operation answers an `OpResult`: the value, or a failure carrying the code and the HTTP status +the [API contract](api-contract.md) gives it, so every transport maps it the same way. + +`serviceRoutesFile()` (stable name `service-routes`, layer `api`, Fastify) writes the thin +transport (layer 5) beside it, `/transport/fastify.ts`: one plugin per package, +registered with the service it calls. Each route parses the request, calls one operation and +sends what it answered; it holds no rules and no database handle. + +```ts +import { createShopService } from "./generated/acme/shop/service/index.js"; +import { shopServiceRoutes } from "./generated/acme/shop/transport/fastify.js"; + +const service = createShopService({ db }); +await app.register(shopServiceRoutes, { service }); + +// A job calls the same operations, here two in one transaction: +await db.transaction(async (tx) => { + await service.createOrder({ title: "first" }, { tx }); + await service.createOrder({ title: "second" }, { tx }); +}); +``` + +Both import the entity module (`entity`, for the table and the allowlists) and the contract types +(`contract-types`), written to the same target, and `@metaobjectsdev/runtime-ts`'s `service` and +`service/fastify` entries; `meta eject service` and `meta eject service-routes` copy that source into +`codegen/runtime/` as they do for the routes. The service lane of the shared API tests runs the +corpus the flat routes pass against the service behind this transport, in both layouts. + +Not covered yet, and still served by the flat generators: write-through entities, single-table (TPH) +hierarchies, many-to-many traversal, projections and reports. Transitions and declared operations +come with the policy, bodies and events interfaces. + ## Requirements can claim operations and transitions A level 5 requirement's `implementedBy` can name an operation as `.`, or a diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index 231f3a33b2..8d0c9c9e22 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -749,6 +749,17 @@ imports `zod` only. It is not scaffolded; add it to `generators` or `meta eject and give it its own `target` to put the layer in a package the transport and clients share. See [Business rules](../features/business-rules.md#the-contract-types-layer-typescript). +### `service/` and `transport/` — the service layer and its Fastify transport + +`serviceFile()` (stable name `service`, layer `service`) is layer 4 of ADR-0067. It writes one +module per metadata package, under the package's directory in either layout: a file per operation +in `/service/` (each entity's derived list, get, create, update and delete, every write in +one transaction with the declared write rules) and `service/index.ts` with the `Service` +interface and `createService(deps)`. `serviceRoutesFile()` (stable name `service-routes`) +writes `/transport/fastify.ts`, the routes that call it. Both need `entity` and +`contract-types` in the same target. Neither is scaffolded; add them to `generators` or `meta eject` +them. See [Business rules](../features/business-rules.md#the-service-layer-typescript). + ### Prove it works Boot the server: diff --git a/fixtures/generator-registry-conformance/README.md b/fixtures/generator-registry-conformance/README.md index e2c95402d8..d1595a21f3 100644 --- a/fixtures/generator-registry-conformance/README.md +++ b/fixtures/generator-registry-conformance/README.md @@ -24,7 +24,7 @@ spelled identically everywhere** (e.g. the REST surface is `routes` in every port, never `controller`/`router`). That cross-port spelling stability is the whole point. -## `layer` — the six values, and why six +## `layer` — the seven values, and why seven `layer` is the grouping an adopter (increasingly an LLM in their repo) **selects by**. Codegen is opt-in: nothing runs until it is chosen, so the catalog's job is @@ -34,15 +34,16 @@ to make the choice cheap, and `layer` is the axis it is cheap along. |---|---|---| | `model` | entity, names, rules-names, contract-types, barrel, dto, value-object | app shape | | `persistence` | queries, prisma-schema, db-context, repository, exposed-table, relations, stored-proc | app shape | -| `api` | routes, routes-hono, filter-allowlist, validator, spring-config, contract-schema, openapi | app shape | +| `service` | service | app shape: the operations a route, a job or an agent tool calls (ADR-0067 §5.6) | +| `api` | routes, routes-hono, service-routes, filter-allowlist, validator, spring-config, contract-schema, openapi | app shape | | `client` | form, hooks, grid, grid-hook, client, commands | app shape | | `docs` | docs, api-docs, requirements, agent-docs, metamodel-docs, docs-site, plantuml, html-docs, ai-docs | declared in the project's generator list like any other; nothing is generated that the list does not declare (ADR-0034 Amendment 9) | | `capability` | prompt-render, output-parser, output-prompt, extractor, render-helper, trace-helper, requirement-tests, cube-model, shared-model, template, callable, json-schema, mustache | `meta gen --list --probe` | -Six, not ten. An earlier draft split `capability` into `trace` / `requirements` / +Seven, not ten. An earlier draft split `capability` into `trace` / `requirements` / `publish` / `primitive`, each with **one member** — a layer with one member does no grouping work, and the split conflated two different kinds of choice. The -first four layers are app-shape decisions a builder makes. `capability` holds the +first five layers are app-shape decisions a builder makes. `capability` holds the ones the **model has already made**: nobody picks `prompt-render` by browsing a taxonomy, they pick it because they declared a `template.prompt`. `--probe` constructs every generator and dry-runs it against the real model, so @@ -51,7 +52,12 @@ information than a category name — and unlike a category name it cannot go sta because it does not describe the generators, it runs them. `capability` looking like a large undifferentiated bucket is therefore the point, -not a defect to be tidied. Do not add a seventh value to make it look tidier. +not a defect to be tidied. Do not add a value to make it look tidier. + +`service` is the one value added since, and not for tidiness: ADR-0067 §5.6 names it. It is +the layer between persistence and the transport (the operations, each write in one +transaction), a choice a builder makes on its own (a project can serve the flat `routes` with +no service at all), and it will hold one generator per port as each port adds its own. `layer` rather than a reuse of "tier", which is already taken twice (native/neutral in ADR-0020, and server/UI elsewhere). @@ -129,6 +135,11 @@ shapes, the operations' inputs and outputs, and the wire error bodies, with no p mapping; C# so far writes the create and update records). Each other port adds itself to their `ports` with its own rules-layer work. +Two names are **TypeScript only for now**: `service`, layer 4 (one module per package, a +function per operation, each write in one transaction with the declared write rules), and +`service-routes`, its thin Fastify transport (layer 5). Each other port adds itself with its own +service-layer work. + ## Changing the surface Adding, removing, or renaming a generator means editing **both** `registry.json` diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index fa7d90160d..0e9d02fe5e 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -118,6 +118,20 @@ "eject": "full", "ports": ["typescript", "csharp"] }, + "service": { + "concept": "The service layer (ADR-0067 layer 4): one module per metadata package, a function per operation, and a factory that binds them to the dependencies passed in. Each store-backed entity gets its derived list, get, create, update and delete; every write runs in one transaction (a savepoint inside a caller's) with the declared write rules (ADR-0045). TypeScript so far, behind its own transport (`service-routes`); the other ports add theirs with their rules-layer work.", + "tier": "native", + "layer": "service", + "eject": "full", + "ports": ["typescript"] + }, + "service-routes": { + "concept": "A thin REST transport over the service layer (ADR-0067 layer 5), one per metadata package: each route parses the request, calls one service operation and sends what it answered, and holds no rules. It answers the shared REST contract as `routes` does. TypeScript (Fastify) so far.", + "tier": "native", + "layer": "api", + "eject": "full", + "ports": ["typescript"] + }, "prompt-render": { "concept": "Per-template.prompt render handle over the render engine, aggregated into one module. TYPESCRIPT ONLY by design: the other four ports emit a prompt's render helper from `render-helper` (see its note) rather than a second generator.", "tier": "native", @@ -430,6 +444,7 @@ "codegen-ts/src/requirement-walk.ts", "codegen-ts/src/routes-expose.ts", "codegen-ts/src/rules-walk.ts", + "codegen-ts/src/service-walk.ts", "codegen-ts/src/source-detect.ts", "codegen-ts/src/templates/entity-ui-descriptor.ts", "codegen-ts/src/templates/find-inbound.ts", diff --git a/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryConformanceTests.cs index db816a8609..beb0d56f18 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryConformanceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryConformanceTests.cs @@ -18,7 +18,7 @@ namespace MetaObjects.Codegen.Tests; /// (3) tier agreement — every native manifest name is non-neutral in the registry /// (C# has no neutral generators per the manifest); /// (4) layer agreement — every manifest name's layer equals the registry's, -/// and every manifest entry declares one of the six. +/// and every manifest entry declares one of the seven. /// /// On mismatch this REPORTS the exact diff (extras / missing / tier / layer) so the /// manifest and registry can be reconciled. It never mutates either. @@ -48,7 +48,7 @@ private sealed record ManifestEntry( // enum would make this gate agree with whatever the code says, which is the one // thing a conformance gate must not do. private static readonly string[] AllowedLayers = - ["model", "persistence", "api", "client", "docs", "capability"]; + ["model", "persistence", "service", "api", "client", "docs", "capability"]; private static IReadOnlyList LoadManifest() { @@ -136,9 +136,9 @@ public void LayerAgreement_ManifestLayers_MatchRegistry() string.Join("\n ", layerMismatches)); } - /// (4b): every manifest entry — every port's — declares one of the six. + /// (4b): every manifest entry — every port's — declares one of the seven. [Fact] - public void EveryManifestEntry_DeclaresOneOfTheSixLayers() + public void EveryManifestEntry_DeclaresOneOfTheSevenLayers() { var bad = LoadManifest() .Where(e => !AllowedLayers.Contains(e.Layer)) diff --git a/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs b/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs index 6a6e57b4b1..c79c4fb4d3 100644 --- a/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs +++ b/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs @@ -35,12 +35,12 @@ public enum GeneratorTier } /// -/// The six layers a generator can belong to — the axis an adopter SELECTS BY, gated +/// The seven layers a generator can belong to — the axis an adopter SELECTS BY, gated /// cross-port against fixtures/generator-registry-conformance/registry.json /// exactly as is. /// /// -/// Six, not ten. An earlier draft split Capability four ways, each with ONE +/// Seven, not ten: the six below plus Service, the shells of ADR-0067 layer 4. An earlier draft split Capability four ways, each with ONE /// member — a layer with one member does no grouping work. The first four layers are /// app-shape decisions a builder makes; Capability holds the ones the MODEL has /// already made (you declared a template.prompt), which is why they are found by @@ -52,6 +52,8 @@ public enum GeneratorLayer Model, /// Query helpers, DbContext, repositories, table objects. Persistence, + /// The service shells that enforce the declared rules (ADR-0067 layer 4). + Service, /// HTTP surface: routes, filter allowlists, validators, wiring. Api, /// Browser tier: forms, hooks, grids. diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/GeneratorRegistryConformanceTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/GeneratorRegistryConformanceTest.kt index 98754843af..9f2bbd595b 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/GeneratorRegistryConformanceTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/GeneratorRegistryConformanceTest.kt @@ -23,7 +23,7 @@ import kotlin.test.assertTrue * (3) tier agreement — every native manifest name is NATIVE in the registry * (Kotlin has no neutral generators per the manifest); * (4) layer agreement — every manifest name's `layer` equals the registry's, and - * every manifest entry declares one of the six. + * every manifest entry declares one of the seven. * * On mismatch this REPORTS the exact diff (missing / extra / tier / layer) so the manifest * and registry can be reconciled. It never mutates either. Repo-root resolution @@ -38,7 +38,7 @@ class GeneratorRegistryConformanceTest { * [GeneratorLayer]. Enumerating the enum would make this gate agree with whatever * the code says, which is the one thing a conformance gate must not do. */ - private val allowedLayers = setOf("model", "persistence", "api", "client", "docs", "capability") + private val allowedLayers = setOf("model", "persistence", "service", "api", "client", "docs", "capability") private val manifestPath: Path = run { var p: Path? = Path.of(System.getProperty("user.dir")).toAbsolutePath() @@ -146,9 +146,9 @@ class GeneratorRegistryConformanceTest { ) } - /** (4b): every manifest entry — every port's — declares one of the six. */ + /** (4b): every manifest entry — every port's — declares one of the seven. */ @Test - fun `every manifest entry declares one of the six layers`() { + fun `every manifest entry declares one of the seven layers`() { val bad = loadManifest() .filter { it.layer !in allowedLayers } .map { "${it.name}='${it.layer}'" } diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/GeneratorRegistry.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/GeneratorRegistry.java index 48070a1fb7..8529fa6f6d 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/GeneratorRegistry.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/GeneratorRegistry.java @@ -82,11 +82,11 @@ public enum Tier { } /** - * The six layers a generator can belong to — the axis an adopter SELECTS BY, + * The seven layers a generator can belong to — the axis an adopter SELECTS BY, * mirroring the manifest's {@code layer} field and gated against it exactly as * {@link Tier} is. * - *

Six, not ten. An earlier draft split {@code CAPABILITY} four ways, each with + *

Seven, not ten: the six below plus {@code SERVICE}, the shells of ADR-0067 layer 4. An earlier draft split {@code CAPABILITY} four ways, each with * ONE member — a layer with one member does no grouping work. The first four layers * are app-shape decisions a builder makes; {@code CAPABILITY} holds the ones the * MODEL has already made (you declared a {@code template.prompt}), which is why they @@ -97,6 +97,8 @@ public enum Layer { MODEL, /** Query helpers, DbContext, repositories, table objects. */ PERSISTENCE, + /** The service shells that enforce the declared rules (ADR-0067 layer 4). */ + SERVICE, /** HTTP surface: routes, filter allowlists, validators, wiring. */ API, /** Browser tier: forms, hooks, grids. */ diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/GeneratorRegistryConformanceTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/GeneratorRegistryConformanceTest.java index 3e814c0b0e..ab09cf3b93 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/GeneratorRegistryConformanceTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/GeneratorRegistryConformanceTest.java @@ -39,7 +39,7 @@ public class GeneratorRegistryConformanceTest { * code says, which is the one thing a conformance gate must not do. */ private static final Set ALLOWED_LAYERS = - Set.of("model", "persistence", "api", "client", "docs", "capability"); + Set.of("model", "persistence", "service", "api", "client", "docs", "capability"); /** * Registered stable names whose {@code classname} is deliberately NOT a wirable @@ -188,7 +188,7 @@ public void registryLayersAgreeWithManifest() throws Exception { } @Test - public void everyManifestEntryDeclaresOneOfTheSixLayers() throws Exception { + public void everyManifestEntryDeclaresOneOfTheSevenLayers() throws Exception { TreeSet bad = new TreeSet<>(); for (Map.Entry e : manifestLayers(loadManifest()).entrySet()) { if (!ALLOWED_LAYERS.contains(e.getValue())) { diff --git a/server/python/src/metaobjects/codegen/generator_registry.py b/server/python/src/metaobjects/codegen/generator_registry.py index c5385ff2eb..9cd7bb60bd 100644 --- a/server/python/src/metaobjects/codegen/generator_registry.py +++ b/server/python/src/metaobjects/codegen/generator_registry.py @@ -62,8 +62,8 @@ GeneratorTier = str # "native" | "neutral" -#: The six layers a generator can belong to — the axis an adopter SELECTS BY, gated -#: cross-port against the manifest exactly as ``tier`` is. Six, not ten: an earlier +#: The seven layers a generator can belong to — the axis an adopter SELECTS BY, gated +#: cross-port against the manifest exactly as ``tier`` is. Seven (the six plus ``service``, ADR-0067 layer 4), not ten: an earlier #: draft split ``capability`` four ways, each with ONE member, and a layer with one #: member does no grouping work. ``capability`` holds the generators the MODEL has #: already chosen (you declared a ``template.prompt``), which is why they are found @@ -71,6 +71,7 @@ GENERATOR_LAYERS: tuple[str, ...] = ( "model", "persistence", + "service", "api", "client", "docs", diff --git a/server/python/tests/conformance/test_generator_registry_conformance.py b/server/python/tests/conformance/test_generator_registry_conformance.py index 40bc220200..e612f2c181 100644 --- a/server/python/tests/conformance/test_generator_registry_conformance.py +++ b/server/python/tests/conformance/test_generator_registry_conformance.py @@ -94,10 +94,10 @@ def test_registry_layers_agree_with_manifest() -> None: assert not mismatches, "layer disagreement vs manifest:\n " + "\n ".join(mismatches) -def test_every_manifest_entry_declares_one_of_the_six_layers() -> None: +def test_every_manifest_entry_declares_one_of_the_seven_layers() -> None: # The closed set, spelled out rather than imported from the code: importing the # port's own tuple would make the gate agree with whatever the code says. - allowed = {"model", "persistence", "api", "client", "docs", "capability"} + allowed = {"model", "persistence", "service", "api", "client", "docs", "capability"} manifest = json.loads(_find_manifest().read_text()) bad = sorted( f"{name}={spec.get('layer')!r}" diff --git a/server/typescript/packages/cli/src/lib/install-set.ts b/server/typescript/packages/cli/src/lib/install-set.ts index 5f7c810cfa..b3de6f76a4 100644 --- a/server/typescript/packages/cli/src/lib/install-set.ts +++ b/server/typescript/packages/cli/src/lib/install-set.ts @@ -32,7 +32,7 @@ import type { PackageManifest } from "./package-manifest.js"; * Resolves the package's ENTRY and walks up to the nearest manifest, rather than asking * for `"/package.json"` directly. The direct form is the obvious one and it is * WRONG: a package's `exports` map gates every subpath, and `@metaobjectsdev/runtime-ts` - * exports `.` / `./drivers` / `./fastify` / `./drizzle-fastify` / `./hono` and no + * exports `.` / `./drivers` / `./fastify` / `./drizzle-fastify` / `./service` / `./service/fastify` / `./hono` and no * `./package.json`, so under real Node it throws ERR_PACKAGE_PATH_NOT_EXPORTED. It * appeared to work in-repo only because bun resolves a symlinked source tree; against * the published package it failed silently on the first try. Resolving the entry is diff --git a/server/typescript/packages/cli/src/lib/runtime-eject.ts b/server/typescript/packages/cli/src/lib/runtime-eject.ts index 688c23c6c2..f1c02d3622 100644 --- a/server/typescript/packages/cli/src/lib/runtime-eject.ts +++ b/server/typescript/packages/cli/src/lib/runtime-eject.ts @@ -38,6 +38,9 @@ export const RUNTIME_ENTRIES: Readonly = { "shared-model": { name: "shared", include: ["**"], version: "1.0.0" }, }; /** - * The three owned generators whose OUTPUT imports the HTTP adapter default to the copy + * The owned generators whose OUTPUT imports the runtime tier default to the copy * `meta eject` places under `codegen/runtime/`. The packaged ones import the package, so the * comparison binds the owned ones to it through the option that exists for the choice; what * is compared is the composition. (The local-copy spelling is gated by runtime-eject.test.ts.) @@ -305,6 +305,8 @@ const OWNED_OPTIONS: Record = { entity: { runtimeImport: HTTP_RUNTIME_PACKAGE }, routes: { runtimeImport: HTTP_RUNTIME_PACKAGE }, "routes-hono": { runtimeImport: HTTP_RUNTIME_PACKAGE }, + service: { runtimeImport: HTTP_RUNTIME_PACKAGE }, + "service-routes": { runtimeImport: HTTP_RUNTIME_PACKAGE }, }; type Factory = (opts?: unknown) => Generator; diff --git a/server/typescript/packages/codegen-ts/src/engine-surface.ts b/server/typescript/packages/codegen-ts/src/engine-surface.ts index 5b5b878b6f..df3bd8853c 100644 --- a/server/typescript/packages/codegen-ts/src/engine-surface.ts +++ b/server/typescript/packages/codegen-ts/src/engine-surface.ts @@ -68,6 +68,7 @@ export const ENGINE_MODULES: readonly string[] = [ "codegen-ts/src/requirement-walk.ts", "codegen-ts/src/routes-expose.ts", "codegen-ts/src/rules-walk.ts", + "codegen-ts/src/service-walk.ts", "codegen-ts/src/source-detect.ts", "codegen-ts/src/templates/entity-ui-descriptor.ts", "codegen-ts/src/templates/find-inbound.ts", diff --git a/server/typescript/packages/codegen-ts/src/engine.ts b/server/typescript/packages/codegen-ts/src/engine.ts index 84e5404fcc..5aa8fecabb 100644 --- a/server/typescript/packages/codegen-ts/src/engine.ts +++ b/server/typescript/packages/codegen-ts/src/engine.ts @@ -55,6 +55,7 @@ export * from "./requirement-walk.js"; export * from "./routes-expose.js"; export * from "./rules-walk.js"; export * from "./contract-walk.js"; +export * from "./service-walk.js"; export * from "./source-detect.js"; export * from "./templates/entity-ui-descriptor.js"; export * from "./templates/find-inbound.js"; diff --git a/server/typescript/packages/codegen-ts/src/generator-registry.ts b/server/typescript/packages/codegen-ts/src/generator-registry.ts index fa554036c0..3452954824 100644 --- a/server/typescript/packages/codegen-ts/src/generator-registry.ts +++ b/server/typescript/packages/codegen-ts/src/generator-registry.ts @@ -58,18 +58,22 @@ import { jsonSchemaFile, openApiFile, prismaSchemaFile, + serviceFile, + serviceRoutesFile, } from "./generators/index.js"; export type GeneratorTier = "native" | "neutral"; /** - * The six layers a generator can belong to — the axis an adopter SELECTS BY. + * The seven layers a generator can belong to — the axis an adopter SELECTS BY. * * Cross-port: `layer` is gated by every port's registry-conformance test against * `fixtures/generator-registry-conformance/registry.json`, exactly as `tier` is, so a * polyglot agent groups the catalog by the same words everywhere. * - * Six, not ten. The first four are app-shape decisions a builder makes; `docs` holds the + * Seven, not ten. The first four are app-shape decisions a builder makes, and `service` (ADR-0067 + * §5.6) the one between persistence and the transport: the operations a route, a job or an agent + * tool calls, each write in one transaction. `docs` holds the * pages written about the model and the code; `capability` holds the ones the MODEL has already made — nobody * picks `prompt-render` by browsing a taxonomy, they pick it because they declared a * `template.prompt`, which `meta gen --list --probe` reports with a real file count. A @@ -78,6 +82,7 @@ export type GeneratorTier = "native" | "neutral"; export const GENERATOR_LAYERS = [ "model", "persistence", + "service", "api", "client", "docs", @@ -287,6 +292,24 @@ export const generatorRegistry: Record = { ejectable: ejectable("prisma-schema"), }, + // ----- service ---------------------------------------------------------- + service: { + name: "service", + kind: "generator", + layer: "service", + description: + "The service layer (ADR-0067): one module per package, a function per derived list, get, create, update and delete, each write in one transaction with the declared write rules.", + tier: "native", + factory: () => serviceFile(), + factoryExport: "serviceFile", + options: "filter?, runtimeImport?, target?", + requires: ["entity", "contract-types"], + runtimePackages: ["@metaobjectsdev/runtime-ts"], + runtimePeers: ["drizzle-orm", "zod"], + configKeys: ["dialect", "extStyle", "outputLayout", "pluralizeCollections", "collectionNameOverrides"], + ejectable: ejectable("service"), + }, + // ----- api -------------------------------------------------------------- "contract-schema": { name: "contract-schema", @@ -339,6 +362,22 @@ export const generatorRegistry: Record = { configKeys: ["dbImport", "apiPrefix", "dialect", "extStyle", "outputLayout"], ejectable: ejectable("routes"), }, + "service-routes": { + name: "service-routes", + kind: "generator", + layer: "api", + description: "A thin Fastify transport per package over the service layer: each route parses, calls one operation and sends its result.", + tier: "native", + factory: () => serviceRoutesFile(), + factoryExport: "serviceRoutesFile", + options: "filter?, runtimeImport?, target?", + framework: "fastify", + requires: ["service", "contract-types"], + runtimePackages: ["@metaobjectsdev/runtime-ts"], + runtimePeers: ["fastify"], + configKeys: ["apiPrefix", "extStyle", "outputLayout"], + ejectable: ejectable("service-routes"), + }, "routes-hono": { name: "routes-hono", kind: "generator", diff --git a/server/typescript/packages/codegen-ts/src/generators/index.ts b/server/typescript/packages/codegen-ts/src/generators/index.ts index 7e9f8647bb..237e1225dd 100644 --- a/server/typescript/packages/codegen-ts/src/generators/index.ts +++ b/server/typescript/packages/codegen-ts/src/generators/index.ts @@ -31,6 +31,8 @@ export { routesFileHono, type RoutesFileHonoOpts } from "./routes-file-hono.js"; export { namesFile } from "./names-file.js"; export { rulesNamesFile, type RulesNamesFileOpts } from "./rules-names-file.js"; export { contractTypes, type ContractTypesFileOpts } from "./contract-types-file.js"; +export { serviceFile, type ServiceFileOpts } from "./service-file.js"; +export { serviceRoutesFile, type ServiceRoutesFileOpts } from "./service-routes-file.js"; export { reportExport, type ReportExportOpts } from "./report-export-file.js"; export { promptRender, type PromptRenderOpts } from "./prompt-render-file.js"; export { outputParser, type OutputParserOpts } from "./output-parser-file.js"; diff --git a/server/typescript/packages/codegen-ts/src/generators/service-file.ts b/server/typescript/packages/codegen-ts/src/generators/service-file.ts new file mode 100644 index 0000000000..4fcad9ceee --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/generators/service-file.ts @@ -0,0 +1,41 @@ +import { isMetaObject, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; +import type { EmittedFile, GenContext, Generator } from "../generator.js"; +import { serviceModelOf, serviceRenderContext } from "../service-walk.js"; +import { renderServiceFiles } from "../templates/service-file.js"; + +/** + * The service layer (ADR-0067 §1, layer 4): one module per metadata package, one file per + * operation, and `createService(deps)`. Each covered entity gets its derived list, get, + * create, update and delete; every write runs in one transaction with the declared write rules + * (ADR-0045). Hand-written code calls the service; a transport (`serviceRoutesFile()`) mounts it. + * + * Imports the entity module (the Drizzle table and allowlists, `entityFile()`) and the contract + * types (`contractTypes()`), so list both. The built-in twin of `src/reference/service.ts` + * (ADR-0034 scaffold-and-own); the reference-byte-identical gate holds the two to the same output. + * + * A SEPARATE generator: a project that does not list it sees no change (`fixtures/codegen-noop/rules`). + */ +export interface ServiceFileOpts { + /** Narrow which entities get operations. ANDed with the generator's own gates, so it can only narrow. */ + filter?: (entity: MetaObject) => boolean; + /** Where the emitted files import `@metaobjectsdev/runtime-ts/service` from. Absent: the package. */ + runtimeImport?: string; + /** Named output target. It must be the entity module's target. */ + target?: string; +} + +export function serviceFile(opts?: ServiceFileOpts): Generator { + const generator: Generator = { + name: "service", + generate: (ctx: GenContext): EmittedFile[] => { + const matches = (obj: MetaData): boolean => isMetaObject(obj) && ctx.matches(obj) && (ctx.selected?.(obj) ?? true); + const model = serviceModelOf(ctx.loadedRoot, { matches }); + if (model.length === 0) return []; + const rc = serviceRenderContext(ctx, "service", opts?.runtimeImport); + return model.flatMap((pkg) => renderServiceFiles(pkg, rc)); + }, + }; + if (opts?.filter) generator.filter = opts.filter; + if (opts?.target) generator.target = opts.target; + return generator; +} diff --git a/server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts b/server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts new file mode 100644 index 0000000000..ef2a809ff4 --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts @@ -0,0 +1,35 @@ +import { isMetaObject, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; +import type { EmittedFile, GenContext, Generator } from "../generator.js"; +import { serviceModelOf, serviceRenderContext } from "../service-walk.js"; +import { renderFastifyTransport } from "../templates/service-file.js"; + +/** + * The thin Fastify transport of the service layer (ADR-0067 §1, layer 5): one file per metadata + * package, `/transport/fastify.ts`, whose routes parse a request, call the package's + * service and send what it answered. It holds no rules, and it imports the service module and + * the contract types only. The built-in twin of `src/reference/service-routes.ts`. + */ +export interface ServiceRoutesFileOpts { + /** Narrow which entities get routes. Keep it the same as the service generator's. */ + filter?: (entity: MetaObject) => boolean; + /** Where the emitted file imports `@metaobjectsdev/runtime-ts/drizzle-fastify` from. Absent: the package. */ + runtimeImport?: string; + /** Named output target. It must be the entity module's target. */ + target?: string; +} + +export function serviceRoutesFile(opts?: ServiceRoutesFileOpts): Generator { + const generator: Generator = { + name: "service-routes", + generate: (ctx: GenContext): EmittedFile[] => { + const matches = (obj: MetaData): boolean => isMetaObject(obj) && ctx.matches(obj) && (ctx.selected?.(obj) ?? true); + const model = serviceModelOf(ctx.loadedRoot, { matches }); + if (model.length === 0) return []; + const rc = serviceRenderContext(ctx, "service-routes", opts?.runtimeImport); + return model.map((pkg) => renderFastifyTransport(pkg, rc)); + }, + }; + if (opts?.filter) generator.filter = opts.filter; + if (opts?.target) generator.target = opts.target; + return generator; +} diff --git a/server/typescript/packages/codegen-ts/src/owned-runtime.ts b/server/typescript/packages/codegen-ts/src/owned-runtime.ts index 0a530409a1..b10d1a255a 100644 --- a/server/typescript/packages/codegen-ts/src/owned-runtime.ts +++ b/server/typescript/packages/codegen-ts/src/owned-runtime.ts @@ -43,6 +43,11 @@ export const HTTP_RUNTIME_MODULES = { "drizzle-fastify": { subpath: "drizzle-fastify", file: "drizzle-fastify/index" }, hono: { subpath: "hono", file: "hono/index" }, allowlists: { subpath: "drizzle-fastify", file: "drizzle-fastify/filter-allowlist" }, + // The store mechanics a generated service shell calls (ADR-0067 layer 4): no web framework. + service: { subpath: "service", file: "service/index" }, + // What the service layer's thin Fastify transport (ADR-0067 layer 5) imports: its own entry, so + // the flat routes' adapter is untouched. + "service-fastify": { subpath: "service/fastify", file: "service/fastify" }, } as const; export type HttpRuntimeModule = keyof typeof HTTP_RUNTIME_MODULES; diff --git a/server/typescript/packages/codegen-ts/src/reference-templates.ts b/server/typescript/packages/codegen-ts/src/reference-templates.ts index 3c16567b32..8e4ea735e6 100644 --- a/server/typescript/packages/codegen-ts/src/reference-templates.ts +++ b/server/typescript/packages/codegen-ts/src/reference-templates.ts @@ -21,6 +21,9 @@ export const REFERENCE_GENERATOR_NAMES = [ // The contract types (ADR-0067 layer 1): the modules' shape is the adopter's, while which objects, // values and operations are covered stays the engine walk. "contract-types", + // The service layer and its Fastify transport (ADR-0067 layers 4 and 5): the operations' and the + // routes' shape is the adopter's, while which entities get operations stays the engine walk. + "service", "service-routes", // The report export (`?format=csv|json|xml` on a served report): which reports get a module, the // column list and the CSV/XML writers, handed over as one file. "report-export", diff --git a/server/typescript/packages/codegen-ts/src/reference/service-routes.ts b/server/typescript/packages/codegen-ts/src/reference/service-routes.ts new file mode 100644 index 0000000000..a140e067cc --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/reference/service-routes.ts @@ -0,0 +1,62 @@ +// REFERENCE TEMPLATE — copy this into your repo (e.g. codegen/generators/service-routes.ts) and own it. +// Then import it LOCALLY in metaobjects.config.ts: +// import { serviceRoutesFile } from "./codegen/generators/service-routes.js"; +// +// RUNTIME: this file executes under whatever runs `meta gen`, and the published CLI's +// shebang is `#!/usr/bin/env node` — so it runs under NODE even in a Bun project. Do not +// reach for `Bun.*` globals here; use `node:` builtins instead. +// targets: the emit step. Replace `renderFastifyTransport` in `../templates/service-file.js` +// to change the routes' SHAPE (a hook on every route, another status); keep +// `serviceModelOf` so the routes cover exactly what the service does. +// use-when: the service layer (service.ts) is served over REST on Fastify. +// emits: /transport/fastify.ts per package with a covered entity: one Fastify +// plugin, `ServiceRoutes`, registered with the service it calls +// (`app.register(blogServiceRoutes, { service })`). Each route parses the request, +// calls one operation and sends what it answered; it holds no rules. +// runtime: the emitted file imports the request and reply helpers (`service/fastify` of +// @metaobjectsdev/runtime-ts). `meta eject service-routes` copies that source into +// `codegen/runtime/` and the file imports the copy; `runtimeImport: +// "@metaobjectsdev/runtime-ts"` goes back to the package. +// customize: swap the renderer; narrow with `filter` (keep it the same as the service's). +// composes-with: service.ts and contract-types.ts, in the same target. +import { + ownedRuntimeImport, + serviceModelOf, + serviceRenderContext, + type EmittedFile, + type GenContext, + type Generator, +} from "@metaobjectsdev/codegen-ts/engine"; +import { renderFastifyTransport } from "../templates/service-file.js"; +import { isMetaObject, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; + +export interface ServiceRoutesFileOpts { + /** Narrow which entities get routes. Keep it the same as the service generator's. */ + filter?: (entity: MetaObject) => boolean; + /** + * Where the emitted file imports the request and reply helpers from. Absent: the copy + * `meta eject service-routes` placed in `codegen/runtime/`. `"@metaobjectsdev/runtime-ts"` + * imports the package instead. + */ + runtimeImport?: string; + /** Named output target. It must be the entity module's target. */ + target?: string; +} + +export function serviceRoutesFile(opts?: ServiceRoutesFileOpts): Generator { + const generator: Generator = { + name: "service-routes", + generate: (ctx: GenContext): EmittedFile[] => { + const matches = (obj: MetaData): boolean => isMetaObject(obj) && ctx.matches(obj) && (ctx.selected?.(obj) ?? true); + const model = serviceModelOf(ctx.loadedRoot, { matches }); + if (model.length === 0) return []; + const runtimeImport = + opts?.runtimeImport ?? (ctx.renderContext && ownedRuntimeImport(ctx.projectRoot ?? ".", ctx.renderContext.selfTarget.outDir)); + const rc = serviceRenderContext(ctx, "service-routes", runtimeImport); + return model.map((pkg) => renderFastifyTransport(pkg, rc)); + }, + }; + if (opts?.filter) generator.filter = opts.filter; + if (opts?.target) generator.target = opts.target; + return generator; +} diff --git a/server/typescript/packages/codegen-ts/src/reference/service.ts b/server/typescript/packages/codegen-ts/src/reference/service.ts new file mode 100644 index 0000000000..d3faed08c3 --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/reference/service.ts @@ -0,0 +1,68 @@ +// REFERENCE TEMPLATE — copy this into your repo (e.g. codegen/generators/service.ts) and own it. +// Then import it LOCALLY in metaobjects.config.ts: +// import { serviceFile } from "./codegen/generators/service.js"; +// +// RUNTIME: this file executes under whatever runs `meta gen`, and the published CLI's +// shebang is `#!/usr/bin/env node` — so it runs under NODE even in a Bun project. Do not +// reach for `Bun.*` globals here; use `node:` builtins instead. +// targets: the emit step. Replace `renderServiceFiles` in `../templates/service-file.js` to +// change an operation's SHAPE (an extra step, a different result type); keep +// `serviceModelOf` so which entities get operations and what they are named stays +// the packaged walk. +// use-when: a route, a job, a queue consumer or an agent tool runs the model's writes, and +// every write has to take the same transaction and the same write rules. +// emits: /service/.ts (one function per derived list, get, create, +// update and delete of every covered entity) and /service/index.ts (the +// `Service` interface, `createService(deps)` and each entity's wire +// mapper), in either layout. A package with no covered entity gets no file. +// runtime: the emitted files import the store mechanics (`service/` of +// @metaobjectsdev/runtime-ts: the transaction, the row lock, the read-back, the +// list query). `meta eject service` copies that source into `codegen/runtime/` +// and the files import the copy; `runtimeImport: "@metaobjectsdev/runtime-ts"` +// goes back to the package. +// customize: swap the renderers; narrow with `filter`. +// composes-with: entity.ts (the Drizzle table and the allowlists) and contract-types.ts (the +// shapes and schemas), both required in the same target; service-routes.ts mounts +// the service on Fastify. +// +// A SEPARATE generator: a project that does not list it sees no change (fixtures/codegen-noop/rules). +import { + ownedRuntimeImport, + serviceModelOf, + serviceRenderContext, + type EmittedFile, + type GenContext, + type Generator, +} from "@metaobjectsdev/codegen-ts/engine"; +import { renderServiceFiles } from "../templates/service-file.js"; +import { isMetaObject, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; + +export interface ServiceFileOpts { + /** Narrow which entities get operations. ANDed with the generator's own gates, so it can only narrow. */ + filter?: (entity: MetaObject) => boolean; + /** + * Where the emitted files import the store mechanics from. Absent: the copy `meta eject service` + * placed in `codegen/runtime/`. `"@metaobjectsdev/runtime-ts"` imports the package instead. + */ + runtimeImport?: string; + /** Named output target. It must be the entity module's target. */ + target?: string; +} + +export function serviceFile(opts?: ServiceFileOpts): Generator { + const generator: Generator = { + name: "service", + generate: (ctx: GenContext): EmittedFile[] => { + const matches = (obj: MetaData): boolean => isMetaObject(obj) && ctx.matches(obj) && (ctx.selected?.(obj) ?? true); + const model = serviceModelOf(ctx.loadedRoot, { matches }); + if (model.length === 0) return []; + const runtimeImport = + opts?.runtimeImport ?? (ctx.renderContext && ownedRuntimeImport(ctx.projectRoot ?? ".", ctx.renderContext.selfTarget.outDir)); + const rc = serviceRenderContext(ctx, "service", runtimeImport); + return model.flatMap((pkg) => renderServiceFiles(pkg, rc)); + }, + }; + if (opts?.filter) generator.filter = opts.filter; + if (opts?.target) generator.target = opts.target; + return generator; +} diff --git a/server/typescript/packages/codegen-ts/src/service-walk.ts b/server/typescript/packages/codegen-ts/src/service-walk.ts new file mode 100644 index 0000000000..3cd73e5b53 --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/service-walk.ts @@ -0,0 +1,173 @@ +// What the service layer covers (ADR-0067 §1, layer 4), for one model. +// +// Engine, not emit: `serviceFile()` and `serviceRoutesFile()` render these records, and an ejected +// copy of either keeps calling this walk, so which objects get a service operation, what the +// operations are named and where their files go stays packaged while the files' shape is the +// adopter's. +// +// Covered: every concrete `object.entity` whose primary source is a writable `source.rdb`, keyed +// by a single-field primary identity. It gets the five derived operations: list, get, create, +// update and delete. Not covered yet: a write-through entity (reads through a replica view), a +// single-table (TPH) hierarchy, many-to-many traversal, projections and reports, and the +// transition commands and declared operations of ADR-0066 (later service work, which adds the +// policy, bodies and events interfaces). + +import { IDENTITY_ATTR_FIELDS, isMetaObject, OBJECT_SUBTYPE_ENTITY, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; +import { packageToPath } from "./import-path.js"; +import { posix } from "node:path"; +import { contractSpecifier } from "./contract-walk.js"; +import { HTTP_RUNTIME_MODULES, HTTP_RUNTIME_PACKAGE, type HttpRuntimeModule } from "./owned-runtime.js"; +import type { ExtStyle, RenderContext } from "./render-context.js"; +import type { GenContext } from "./generator.js"; +import { effectivePackage } from "./docs-paths.js"; +import { hasWritableRdbSource } from "./source-detect.js"; +import { isAbstract } from "./instance-artifacts.js"; +import { isWriteThrough } from "./projection/projection-detector.js"; +import { declaresTphDiscriminator, isTphSubtype } from "./tph.js"; +import { pkInfoOf } from "./pk-resolver.js"; +import { listFnName, toCamelCase, toPascalCase } from "./naming.js"; + +/** The folder a package's service files go in, under the package's directory in either layout. */ +export const SERVICE_DIR = "service"; + +/** The service module's index file: the operations interface and its factory. */ +export const SERVICE_INDEX_FILE = "index.ts"; + +/** The five derived operations of an entity, in the order the files and the interface list them. */ +export const DERIVED_OPERATIONS = ["list", "get", "create", "update", "delete"] as const; +export type DerivedOperation = (typeof DERIVED_OPERATIONS)[number]; + +/** One entity's service operations. */ +export interface ServiceEntity { + readonly obj: MetaObject; + /** The field the primary identity names: the key a get, update or delete takes. */ + readonly keyField: string; + /** The function name of each derived operation (`listAuthors`, `getAuthor`, ...). */ + readonly operations: Readonly>; +} + +/** One metadata package's service module. */ +export interface ServicePackage { + readonly package: string; + readonly entities: readonly ServiceEntity[]; +} + +export interface ServiceWalkOpts { + /** Narrow which objects are covered (the generator's `filter` and the run's selection). */ + matches?: (obj: MetaObject) => boolean; +} + +/** Whether `obj` gets the derived service operations. */ +export function hasServiceOperations(obj: MetaObject): boolean { + if (obj.subType !== OBJECT_SUBTYPE_ENTITY || isAbstract(obj)) return false; + if (!hasWritableRdbSource(obj) || isWriteThrough(obj)) return false; + if (declaresTphDiscriminator(obj) || isTphSubtype(obj)) return false; + return serviceKeyField(obj) !== undefined; +} + +/** The single field a service operation addresses a row by, or undefined for a composite or absent key. */ +export function serviceKeyField(obj: MetaObject): string | undefined { + const pk = pkInfoOf(obj); + if (pk === undefined) return undefined; + const fields = obj.primaryIdentity()?.attr(IDENTITY_ATTR_FIELDS); + if (Array.isArray(fields) && fields.length !== 1) return undefined; + return pk.fieldName; +} + +/** The derived operation names of `obj`. */ +export function serviceOperationNames(obj: MetaObject): Readonly> { + return { + list: listFnName(obj), + get: `get${obj.name}`, + create: `create${obj.name}`, + update: `update${obj.name}`, + delete: `delete${obj.name}`, + }; +} + +/** The service modules of `root`, one per package that has a covered entity, sorted by package. */ +export function serviceModelOf(root: MetaData, opts: ServiceWalkOpts = {}): ServicePackage[] { + const matches = opts.matches ?? (() => true); + const packages = new Map(); + for (const obj of root.children().filter(isMetaObject)) { + if (!hasServiceOperations(obj) || !matches(obj)) continue; + const pkg = effectivePackage(obj) ?? ""; + const list = packages.get(pkg) ?? []; + packages.set(pkg, list); + list.push({ obj, keyField: serviceKeyField(obj)!, operations: serviceOperationNames(obj) }); + } + return [...packages.keys()].sort().map((pkg) => ({ package: pkg, entities: packages.get(pkg)! })); +} + +/** Where a file of package `pkg`'s service module goes, relative to the target's outDir. */ +export function servicePath(pkg: string, file: string): string { + const dir = packageToPath(pkg); + return dir === "" ? `${SERVICE_DIR}/${file}` : `${dir}/${SERVICE_DIR}/${file}`; +} + +/** The name of package `pkg`'s service type: its last segment, PascalCase, plus `Service` + * (`acme::purchasing` → `PurchasingService`, `acme::purchase_orders` → `PurchaseOrdersService`); + * the root package's is `ModelService`. */ +export function serviceTypeName(pkg: string): string { + const segments = pkg.split("::").filter((s) => s !== ""); + const last = segments[segments.length - 1]; + return `${last === undefined ? "Model" : toPascalCase(toCamelCase(last))}Service`; +} + +/** The factory that builds package `pkg`'s service: `create`. */ +export function serviceFactoryName(pkg: string): string { + return `create${serviceTypeName(pkg)}`; +} + +/** The Fastify plugin that mounts package `pkg`'s service routes: `Routes`. */ +export function serviceRoutesName(pkg: string): string { + const type = serviceTypeName(pkg); + return `${type.charAt(0).toLowerCase()}${type.slice(1)}Routes`; +} + +/** The folder a package's thin transport goes in (ADR-0067 layer 5): its own, beside the service + * module's, so each generator owns the paths it writes. */ +export const TRANSPORT_DIR = "transport"; + +/** The Fastify transport's file in {@link TRANSPORT_DIR}. */ +export const FASTIFY_TRANSPORT_FILE = "fastify.ts"; + +/** Where package `pkg`'s Fastify transport goes, relative to the target's outDir. */ +export function fastifyTransportPath(pkg: string): string { + const dir = packageToPath(pkg); + return dir === "" ? `${TRANSPORT_DIR}/${FASTIFY_TRANSPORT_FILE}` : `${dir}/${TRANSPORT_DIR}/${FASTIFY_TRANSPORT_FILE}`; +} + +/** + * The import specifier of a runtime module, as seen from the generated file at `fromFile` + * (relative to the target's outDir). The service and transport files sit one folder below their + * package's directory in either layout, so a relative `httpRuntimeImport` (an owned copy, ADR-0034 + * Amendment 3) is resolved from the file itself rather than from the package directory. + */ +export function runtimeSpecifierFrom( + fromFile: string, + module: HttpRuntimeModule, + ctx: { httpRuntimeImport?: string | undefined; extStyle: ExtStyle }, +): string { + const entry = HTTP_RUNTIME_MODULES[module]; + const base = ctx.httpRuntimeImport?.replace(/\/$/, ""); + if (base === undefined || base === HTTP_RUNTIME_PACKAGE) return `${HTTP_RUNTIME_PACKAGE}/${entry.subpath}`; + if (base.startsWith("./") || base.startsWith("../")) { + return contractSpecifier(fromFile, posix.normalize(`${base}/${entry.file}.ts`), ctx.extStyle); + } + return ctx.extStyle === "js" ? `${base}/${entry.file}.js` : `${base}/${entry.file}`; +} + +/** + * The render context a service-layer generator runs with. Refused when the run supplies none, or + * when the generator writes to another target than the entity module: the service and transport + * files import the entity module and the contract types by a relative path. + */ +export function serviceRenderContext(ctx: GenContext, generator: string, runtimeImport: string | undefined): RenderContext { + const rc = ctx.renderContext; + if (!rc) throw new Error(`${generator}: renderContext is required (provided by runGen)`); + if (rc.selfTarget.name !== rc.entityModuleTarget.name) { + throw new Error(`${generator}: write it to the entity module's target ("${rc.entityModuleTarget.name}"), not "${rc.selfTarget.name}"`); + } + return runtimeImport === undefined ? rc : { ...rc, httpRuntimeImport: runtimeImport }; +} diff --git a/server/typescript/packages/codegen-ts/src/templates/service-file.ts b/server/typescript/packages/codegen-ts/src/templates/service-file.ts new file mode 100644 index 0000000000..a51ac5cb34 --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/templates/service-file.ts @@ -0,0 +1,369 @@ +// The service layer (ADR-0067 §1, layer 4) and its thin Fastify transport (layer 5). +// +// A package's service module is a folder of files, one per operation, and an index that declares +// the operations interface and the factory that binds them to their dependencies: +// +// /service/.ts — one exported function: `(deps, ...args, opts) => OpResult` +// /service/index.ts — `ServiceDeps`, the `Service` interface, `createService`, +// and each entity's wire mapper +// /transport/fastify.ts — the routes: parse, call the service, send what it answered +// +// Every write operation runs in one transaction (a savepoint inside a caller's), in ADR-0067 §4's +// order: load the row under a row lock, validate and stamp the input (ADR-0045), write. A refusal +// rolls it back. Reads open no write transaction. The mechanics are `@metaobjectsdev/runtime-ts/service`; +// what runs, against which schema and table, is written here. + +import type { MetaObject } from "@metaobjectsdev/metadata"; +import { GENERATED_EDIT_NOTE, GENERATED_HEADER } from "../constants.js"; +import { withExtIfRelative, type RenderContext } from "../render-context.js"; +import { decimalColumnsLine, knownFieldsLine, paginationLine, restPath, writeDeniedColumnsLine } from "../api-surface.js"; +import { dbTypeBlock } from "../dialect-module.js"; +import { contractObjectPath, contractSpecifier } from "../contract-walk.js"; +import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; +import { effectivePackage } from "../docs-paths.js"; +import { + fastifyTransportPath, + runtimeSpecifierFrom, + serviceFactoryName, + serviceTypeName, + servicePath, + serviceRoutesName, + SERVICE_INDEX_FILE, + type ServiceEntity, + type ServicePackage, +} from "../service-walk.js"; +import { TsWriter, str } from "../writer/ts-writer.js"; + +/** One emitted file of the service or transport layer. */ +export interface ServiceFile { + readonly path: string; + readonly content: string; +} + +/** Where a module of `obj` (its entity module or its contract module) is, from the file at `from`. */ +interface Modules { + readonly entity: string; + readonly contract: string; +} + +function modulesOf(from: string, obj: MetaObject, ctx: RenderContext): Modules { + const layout = ctx.outputLayout ?? DEFAULT_OUTPUT_LAYOUT; + return { + entity: contractSpecifier(from, entityOutputPath(layout, effectivePackage(obj), `${obj.name}.ts`), ctx.extStyle), + contract: contractSpecifier(from, contractObjectPath(layout, obj), ctx.extStyle), + }; +} + +function header(w: TsWriter, what: string): void { + w.header(`// ${GENERATED_HEADER} — ${GENERATED_EDIT_NOTE}`, `// Source metadata: ${what}`); +} + +/** + * An object literal of `key: value,` entries (an api-surface fragment may hold several): `head{}tail` + * when there are none, else a block. The fragments' own indent is dropped and the writer's used. + */ +function objectLiteral(w: TsWriter, head: string, entries: readonly string[], tail: string): void { + // An entry is one `key: value,` line, or an api-surface fragment of several, each led by a break. + const lines = entries.flatMap((e) => e.split("\n")).map((l) => l.trim()).filter((l) => l !== ""); + if (lines.length === 0) { + w.line(`${head}{}${tail}`); + return; + } + w.block(`${head}{`, () => { + for (const l of lines) w.line(l); + }, `}${tail}`); +} + +const lowerFirst = (s: string): string => `${s.charAt(0).toLowerCase()}${s.slice(1)}`; + +/** The wire mapper of an entity's rows, as the service index exports it. */ +export function wireMapperName(entityName: string): string { + return `${lowerFirst(entityName)}ToWire`; +} + +/** Every file of package `pkg`'s service module. */ +export function renderServiceFiles(pkg: ServicePackage, ctx: RenderContext): ServiceFile[] { + const files: ServiceFile[] = []; + for (const e of pkg.entities) { + for (const op of ["list", "get", "create", "update", "delete"] as const) { + const path = servicePath(pkg.package, `${e.operations[op]}.ts`); + files.push({ path, content: renderOperation(op, e, path, ctx) }); + } + } + const index = servicePath(pkg.package, SERVICE_INDEX_FILE); + files.push({ path: index, content: renderServiceIndex(pkg, index, ctx) }); + return files; +} + +function renderOperation( + op: "list" | "get" | "create" | "update" | "delete", + e: ServiceEntity, + path: string, + ctx: RenderContext, +): string { + const obj = e.obj; + const name = obj.name; + const fn = e.operations[op]; + const w = new TsWriter(); + header(w, `${name} (${obj.fqn()}) — service operation ${fn} (ADR-0067 layer 4)`); + const runtime = runtimeSpecifierFrom(path, "service", ctx); + const mods = modulesOf(path, obj, ctx); + const table = w.use(ctx.collectionName(name), mods.entity); + const row = w.useType(name, mods.contract); + const deps = w.useType("ServiceDeps", withExtIfRelative(`./${SERVICE_INDEX_FILE.replace(/\.ts$/, "")}`, ctx.extStyle)); + const opOptions = w.useType("OpOptions", runtime); + const opResult = w.useType("OpResult", runtime); + const dialect = str(ctx.dialect); + const keyField = str(e.keyField); + const id = "id: number | string"; + + if (op === "list") { + const listRows = w.use("listRows", runtime); + const listPage = w.useType("ListPage", runtime); + const query = w.useType("ListQueryInput", runtime); + const inReadScope = w.use("inReadScope", runtime); + const filter = w.use(`${name}FilterAllowlist`, mods.entity); + const sort = w.use(`${name}SortAllowlist`, mods.entity); + w.doc( + `A page of ${name} rows: the filter, search, sort and page of \`query\` (the bracketed tree a`, + "query string parses to), checked against the allowlists; ordered by the key when it names no sort.", + ); + w.block( + `export async function ${fn}(deps: ${deps}, query: ${query} = {}, opts: ${opOptions} = {}): Promise<${opResult}<${listPage}<${row}>>> {`, + () => { + w.block(`return ${inReadScope}(deps.db, opts.tx, async (db) => {`, () => { + objectLiteral( + w, + `const spec: ${w.useType("ListSpec", runtime)} = `, + [`filterAllowlist: ${filter},`, `sortAllowlist: ${sort},`, `dialect: ${dialect},`, `keyField: ${keyField},`, paginationLine(obj, "", ctx.loadedRoot)], + ";", + ); + w.line(`return (await ${listRows}(db, ${table}, query, spec)) as ${listPage}<${row}>;`); + }, "});"); + }, + ); + return w.toString(); + } + + if (op === "get") { + const inReadScope = w.use("inReadScope", runtime); + const readOne = w.use("readOne", runtime); + const keyCondition = w.use("keyCondition", runtime); + const notFound = w.use("notFound", runtime); + w.doc(`The ${name} row \`id\` names: \`not_found\` when there is none, \`invalid_id\` when \`id\` is no key.`); + w.block(`export async function ${fn}(deps: ${deps}, ${id}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { + w.block(`return ${inReadScope}(deps.db, opts.tx, async (db) => {`, () => { + w.line(`const row = await ${readOne}(db, ${table}, ${keyCondition}(${table}, ${keyField}, id));`); + w.line(`if (row === undefined) ${notFound}();`); + w.line(`return row as ${row};`); + }, "});"); + }); + return w.toString(); + } + + const inWriteTransaction = w.use("inWriteTransaction", runtime); + if (op === "create" || op === "update") { + const writeRules = w.useType("WriteBodyRules", runtime); + const validateBody = w.use("validateBody", runtime); + w.doc("What a write body may name: every other key is refused, a server-owned one dropped."); + objectLiteral(w, `const writeRules: ${writeRules} = `, [knownFieldsLine(obj, "", ctx.loadedRoot), writeDeniedColumnsLine(obj, "")], ";"); + w.blank(); + if (op === "create") { + const insertRow = w.use("insertRow", runtime); + const schema = w.use(`${name}InsertSchema`, mods.contract); + const input = w.useType(`${name}Create`, mods.contract); + w.doc( + `Create a ${name}. In one transaction: validate the input and stamp what the model declares`, + "(ADR-0045), then insert it and answer the written row.", + ); + w.block(`export async function ${fn}(deps: ${deps}, input: ${input}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { + w.block(`return ${inWriteTransaction}(deps.db, opts.tx, async (tx) => {`, () => { + w.line(`const values = ${validateBody}(${schema}, input, writeRules);`); + w.line(`return (await ${insertRow}(tx, ${table}, values, ${dialect}, ${keyField})) as ${row};`); + }, "});"); + }); + return w.toString(); + } + const keyCondition = w.use("keyCondition", runtime); + const loadForWrite = w.use("loadForWrite", runtime); + const updateRow = w.use("updateRow", runtime); + const notFound = w.use("notFound", runtime); + const schema = w.use(`${name}UpdateSchema`, mods.contract); + const patch = w.useType(`${name}Patch`, mods.contract); + w.doc( + `Update the ${name} row \`id\` names with \`patch\`. In one transaction: load the row under a row`, + "lock (`not_found` when there is none), validate the patch and stamp what the model declares", + "(ADR-0045), then write it and answer the written row. A patch with nothing to write answers the row.", + ); + w.block( + `export async function ${fn}(deps: ${deps}, ${id}, patch: ${patch}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, + () => { + w.block(`return ${inWriteTransaction}(deps.db, opts.tx, async (tx) => {`, () => { + w.line(`const cond = ${keyCondition}(${table}, ${keyField}, id);`); + w.line(`const current = await ${loadForWrite}(tx, ${table}, cond, ${dialect});`); + w.line(`if (current === undefined) ${notFound}();`); + w.line(`const data: Record = ${validateBody}(${schema}, patch, writeRules);`); + w.line(`if (Object.keys(data).length === 0) return current as ${row};`); + w.line(`const row = await ${updateRow}(tx, ${table}, data, cond, ${dialect});`); + w.line(`if (row === undefined) ${notFound}();`); + w.line(`return row as ${row};`); + }, "});"); + }, + ); + return w.toString(); + } + + const keyCondition = w.use("keyCondition", runtime); + const loadForWrite = w.use("loadForWrite", runtime); + const deleteRows = w.use("deleteRows", runtime); + const notFound = w.use("notFound", runtime); + w.doc( + `Delete the ${name} row \`id\` names. In one transaction: load it under a row lock (\`not_found\``, + "when there is none), then delete it.", + ); + w.block(`export async function ${fn}(deps: ${deps}, ${id}, opts: ${opOptions} = {}): Promise<${opResult}> {`, () => { + w.block(`return ${inWriteTransaction}(deps.db, opts.tx, async (tx) => {`, () => { + w.line(`const cond = ${keyCondition}(${table}, ${keyField}, id);`); + w.line(`if ((await ${loadForWrite}(tx, ${table}, cond, ${dialect})) === undefined) ${notFound}();`); + w.line(`await ${deleteRows}(tx, ${table}, cond);`); + }, "});"); + }); + return w.toString(); +} + +function renderServiceIndex(pkg: ServicePackage, path: string, ctx: RenderContext): string { + const w = new TsWriter(); + const label = pkg.package === "" ? "the model's root package" : `package ${pkg.package}`; + header(w, `${label} — service module (ADR-0067 layer 4)`); + const runtime = runtimeSpecifierFrom(path, "service", ctx); + const opOptions = w.useType("OpOptions", runtime); + const opResult = w.useType("OpResult", runtime); + const listPage = w.useType("ListPage", runtime); + const query = w.useType("ListQueryInput", runtime); + const timestampWire = w.use("timestampWire", runtime); + const withWire = w.use("withWire", runtime); + const type = serviceTypeName(pkg.package); + const { import: dbImport, alias: dbAlias } = dbTypeBlock(ctx.dialect); + + // The dialect's Drizzle base type, the same one the queries generator types `db` with. + const dbModule = /from "([^"]+)"/.exec(dbImport)![1]!; + for (const t of /import type \{ ([^}]+) \}/.exec(dbImport)![1]!.split(",").map((s) => s.trim())) w.useType(t, dbModule); + w.line(dbAlias); + w.blank(); + w.doc("What the service needs from the composition root."); + w.block("export interface ServiceDeps {", () => { + w.doc("The database every operation runs on. A caller may pass a transaction of its own per call (`opts.tx`)."); + w.line("readonly db: Db;"); + }); + + const calls: string[] = []; + w.blank(); + w.doc( + `The operations of ${label}. A transport, a job or an agent tool calls these; each answers an`, + "`OpResult`, and a failure carries the status the REST contract gives its code.", + ); + w.block(`export interface ${type} {`, () => { + for (const e of pkg.entities) { + const mods = modulesOf(path, e.obj, ctx); + const row = w.useType(e.obj.name, mods.contract); + const create = w.useType(`${e.obj.name}Create`, mods.contract); + const patch = w.useType(`${e.obj.name}Patch`, mods.contract); + const o = e.operations; + for (const f of Object.values(o)) w.use(f, withExtIfRelative(`./${f}`, ctx.extStyle)); + w.line(`${o.list}(query?: ${query}, opts?: ${opOptions}): Promise<${opResult}<${listPage}<${row}>>>;`); + w.line(`${o.get}(id: number | string, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); + w.line(`${o.create}(input: ${create}, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); + w.line(`${o.update}(id: number | string, patch: ${patch}, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); + w.line(`${o.delete}(id: number | string, opts?: ${opOptions}): Promise<${opResult}>;`); + calls.push( + `${o.list}: (query, opts) => ${o.list}(deps, query, opts),`, + `${o.get}: (id, opts) => ${o.get}(deps, id, opts),`, + `${o.create}: (input, opts) => ${o.create}(deps, input, opts),`, + `${o.update}: (id, patch, opts) => ${o.update}(deps, id, patch, opts),`, + `${o.delete}: (id, opts) => ${o.delete}(deps, id, opts),`, + ); + } + }); + + w.blank(); + w.doc(`Bind the operations of ${label} to \`deps\`.`); + w.block(`export function ${serviceFactoryName(pkg.package)}(deps: ServiceDeps): ${type} {`, () => { + w.block("return {", () => { + for (const c of calls) w.line(c); + }, "};"); + }); + + for (const e of pkg.entities) { + const mods = modulesOf(path, e.obj, ctx); + const table = w.use(ctx.collectionName(e.obj.name), mods.entity); + w.blank(); + w.doc(`The wire form (ADR-0019) of a ${e.obj.name} row: what a transport sends.`); + objectLiteral(w, `export const ${wireMapperName(e.obj.name)} = ${withWire}(${timestampWire}(${table}), `, [decimalColumnsLine(e.obj, "", ctx.loadedRoot)], ");"); + } + return w.toString(); +} + +/** The thin Fastify transport of package `pkg`: parse, call the service, send what it answered. */ +export function renderFastifyTransport(pkg: ServicePackage, ctx: RenderContext): ServiceFile { + const path = fastifyTransportPath(pkg.package); + const w = new TsWriter(); + const label = pkg.package === "" ? "the model's root package" : `package ${pkg.package}`; + header(w, `${label} — Fastify transport (ADR-0067 layer 5)`); + const runtime = runtimeSpecifierFrom(path, "service-fastify", ctx); + const serviceIndex = contractSpecifier(path, servicePath(pkg.package, SERVICE_INDEX_FILE), ctx.extStyle); + const fastifyInstance = w.useType("FastifyInstance", "fastify"); + const send = w.use("sendOpResult", runtime); + const handler = w.use("withContractErrorHandler", runtime); + const parseQuery = w.use("parseListQueryString", runtime); + const rawQuery = w.use("rawQueryOf", runtime); + const type = w.useType(serviceTypeName(pkg.package), serviceIndex); + const routes = serviceRoutesName(pkg.package); + + w.doc("What the routes need: the service they call."); + w.block(`export interface ${type}RoutesOptions {`, () => { + w.line(`readonly service: ${type};`); + }); + w.blank(); + w.doc( + `Mount the REST routes of ${label}. Each route parses the request, calls one operation of the`, + "service and sends what it answered; it holds no rules. Register it with the service:", + `\`app.register(${routes}, { service })\`.`, + ); + w.block(`export async function ${routes}(fastify: ${fastifyInstance}, opts: ${type}RoutesOptions): Promise {`, () => { + w.line("const { service } = opts;"); + w.line(`const ro = ${handler}(undefined);`); + const mount = (app: string) => { + for (const e of pkg.entities) { + const mods = modulesOf(path, e.obj, ctx); + const create = w.useType(`${e.obj.name}Create`, mods.contract); + const patch = w.useType(`${e.obj.name}Patch`, mods.contract); + const toWire = w.use(wireMapperName(e.obj.name), serviceIndex); + const o = e.operations; + const base = str(restPath(e.obj)); + const item = str(`${restPath(e.obj)}/:id`); + const params = "{ Params: { id: string } }"; + w.block(`${app}.get(${base}, ro, async (req, reply) => {`, () => { + w.line(`const result = await service.${o.list}(${parseQuery}(${rawQuery}(req.raw.url)));`); + w.line( + `return ${send}(reply, result, 200, (page) => (page.total === undefined ? page.rows.map(${toWire}) : { rows: page.rows.map(${toWire}), total: page.total }));`, + ); + }, "});"); + w.line(`${app}.get<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.get}(req.params.id), 200, ${toWire}));`); + w.line(`${app}.post(${base}, ro, async (req, reply) => ${send}(reply, await service.${o.create}(req.body as ${create}), 201, ${toWire}));`); + w.line("// The update is reachable by PATCH and by PUT, as in every port."); + for (const verb of ["patch", "put"]) { + w.line( + `${app}.${verb}<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.update}(req.params.id, req.body as ${patch}), 200, ${toWire}));`, + ); + } + w.line(`${app}.delete<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.delete}(req.params.id), 204));`); + } + }; + if (ctx.apiPrefix) { + w.block("await fastify.register(async (app) => {", () => mount("app"), `}, { prefix: ${str(ctx.apiPrefix)} });`); + } else { + mount("fastify"); + } + }); + return { path, content: w.toString() }; +} diff --git a/server/typescript/packages/codegen-ts/test/generator-registry.test.ts b/server/typescript/packages/codegen-ts/test/generator-registry.test.ts index 0fd585d713..8b12679885 100644 --- a/server/typescript/packages/codegen-ts/test/generator-registry.test.ts +++ b/server/typescript/packages/codegen-ts/test/generator-registry.test.ts @@ -24,6 +24,8 @@ const EXPECTED_NATIVE = [ "names", "rules-names", "contract-types", + "service", + "service-routes", "report-export", "prompt-render", "output-parser", @@ -181,13 +183,14 @@ describe("generator-registry (ADR-0021 D3)", () => { } }); - test("no entry declares a framework — every codegen-ts generator but routes is neutral", () => { - // The two `api`-layer route generators are the only framework-bearing entries in - // this package; `client` (react/tanstack) lives in the other two slices. + test("no entry declares a framework — every codegen-ts generator but the route tier is neutral", () => { + // The three `api`-layer route generators (the flat Fastify and Hono routes, and the service + // layer's Fastify transport) are the only framework-bearing entries in this package; + // `client` (react/tanstack) lives in the other two slices. const framed = Object.values(generatorRegistry) .filter((e) => e.framework !== undefined) .map((e) => `${e.name}=${e.framework}`) .sort(); - expect(framed).toEqual(["routes-hono=hono", "routes=fastify"]); + expect(framed).toEqual(["routes-hono=hono", "routes=fastify", "service-routes=fastify"]); }); }); diff --git a/server/typescript/packages/codegen-ts/test/golden/generator-registry-conformance.test.ts b/server/typescript/packages/codegen-ts/test/golden/generator-registry-conformance.test.ts index 3332a0db80..1ab23fe975 100644 --- a/server/typescript/packages/codegen-ts/test/golden/generator-registry-conformance.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/generator-registry-conformance.test.ts @@ -8,7 +8,7 @@ // 2. Tier agreement — a manifest name marked `tier: "neutral"` is flagged // neutral in the TS registry; native manifest names are NOT neutral. // 3. Layer agreement — a manifest name's `layer` equals the TS registry's. -// 4. Every manifest entry declares one of the six layers. +// 4. Every manifest entry declares one of the seven layers. // // PRESENCE BOTH WAYS IS ASSERTED ELSEWHERE. `codegen-ts` is one SLICE of the // TypeScript catalog: `form` lives in `codegen-ts-react` and `hooks`/`grid`/ @@ -60,9 +60,9 @@ interface ManifestEntry { // The closed set, mirrored from GENERATOR_LAYERS. Spelled out here rather than // imported so this gate fails if the CODE's union and the MANIFEST's values ever -// diverge from the six the design ruled — importing the union would make the test +// diverge from the seven the design ruled (`service` added by ADR-0067 §5.6) — importing the union would make the test // agree with whatever the code says. -const LAYERS = ["model", "persistence", "api", "client", "docs", "capability"] as const; +const LAYERS = ["model", "persistence", "service", "api", "client", "docs", "capability"] as const; interface Manifest { ports: string[]; @@ -110,7 +110,7 @@ describe("generator registry — conforms to canonical stable-name manifest (ADR expect(extraInRegistry, message).toEqual([]); }); - it("every manifest entry declares one of the six layers", () => { + it("every manifest entry declares one of the seven layers", () => { const bad = Object.entries(manifest.generators) .filter(([, e]) => !(LAYERS as readonly string[]).includes(e.layer)) .map(([n, e]) => `${n}=${String(e.layer)}`) diff --git a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts index 7b64b2ca27..cca1238170 100644 --- a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts @@ -26,6 +26,10 @@ import { rulesNamesFile as builtinRulesNames } from "../src/generators/rules-nam import { rulesNamesFile as refRulesNames } from "../src/reference/rules-names.js"; import { contractTypes as builtinContractTypes } from "../src/generators/contract-types-file.js"; import { contractTypes as refContractTypes } from "../src/reference/contract-types.js"; +import { serviceFile as builtinService } from "../src/generators/service-file.js"; +import { serviceFile as refService } from "../src/reference/service.js"; +import { serviceRoutesFile as builtinServiceRoutes } from "../src/generators/service-routes-file.js"; +import { serviceRoutesFile as refServiceRoutes } from "../src/reference/service-routes.js"; import { reportExport as builtinReportExport } from "../src/generators/report-export-file.js"; import { reportExport as refReportExport } from "../src/reference/report-export.js"; import { promptRender as builtinPromptRender } from "../src/generators/prompt-render-file.js"; @@ -186,6 +190,10 @@ const PAIRS: Record Generator; ref: () // test/rules-names.test.ts runs both over a rules model. "rules-names": { builtin: builtinRulesNames, ref: refRulesNames }, "contract-types": { builtin: builtinContractTypes, ref: refContractTypes }, + // Bound to the package as the routes pair is: the built-ins import it, the references default to + // the copy `meta eject` places in `codegen/runtime/`. + service: { builtin: builtinService, ref: () => refService(PKG) }, + "service-routes": { builtin: builtinServiceRoutes, ref: () => refServiceRoutes(PKG) }, // Emits nothing over the entity-shaped fixtures (none declares a served report); the // describe after the route-composition one runs the pair, with the routes, over the report corpus. "report-export": { builtin: builtinReportExport, ref: refReportExport }, diff --git a/server/typescript/packages/codegen-ts/test/reference-templates.test.ts b/server/typescript/packages/codegen-ts/test/reference-templates.test.ts index 23d3f84b5d..38cb42475a 100644 --- a/server/typescript/packages/codegen-ts/test/reference-templates.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-templates.test.ts @@ -13,7 +13,7 @@ import { join } from "node:path"; describe("reference-templates reader", () => { test("exposes the copyable generator names, entity first (reader sentinel)", () => { expect([...REFERENCE_GENERATOR_NAMES]).toEqual([ - "entity", "queries", "routes", "routes-hono", "barrel", "names", "rules-names", "contract-types", "report-export", + "entity", "queries", "routes", "routes-hono", "barrel", "names", "rules-names", "contract-types", "service", "service-routes", "report-export", "prompt-render", "output-parser", "extractor", "output-prompt", "render-helper", "requirement-tests", "cube-model", "prisma-schema", "contract-schema", "openapi", "callable", "trace-helper", "shared-model", "docs", "api-docs", "requirements", "agent-docs", "metamodel-docs", diff --git a/server/typescript/packages/codegen-ts/test/service-file.test.ts b/server/typescript/packages/codegen-ts/test/service-file.test.ts new file mode 100644 index 0000000000..589b3c249d --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/service-file.test.ts @@ -0,0 +1,146 @@ +// The service layer's generators (ADR-0067 layers 4 and 5): which entities get operations, where +// the files go in each layout, what the package's service is named, and the refusals. Behaviour is +// gated by the api-contract service lane and compilation by the service compile gate, both in +// `integration-tests`; this file holds the walk and the paths. +import { describe, expect, test } from "bun:test"; +import { join, resolve, dirname } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { InMemoryStringSource, loadUris, MetaDataLoader, type MetaRoot } from "@metaobjectsdev/metadata"; +import { contractTypes, entityFile, serviceFile, serviceRoutesFile } from "../src/generators/index.js"; +import { defineConfig, runGen, type OutputLayout } from "../src/index.js"; +import { serviceModelOf, serviceRoutesName, serviceTypeName } from "../src/service-walk.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; +import type { Generator } from "../src/generator.js"; + +const FITNESS = resolve( + dirname(fileURLToPath(import.meta.url)), + "..", "..", "..", "..", "..", "fixtures", "persistence-conformance", "canonical", "meta.fitness.json", +); + +const entity = (name: string, extra: unknown[] = [], table = `${name.toLowerCase()}s`) => ({ + "object.entity": { + name, + children: [ + { "source.rdb": { "@table": table } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "title", "@maxLength": 80 } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ...extra, + ], + }, +}); + +async function load(pkg: string, children: unknown[]): Promise { + const result = await new MetaDataLoader({ strict: true }).load([ + new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: pkg, children } }), { id: "service.json" }), + ]); + expect(result.errors.map((e) => e.message)).toEqual([]); + return result.root; +} + +async function gen( + root: MetaRoot, + generators: Generator[], + layout: OutputLayout = "package", + extra: Record = {}, +): Promise> { + const dir = makeScratchDir("service-file-"); + try { + const r = await runGen({ + config: defineConfig({ outDir: "gen", extStyle: "js", dialect: "postgres", outputLayout: layout, generators, ...extra }), + metadata: root, + projectRoot: dir, + dryRun: true, + }); + const out = join(dir, "gen"); + return Object.fromEntries([...(r.rendered ?? new Map())].map(([path, content]) => [path.slice(out.length + 1), content])); + } finally { + removeTree(dir); + } +} + +const tier = (): Generator[] => [entityFile(), contractTypes(), serviceFile(), serviceRoutesFile()]; +const servicePaths = (files: Record) => + Object.keys(files).filter((p) => p.includes("/service/") || p.includes("/transport/") || p.startsWith("service/") || p.startsWith("transport/")).sort(); + +describe("service generators — what they write", () => { + test("one file per operation, the index and the transport, under the package's directory", async () => { + const root = await load("acme::shop", [entity("Order"), entity("Customer")]); + expect(servicePaths(await gen(root, tier()))).toEqual([ + "acme/shop/service/createCustomer.ts", + "acme/shop/service/createOrder.ts", + "acme/shop/service/deleteCustomer.ts", + "acme/shop/service/deleteOrder.ts", + "acme/shop/service/getCustomer.ts", + "acme/shop/service/getOrder.ts", + "acme/shop/service/index.ts", + "acme/shop/service/listCustomers.ts", + "acme/shop/service/listOrders.ts", + "acme/shop/service/updateCustomer.ts", + "acme/shop/service/updateOrder.ts", + "acme/shop/transport/fastify.ts", + ]); + }); + + test("the flat layout keeps the package directory: two packages cannot both write service/index.ts", async () => { + const root = await load("acme::shop", [entity("Order")]); + const files = await gen(root, tier(), "flat"); + expect(files["acme/shop/service/index.ts"]).toContain("export function createShopService(deps: ServiceDeps): ShopService {"); + // The entity module stays where the flat layout puts it, and the service reaches it. + expect(files["acme/shop/service/createOrder.ts"]).toContain('from "../../../Order.js";'); + }); + + test("the service is named for the package's last segment; the root package's is ModelService", () => { + expect(serviceTypeName("acme::purchasing")).toBe("PurchasingService"); + expect(serviceTypeName("acme::purchase_orders")).toBe("PurchaseOrdersService"); + expect(serviceTypeName("")).toBe("ModelService"); + expect(serviceRoutesName("acme::purchasing")).toBe("purchasingServiceRoutes"); + }); + + test("a model with no store-backed entity gets no file, and a project that lists none sees no change", async () => { + const root = await load("acme::shop", [{ "object.value": { name: "Money", children: [{ "field.long": { name: "cents" } }] } }]); + expect(servicePaths(await gen(root, tier()))).toEqual([]); + const withOrder = await load("acme::shop", [entity("Order")]); + expect(servicePaths(await gen(withOrder, [entityFile(), contractTypes()]))).toEqual([]); + }); + + test("filter narrows the entities that get operations", async () => { + const root = await load("acme::shop", [entity("Order"), entity("Customer")]); + const onlyOrder = (e: { name: string }) => e.name === "Order"; + const files = await gen(root, [entityFile(), contractTypes(), serviceFile({ filter: onlyOrder }), serviceRoutesFile({ filter: onlyOrder })]); + expect(servicePaths(files).filter((p) => p.includes("Customer"))).toEqual([]); + expect(files["acme/shop/service/index.ts"]).not.toContain("Customer"); + }); + + test("a relative runtimeImport (an owned copy) is resolved from the file, one folder below the package", async () => { + const root = await load("acme::shop", [entity("Order")]); + const files = await gen(root, [entityFile(), contractTypes(), serviceFile({ runtimeImport: "../codegen/runtime" }), serviceRoutesFile({ runtimeImport: "../codegen/runtime" })]); + expect(files["acme/shop/service/createOrder.ts"]).toContain('from "../../../../codegen/runtime/service/index.js";'); + expect(files["acme/shop/transport/fastify.ts"]).toContain('from "../../../../codegen/runtime/service/fastify.js";'); + }); + + test("written to another target than the entity module's, it is refused by name", async () => { + const root = await load("acme::shop", [entity("Order")]); + await expect( + gen(root, [entityFile(), contractTypes(), serviceFile({ target: "api" })], "package", { + targets: { api: { outDir: "api" } }, + importBase: "@acme/model", + }), + ).rejects.toThrow(/service: write it to the entity module's target/); + }); +}); + +describe("service walk — which entities get the derived operations", () => { + test("over the fitness corpus: concrete, store-backed, single-key entities only", async () => { + const result = await loadUris([pathToFileURL(FITNESS).href]); + expect(result.errors).toEqual([]); + const covered = serviceModelOf(result.root).flatMap((p) => p.entities.map((e) => e.obj.name)); + expect(covered).toContain("Program"); + // A concrete entity that inherits its fields from an abstract one. + expect(covered).toContain("Gadget"); + // The abstract level has no table of its own. + expect(covered).not.toContain("Labeled"); + // A single-table hierarchy, its base and its subtypes, is later service work. + for (const tph of ["Auth", "BridgeAuth", "CouponAuth", "PermitAuth", "ReferralAuth"]) expect(covered).not.toContain(tph); + }); +}); diff --git a/server/typescript/packages/integration-tests/src/api-contract-generated-lane.ts b/server/typescript/packages/integration-tests/src/api-contract-generated-lane.ts new file mode 100644 index 0000000000..9aa7d29aaa --- /dev/null +++ b/server/typescript/packages/integration-tests/src/api-contract-generated-lane.ts @@ -0,0 +1,72 @@ +// The generated api-contract lane, shared by its two entry files: `api-contract-generated.test.ts` +// (the flat per-entity routes) and `api-contract-service.test.ts` (the service layer behind its +// thin Fastify transport, ADR-0067 layers 4 and 5). Same corpus, same expects, so the two +// servers cannot answer the contract differently. +// +// Flat layout: one Postgres testcontainer per scenario. Package layout: one container +// for the file and a fresh database per scenario. Reuses the server-agnostic runner +// (loadScenarios/assertResponse). + +import { describe, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { API_CONTRACT_DIR, API_CONTRACT_SCENARIOS_DIR } from "./paths.ts"; +import { openApiCheck, type ContractCheck } from "./api-contract-openapi-check.ts"; +import { loadScenarios, assertResponse, type ApiScenario, parseBodyExact } from "./api-contract-scenario.ts"; +import { + startGeneratedServer, + type GeneratedLane, + type GeneratedServerHandle, +} from "./api-contract-generated-server.ts"; +import { type AuthorRow } from "./api-contract-server.ts"; +import { OUTPUT_LAYOUTS, postgresFor } from "./output-layout.ts"; + +const SEED = JSON.parse(readFileSync(join(API_CONTRACT_DIR, "seed.json"), "utf8")) as { rows: AuthorRow[] }; +const META_PATH = join(API_CONTRACT_DIR, "meta.json"); + +const contractCheck: ContractCheck = openApiCheck("blog"); + +/** + * Run the corpus against one generated server: the flat routes, or (`api-contract-service.test.ts`) + * the service layer behind its thin transport. + */ +export function describeGeneratedLane(lane: GeneratedLane, label: string): void { + for (const layout of OUTPUT_LAYOUTS) describe(`api contract conformance — TS GENERATED ${label} runner [${layout}]`, () => { + const startPostgres = postgresFor(layout); + for (const scenario of loadScenarios(API_CONTRACT_SCENARIOS_DIR)) { + test(scenario.name, async () => { + const pg = await startPostgres(); + let server: GeneratedServerHandle | null = null; + try { + server = await startGeneratedServer(pg.connectionUri, META_PATH, layout, lane); + if (scenario.setup?.truncate) await server.truncate(); + else await server.applySeed(SEED.rows); + + await executeRequests(scenario, server); + } finally { + if (server) await server.close(); + await pg.stop(); + } + }, { timeout: 60_000 }); + } + }); +} + + +async function executeRequests(scenario: ApiScenario, server: GeneratedServerHandle): Promise { + for (const req of scenario.requests) { + const init: RequestInit = { method: req.method }; + if (req.body !== undefined) { + init.body = JSON.stringify(req.body); + init.headers = { "content-type": "application/json" }; + } + const res = await fetch(server.baseUrl + req.path, init); + const bodyText = await res.text(); + let body: unknown = null; + if (bodyText.length > 0) { + try { body = parseBodyExact(bodyText); } catch { body = bodyText; } + } + assertResponse(scenario.name, req, res.status, body); + contractCheck(req, res.status, bodyText); + } +} diff --git a/server/typescript/packages/integration-tests/src/api-contract-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-generated-server.ts index 55592f741f..c7fc40051d 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-generated-server.ts @@ -31,6 +31,7 @@ import { fileURLToPath, pathToFileURL } from "node:url"; import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; import { indexEmitted, type OutputLayout } from "./output-layout.ts"; import { entityFile, routesFile } from "@metaobjectsdev/test-generators"; +import { contractTypes, serviceFile, serviceRoutesFile } from "@metaobjectsdev/codegen-ts/generators"; import pg from "pg"; import { executeSql } from "./postgres-sql.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; @@ -58,10 +59,18 @@ export interface GeneratedServerHandle { * loader and drives `runGen` so the full loader → generator pipeline produces * the artifact under test. */ +/** + * Which generated server the lane boots: the flat per-entity routes (`routes`), or the service + * layer behind its thin Fastify transport (`service`, ADR-0067 layers 4 and 5), which must answer + * the same corpus the same way. + */ +export type GeneratedLane = "routes" | "service"; + export async function startGeneratedServer( connectionUri: string, metaPath: string, outputLayout: OutputLayout = "flat", + lane: GeneratedLane = "routes", ): Promise { // Emit INSIDE the package tree (under .gen-tmp/, gitignored) rather than the // OS tmpdir. The emitted route imports the bare specifier @@ -90,7 +99,9 @@ export async function startGeneratedServer( dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [entityFile(), routesFile()], + generators: lane === "service" + ? [entityFile(), contractTypes(), serviceFile(), serviceRoutesFile()] + : [entityFile(), routesFile()], }), metadata: root, }); @@ -137,12 +148,23 @@ export const db = drizzle(pool); ); // 4. Import the EMITTED route file unmodified and mount it. - const routeUrl = pathToFileURL(emitted.locate("Author.routes.ts")).href; - const mod = (await import(routeUrl)) as { authorRoutes: (f: FastifyInstance) => Promise }; - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; - + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; const fastify = Fastify(); - await fastify.register(mod.authorRoutes); + if (lane === "service") { + // The service is built at the composition root with its dependencies, and the transport is + // registered with the service: the routes hold no database handle of their own. + const service = (await import(pathToFileURL(join(tmp, "acme/blog/service/index.ts")).href)) as { + createBlogService: (deps: { db: unknown }) => unknown; + }; + const transport = (await import(pathToFileURL(join(tmp, "acme/blog/transport/fastify.ts")).href)) as { + blogServiceRoutes: (f: FastifyInstance, opts: { service: unknown }) => Promise; + }; + await fastify.register(transport.blogServiceRoutes, { service: service.createBlogService({ db: dbMod.db }) }); + } else { + const routeUrl = pathToFileURL(emitted.locate("Author.routes.ts")).href; + const mod = (await import(routeUrl)) as { authorRoutes: (f: FastifyInstance) => Promise }; + await fastify.register(mod.authorRoutes); + } await fastify.ready(); const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); diff --git a/server/typescript/packages/integration-tests/test/api-contract-generated.test.ts b/server/typescript/packages/integration-tests/test/api-contract-generated.test.ts index 613e65c369..4ef1fc05f0 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-generated.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-generated.test.ts @@ -7,62 +7,8 @@ // deployed artifact implements the cross-port contract, not just the // golden-snapshot structure. // -// Flat layout: one Postgres testcontainer per scenario. Package layout: one container -// for the file and a fresh database per scenario. Reuses the server-agnostic runner -// (loadScenarios/assertResponse). +// The lane itself is `src/api-contract-generated-lane.ts`, shared with the service lane. -import { describe, test } from "bun:test"; -import { readFileSync } from "node:fs"; -import { join } from "node:path"; -import { API_CONTRACT_DIR, API_CONTRACT_SCENARIOS_DIR } from "../src/paths.ts"; -import { openApiCheck, type ContractCheck } from "../src/api-contract-openapi-check.ts"; -import { loadScenarios, assertResponse, type ApiScenario, parseBodyExact } from "../src/api-contract-scenario.ts"; -import { - startGeneratedServer, - type GeneratedServerHandle, -} from "../src/api-contract-generated-server.ts"; -import { type AuthorRow } from "../src/api-contract-server.ts"; -import { OUTPUT_LAYOUTS, postgresFor } from "../src/output-layout.ts"; +import { describeGeneratedLane } from "../src/api-contract-generated-lane.ts"; -const SEED = JSON.parse(readFileSync(join(API_CONTRACT_DIR, "seed.json"), "utf8")) as { rows: AuthorRow[] }; -const META_PATH = join(API_CONTRACT_DIR, "meta.json"); - -const contractCheck: ContractCheck = openApiCheck("blog"); - -for (const layout of OUTPUT_LAYOUTS) describe(`api contract conformance — TS GENERATED routes runner [${layout}]`, () => { - const startPostgres = postgresFor(layout); - for (const scenario of loadScenarios(API_CONTRACT_SCENARIOS_DIR)) { - test(scenario.name, async () => { - const pg = await startPostgres(); - let server: GeneratedServerHandle | null = null; - try { - server = await startGeneratedServer(pg.connectionUri, META_PATH, layout); - if (scenario.setup?.truncate) await server.truncate(); - else await server.applySeed(SEED.rows); - - await executeRequests(scenario, server); - } finally { - if (server) await server.close(); - await pg.stop(); - } - }, { timeout: 60_000 }); - } -}); - -async function executeRequests(scenario: ApiScenario, server: GeneratedServerHandle): Promise { - for (const req of scenario.requests) { - const init: RequestInit = { method: req.method }; - if (req.body !== undefined) { - init.body = JSON.stringify(req.body); - init.headers = { "content-type": "application/json" }; - } - const res = await fetch(server.baseUrl + req.path, init); - const bodyText = await res.text(); - let body: unknown = null; - if (bodyText.length > 0) { - try { body = parseBodyExact(bodyText); } catch { body = bodyText; } - } - assertResponse(scenario.name, req, res.status, body); - contractCheck(req, res.status, bodyText); - } -} +describeGeneratedLane("routes", "routes"); diff --git a/server/typescript/packages/integration-tests/test/api-contract-service.test.ts b/server/typescript/packages/integration-tests/test/api-contract-service.test.ts new file mode 100644 index 0000000000..f58e15030d --- /dev/null +++ b/server/typescript/packages/integration-tests/test/api-contract-service.test.ts @@ -0,0 +1,11 @@ +// bun:test entry — the generated SERVICE api-contract lane (ADR-0067 layers 4 and 5). +// +// The same corpus as the generated-routes lane, but the server under test is the emitted service +// module (`/service/*.ts`: one function per operation, each write in one transaction with the +// model's write rules) behind the emitted thin Fastify transport (`/transport/fastify.ts`), +// built with its database at the composition root. Passing it proves moving the rules out of the +// route into a service changed nothing a client can see. + +import { describeGeneratedLane } from "../src/api-contract-generated-lane.ts"; + +describeGeneratedLane("service", "service"); diff --git a/server/typescript/packages/integration-tests/test/service-compile.test.ts b/server/typescript/packages/integration-tests/test/service-compile.test.ts new file mode 100644 index 0000000000..0108b715d8 --- /dev/null +++ b/server/typescript/packages/integration-tests/test/service-compile.test.ts @@ -0,0 +1,114 @@ +// The service tier's compile gate (ADR-0067 layers 4 and 5): the shared fitness corpus, generated +// with the entity module, the contract types, the service and its Fastify transport, compiled with +// the real compiler in both profiles, every dialect and both output layouts. +// +// A separate gate from codegen-ts's `codegen-compile-conformance.test.ts`, which keeps its program +// to drizzle and zod: a service imports the entity module's allowlists and +// `@metaobjectsdev/runtime-ts`, and its transport imports fastify, so its program has to resolve +// all three, which this package does. Behaviour is gated by the api-contract service +// lane (`integration-tests/test/api-contract-service.test.ts`); this asks only whether what it +// runs BUILDS, which bun, running the emitted files unchecked, never asks. +import { describe, test, expect, setDefaultTimeout } from "bun:test"; +import { mkdirSync, mkdtempSync, readdirSync, statSync, writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import ts from "typescript"; +import { loadUris, type MetaRoot } from "@metaobjectsdev/metadata"; +import { contractTypes, entityFile, serviceFile, serviceRoutesFile } from "@metaobjectsdev/codegen-ts/generators"; +import { runGen, defineConfig, type OutputLayout } from "@metaobjectsdev/codegen-ts"; +import { rmSync } from "node:fs"; + +setDefaultTimeout(120_000); + +// Inside the package tree, so the emitted imports resolve through this package's node_modules +// (drizzle-orm, zod, fastify and the workspace's runtime-ts), as the generated api-contract lanes do. +const GEN_TMP = join(dirname(fileURLToPath(import.meta.url)), "..", ".gen-tmp"); +mkdirSync(GEN_TMP, { recursive: true }); + +const CORPUS = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..", "..", "fixtures", "persistence-conformance", "canonical", "meta.fitness.json"); + +async function loadCorpus(): Promise { + const result = await loadUris([pathToFileURL(CORPUS).href]); + if (result.errors.length > 0) throw new Error(`${CORPUS} did not load: ${result.errors.map((e) => e.message).join("; ")}`); + return result.root; +} + +const PROFILES: ReadonlyArray = [ + ["defaults", { strict: true, target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler, skipLibCheck: true }], + [ + "tsc --init", + { + module: ts.ModuleKind.NodeNext, + moduleResolution: ts.ModuleResolutionKind.NodeNext, + target: ts.ScriptTarget.ESNext, + types: [], + noUncheckedIndexedAccess: true, + exactOptionalPropertyTypes: true, + strict: true, + verbatimModuleSyntax: true, + isolatedModules: true, + noUncheckedSideEffectImports: true, + moduleDetection: ts.ModuleDetectionKind.Force, + skipLibCheck: true, + }, + ], +]; + +function emittedTs(dir: string): string[] { + const out: string[] = []; + const walk = (d: string): void => { + for (const n of readdirSync(d)) { + const f = join(d, n); + if (statSync(f).isDirectory()) { + if (n !== ".metaobjects") walk(f); + } else if (/\.tsx?$/.test(n)) out.push(f); + } + }; + walk(dir); + return out.sort(); +} + +describe("service compile gate — the shared fitness corpus", () => { + for (const layout of ["flat", "package"] as const satisfies readonly OutputLayout[]) { + for (const dialect of ["postgres", "sqlite", "mysql"] as const) { + for (const [profile, options] of PROFILES) { + test(`${layout} / ${dialect} [${profile}]: the service and its transport compile with zero diagnostics`, async () => { + const root = await loadCorpus(); + const dir = mkdtempSync(join(GEN_TMP, `service-compile-${layout}-${dialect}-`)); + try { + await runGen({ + config: defineConfig({ + outDir: dir, + extStyle: "js", + dbImport: "~/db", + dialect, + outputLayout: layout, + generators: [entityFile(), contractTypes(), serviceFile(), serviceRoutesFile()], + }), + metadata: root, + projectRoot: dir, + }); + const files = emittedTs(dir); + const rel = files.map((f) => f.slice(dir.length + 1).split("\\").join("/")); + // The tier is present by name, so the gate cannot pass on an empty service. + expect(rel).toContain("fitness/service/index.ts"); + expect(rel).toContain("fitness/service/createProgram.ts"); + expect(rel).toContain("fitness/transport/fastify.ts"); + writeFileSync(join(dir, "package.json"), JSON.stringify({ type: "module" })); + const program = ts.createProgram(files, { ...options, noEmit: true }); + const diagnostics = ts.getPreEmitDiagnostics(program).map((d) => { + const where = + d.file && d.start !== undefined + ? `${d.file.fileName.slice(dir.length + 1)}:${d.file.getLineAndCharacterOfPosition(d.start).line + 1} ` + : ""; + return `${where}${ts.flattenDiagnosticMessageText(d.messageText, "\n")}`; + }); + expect(diagnostics).toEqual([]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + } + } + } +}); diff --git a/server/typescript/packages/runtime-ts/package.json b/server/typescript/packages/runtime-ts/package.json index cda6df9a35..ec39aa536a 100644 --- a/server/typescript/packages/runtime-ts/package.json +++ b/server/typescript/packages/runtime-ts/package.json @@ -26,6 +26,16 @@ "types": "./dist/drizzle-fastify/index.d.ts", "default": "./dist/drizzle-fastify/index.js" }, + "./service": { + "bun": "./src/service/index.ts", + "types": "./dist/service/index.d.ts", + "default": "./dist/service/index.js" + }, + "./service/fastify": { + "bun": "./src/service/fastify.ts", + "types": "./dist/service/fastify.d.ts", + "default": "./dist/service/fastify.js" + }, "./hono": { "bun": "./src/hono/index.ts", "types": "./dist/hono/index.d.ts", diff --git a/server/typescript/packages/runtime-ts/src/service/fastify.ts b/server/typescript/packages/runtime-ts/src/service/fastify.ts new file mode 100644 index 0000000000..efad5f595a --- /dev/null +++ b/server/typescript/packages/runtime-ts/src/service/fastify.ts @@ -0,0 +1,26 @@ +// What a generated thin Fastify transport over the service layer imports (ADR-0067 layer 5, +// `meta gen` generator `service-routes`): parse the request, call one service operation, send what +// it answered. Its own entry, beside the store mechanics in `./index.ts`, so the flat routes' +// adapter (`../drizzle-fastify`) and what `meta eject routes` copies of it stay as they were. + +import type { FastifyReply } from "fastify"; +import type { OpResult } from "./index.js"; + +export { withContractErrorHandler } from "../drizzle-fastify/route-error-handler.js"; +export { parseListQueryString, rawQueryOf } from "../drizzle-fastify/list-query.js"; + +/** + * Send `result` on `reply`: a failure with the status the service gave it and its body as is, a + * success with `okStatus` and the value mapped to the wire by `toWire` (absent, sent as is). + * `okStatus` 204 sends no body. + */ +export function sendOpResult( + reply: FastifyReply, + result: OpResult, + okStatus = 200, + toWire?: (value: T) => unknown, +): FastifyReply { + if (!result.ok) return reply.code(result.status).send(result.error); + if (okStatus === 204) return reply.code(204).send(); + return reply.code(okStatus).send(toWire === undefined ? result.value : toWire(result.value)); +} diff --git a/server/typescript/packages/runtime-ts/src/service/index.ts b/server/typescript/packages/runtime-ts/src/service/index.ts new file mode 100644 index 0000000000..47953c1ab3 --- /dev/null +++ b/server/typescript/packages/runtime-ts/src/service/index.ts @@ -0,0 +1,265 @@ +// The mechanics a generated service shell calls (ADR-0067 layer 4, `meta gen` generator `service`). +// +// A generated operation file decides WHAT runs: which schema validates the input, which fields a +// body may name, which row it loads and writes. This module is HOW, store by store: one transaction +// (or a savepoint inside the caller's), the row lock, the dialect's read-back after a write, the +// list query, and the conversion of a refusal or a constraint failure into a result the transport +// maps to the wire. It imports drizzle-orm and nothing from a web framework, so a job, a queue +// consumer or a test calls a service exactly as a route does. +// +// The semantics are the ones `mountCrudRoutes` (../drizzle-fastify) has always answered with, so a +// service behind the thin transport passes the same shared API tests the flat routes pass. + +import { and, asc, count, eq, type SQL } from "drizzle-orm"; +import type { ZodTypeAny, z } from "zod"; +import { classifyConstraintError, logAndRedact, RedactedDatabaseError } from "../constraint-errors.js"; +import { validationErrorBody } from "../route-errors.js"; +import { ERROR_CODE_UNKNOWN_FIELDS, stripDeniedColumns, unknownBodyKeys } from "../wire-format.js"; +import { supportsReturning, type SqlDialect } from "../sql-dialect.js"; +import { coerceIdForColumn, contractErrorCode, extractRowCount, firstRow, isTruthyFlag } from "../drizzle-fastify/util.js"; +import { parseFilterParams } from "../drizzle-fastify/filter-parser.js"; +import { FilterParseError, pageLimit, type PageSize } from "../drizzle-fastify/list-params.js"; +import type { FilterAllowlist, SortAllowlist } from "../drizzle-fastify/filter-allowlist.js"; + +export type { SqlDialect } from "../sql-dialect.js"; +export type { PageSize } from "../drizzle-fastify/list-params.js"; +export type { FilterAllowlist, SortAllowlist } from "../drizzle-fastify/filter-allowlist.js"; +// The wire mappers a generated service index builds its `ToWire` from: no framework in them. +export { timestampWire } from "../timestamp-wire.js"; +export { withWire } from "../wire-format.js"; + +// biome-ignore lint/suspicious/noExplicitAny: the adopter's Drizzle database, table or transaction +type Drizzle = any; + +/** An error body: a short code, and whatever detail the contract gives that code. */ +export interface ServiceErrorBody { + readonly error: string; + readonly [detail: string]: unknown; +} + +/** + * What an operation answers. A failure carries the HTTP status the REST contract gives its code + * (docs/features/api-contract.md), so every transport maps it the same way; a caller that is not + * HTTP reads `error.error`. + */ +export type OpResult = + | { readonly ok: true; readonly value: T } + | { readonly ok: false; readonly status: number; readonly error: ServiceErrorBody }; + +/** The status of a refusal the shell raises with no status of its own: a business refusal (ADR-0067 §4). */ +export const REFUSAL_STATUS = 409; + +/** Thrown inside an operation to refuse it. The transaction it was thrown in rolls back. */ +export class Refusal extends Error { + constructor( + readonly body: ServiceErrorBody, + readonly status: number = REFUSAL_STATUS, + ) { + super(body.error); + this.name = "Refusal"; + } +} + +/** Refuse the operation with `body`, answered with `status`. */ +export function refuse(body: ServiceErrorBody, status: number = REFUSAL_STATUS): never { + throw new Refusal(body, status); +} + +/** The refusal of a row that is not there. */ +export function notFound(): never { + refuse({ error: "not_found" }, 404); +} + +/** The options every operation takes. */ +export interface OpOptions { + /** + * A transaction the caller opened, for a job that runs several operations atomically. A write + * runs in a savepoint inside it, so a refusal undoes this operation's writes and leaves the + * caller's transaction open; a read runs on it. + */ + readonly tx?: unknown; +} + +/** + * Run a write operation in one transaction: a new one on `db`, or a savepoint inside `tx`. A + * refusal rolls the transaction back and is answered as a failed result, as is a write the + * database refused on a constraint. Any other failure is logged and rethrown redacted, with no + * SQL in it. + */ +export async function inWriteTransaction( + db: unknown, + tx: unknown, + fn: (tx: Drizzle) => Promise, +): Promise> { + const scope: Drizzle = tx ?? db; + try { + return { ok: true, value: await scope.transaction(fn) }; + } catch (e) { + return failure(e); + } +} + +/** Run a read operation on `tx` when the caller passed one, else on `db`. A query opens no write transaction. */ +export async function inReadScope(db: unknown, tx: unknown, fn: (db: Drizzle) => Promise): Promise> { + try { + return { ok: true, value: await fn(tx ?? db) }; + } catch (e) { + return failure(e); + } +} + +function failure(e: unknown): OpResult { + if (e instanceof Refusal) return { ok: false, status: e.status, error: e.body }; + if (e instanceof FilterParseError) { + return { ok: false, status: 400, error: { error: contractErrorCode(e.code), ...(e.details ?? {}) } }; + } + const f = classifyConstraintError(e); + if (f !== undefined) return { ok: false, status: f.status, error: f.body }; + logAndRedact(e); + throw new RedactedDatabaseError(); +} + +/** What a write body may name. */ +export interface WriteBodyRules { + /** Every key a body may carry; another is refused with `unknown_fields`. Absent, unknown keys are dropped. */ + readonly knownFields?: readonly string[]; + /** Keys a body may carry that no write takes (a credential, a `@formExclude` field): dropped. */ + readonly writeDeniedColumns?: readonly string[]; +} + +/** + * Validate a write body against its create or update schema: the keys first (`unknown_fields`), + * then the schema, which stamps what it declares (`@autoSet`) and lists every issue + * (`validation`). + */ +export function validateBody(schema: S, body: unknown, rules: WriteBodyRules): z.output { + const unknown = unknownBodyKeys(body, rules.knownFields); + if (unknown.length > 0) refuse({ error: ERROR_CODE_UNKNOWN_FIELDS, fields: unknown }, 400); + const parsed = schema.safeParse(stripDeniedColumns(body, rules.writeDeniedColumns)); + if (!parsed.success) refuse(validationErrorBody(parsed.error.issues) as unknown as ServiceErrorBody, 400); + return parsed.data; +} + +/** + * The condition that addresses the row of `table` whose `keyField` is `id`, compared as the column + * stores it, or a refusal (`invalid_id`) when `id` is not the canonical spelling of a key: a + * numeric-looking id on a text key stays text, and `0x1` is no numeric key. + * + * Built here rather than in the generated file, so the condition and the queries that take it + * come from one drizzle-orm: a generated file never hands this module a `SQL` of its own copy. + */ +export function keyCondition(table: Drizzle, keyField: string, id: string | number): SQL { + const column = table[keyField]; + const key = coerceIdForColumn(column, String(id)); + if (key === undefined) refuse({ error: "invalid_id" }, 400); + return eq(column, key); +} + +/** Does this dialect lock a row read for update? SQLite has no row lock: its writer lock is the whole database. */ +function locksRows(dialect: SqlDialect): boolean { + return dialect === "postgres" || dialect === "mysql"; +} + +/** Read one row by `cond`, locked for the rest of the transaction where the dialect has a row lock. */ +export async function loadForWrite(tx: Drizzle, table: Drizzle, cond: SQL, dialect: SqlDialect): Promise | undefined> { + let q = tx.select().from(table).where(cond).limit(1).$dynamic(); + if (locksRows(dialect)) q = q.for("update"); + const rows = (await q) as Record[]; + return rows[0]; +} + +/** Read one row by `cond`, or undefined. */ +export async function readOne(db: Drizzle, src: Drizzle, cond: SQL): Promise | undefined> { + return (await firstRow(db, src, cond)) as Record | undefined; +} + +/** + * Insert `values` and read the written row back. MySQL has no RETURNING, so there the row is read + * back by its key: the one the body assigned, else the one the database generated. + */ +export async function insertRow( + tx: Drizzle, + table: Drizzle, + values: Record, + dialect: SqlDialect, + keyField = "id", +): Promise> { + if (supportsReturning(dialect)) { + return ((await tx.insert(table).values(values).returning()) as Record[])[0]!; + } + const [inserted] = (await tx.insert(table).values(values).$returningId()) as Array | undefined>; + const key = values[keyField] ?? inserted?.[keyField]; + return (await readOne(tx, table, eq(table[keyField], key))) as Record; +} + +/** Update the row `cond` names with `data` and read it back. */ +export async function updateRow( + tx: Drizzle, + table: Drizzle, + data: Record, + cond: SQL, + dialect: SqlDialect, +): Promise | undefined> { + if (supportsReturning(dialect)) { + return ((await tx.update(table).set(data).where(cond).returning()) as Record[])[0]; + } + await tx.update(table).set(data).where(cond); + return readOne(tx, table, cond); +} + +/** Delete the rows `cond` names, and say how many went. */ +export async function deleteRows(tx: Drizzle, table: Drizzle, cond: SQL): Promise { + return extractRowCount(await tx.delete(table).where(cond)); +} + +/** How a list reads its source. */ +export interface ListSpec { + readonly filterAllowlist: FilterAllowlist; + readonly sortAllowlist: SortAllowlist; + readonly dialect: SqlDialect; + /** The project's page size (`api.pagination`); absent, a list with no `limit` answers 50 rows. */ + readonly pagination?: PageSize; + /** The key field a list with no `sort` is ordered by, so a page is stable. Default `id`. */ + readonly keyField?: string; +} + +/** A page of a list, and the count of every row the filter matches when the query asked for it (`withCount`). */ +export interface ListPage { + readonly rows: T[]; + readonly total?: number; +} + +/** + * The list query, as the bracketed tree a query string parses to + * (`{ filter: { name: { like: "A%" } }, sort: "name:asc", limit: "10" }`). A job passes the same + * tree a route parses from its URL. + */ +export type ListQueryInput = Record; + +/** + * Read a page of `src`: the filter, search, sort and page of `query`, checked against the + * allowlists, ordered by the key when the query names no sort. A refused query is answered as the + * REST contract answers it (`invalid_filter_field`, `invalid_sort`, `limit_too_large`, ...). + */ +export async function listRows(db: Drizzle, src: Drizzle, query: ListQueryInput, spec: ListSpec): Promise>> { + const parsed = parseFilterParams({ + query, + table: src, + allowlist: spec.filterAllowlist, + sortAllowlist: spec.sortAllowlist, + dialect: spec.dialect, + }); + const where = parsed.where && parsed.searchWhere ? and(parsed.where, parsed.searchWhere) : (parsed.where ?? parsed.searchWhere); + let q = db.select().from(src).$dynamic(); + if (where) q = q.where(where); + if (parsed.orderBy) q = q.orderBy(...parsed.orderBy); + else if (src[spec.keyField ?? "id"] !== undefined) q = q.orderBy(asc(src[spec.keyField ?? "id"])); + q = q.limit(pageLimit(parsed.limit, spec.pagination)); + if (parsed.offset !== undefined) q = q.offset(parsed.offset); + const rows = (await q) as Record[]; + if (!isTruthyFlag(query.withCount)) return { rows }; + let cq = db.select({ c: count() }).from(src).$dynamic(); + if (where) cq = cq.where(where); + const countRow = (await cq)[0] as { c: number } | undefined; + return { rows, total: countRow?.c ?? 0 }; +} diff --git a/server/typescript/packages/runtime-ts/test/service.test.ts b/server/typescript/packages/runtime-ts/test/service.test.ts new file mode 100644 index 0000000000..c76a69f9c0 --- /dev/null +++ b/server/typescript/packages/runtime-ts/test/service.test.ts @@ -0,0 +1,197 @@ +// The store mechanics a generated service calls (`@metaobjectsdev/runtime-ts/service`, ADR-0067 +// layer 4): one transaction per write, a savepoint inside a caller's, a refusal that rolls back, +// and the failures the REST contract gives a status. +// +// libsql on a scratch file: drizzle's libsql driver runs an async transaction, and an in-memory +// libsql database would hand the transaction a connection of its own with no tables in it. +import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test"; +import { createClient, type Client } from "@libsql/client"; +import { drizzle } from "drizzle-orm/libsql"; +import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { z } from "zod"; +import { + deleteRows, + inReadScope, + insertRow, + inWriteTransaction, + keyCondition, + listRows, + loadForWrite, + notFound, + refuse, + updateRow, + validateBody, + type OpResult, +} from "../src/service/index.js"; +import { RedactedDatabaseError } from "../src/constraint-errors.js"; + +const notes = sqliteTable("notes", { + id: integer("id").primaryKey({ autoIncrement: true }), + title: text("title").notNull(), + secret: text("secret"), +}); +const InsertSchema = z.object({ id: z.number().int().optional(), title: z.string().min(1), secret: z.string().optional() }); +const allowlist = { title: { ops: ["eq", "like"], kind: "string", leadingWildcard: false } } as never; +const sortAllowlist = { title: true } as never; + +let dir: string; +let client: Client; +let db: ReturnType; + +beforeAll(async () => { + dir = mkdtempSync(join(process.env.DEV_SCRATCH ?? tmpdir(), "runtime-ts-service-")); + client = createClient({ url: `file:${join(dir, "service.db")}` }); + db = drizzle(client); + await client.execute("CREATE TABLE notes (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, secret TEXT)"); +}); + +afterAll(() => { + client.close(); + rmSync(dir, { recursive: true, force: true }); +}); + +beforeEach(async () => { + await client.execute("DELETE FROM notes"); + // AUTOINCREMENT keeps its counter across a DELETE; each test starts its keys at 1. + await client.execute("DELETE FROM sqlite_sequence WHERE name = 'notes'"); +}); + +async function titles(): Promise { + return (await client.execute("SELECT title FROM notes ORDER BY id")).rows.map((r) => String(r["title"])); +} + +function failed(r: OpResult): { status: number; error: Record } { + if (r.ok) throw new Error(`expected a failure, got ${JSON.stringify(r.value)}`); + return r; +} + +describe("inWriteTransaction", () => { + test("a write commits and answers its value", async () => { + const r = await inWriteTransaction(db, undefined, (tx) => insertRow(tx, notes, { title: "a" }, "sqlite")); + expect(r).toEqual({ ok: true, value: { id: 1, title: "a", secret: null } }); + expect(await titles()).toEqual(["a"]); + }); + + test("a refusal rolls back every write the operation made and answers 409 with its body", async () => { + const r = await inWriteTransaction(db, undefined, async (tx) => { + await insertRow(tx, notes, { title: "written, then undone" }, "sqlite"); + refuse({ error: "not_allowed", reason: "closed" }); + }); + expect(failed(r)).toEqual({ ok: false, status: 409, error: { error: "not_allowed", reason: "closed" } } as never); + expect(await titles()).toEqual([]); + }); + + test("inside a caller's transaction a refusal undoes this operation only (a savepoint)", async () => { + await db.transaction(async (outer) => { + await insertRow(outer, notes, { title: "the caller's" }, "sqlite"); + const r = await inWriteTransaction(db, outer, async (tx) => { + await insertRow(tx, notes, { title: "the operation's" }, "sqlite"); + notFound(); + }); + expect(failed(r).status).toBe(404); + }); + expect(await titles()).toEqual(["the caller's"]); + }); + + test("a constraint the database refuses answers the contract's constraint_violation", async () => { + await insertRow(db, notes, { id: 7, title: "first" }, "sqlite"); + const r = await inWriteTransaction(db, undefined, (tx) => insertRow(tx, notes, { id: 7, title: "again" }, "sqlite")); + const f = failed(r); + expect(f.status).toBe(409); + expect(f.error.error).toBe("constraint_violation"); + }); + + test("any other failure is rethrown redacted, with no SQL in it", async () => { + const quiet = console.error; + console.error = () => {}; + try { + const bogus = sqliteTable("no_such_table", { id: integer("id").primaryKey() }); + await expect(inWriteTransaction(db, undefined, (tx) => insertRow(tx, bogus, { id: 1 }, "sqlite"))).rejects.toBeInstanceOf( + RedactedDatabaseError, + ); + } finally { + console.error = quiet; + } + }); +}); + +describe("validateBody", () => { + const rules = { knownFields: ["id", "title", "secret"], writeDeniedColumns: ["secret"] }; + + test("an unknown key is refused with unknown_fields, naming it", async () => { + const r = await inWriteTransaction(db, undefined, async () => validateBody(InsertSchema, { title: "a", colour: "red" }, rules)); + expect(failed(r)).toEqual({ ok: false, status: 400, error: { error: "unknown_fields", fields: ["colour"] } } as never); + }); + + test("a schema failure is refused with validation", async () => { + const r = await inWriteTransaction(db, undefined, async () => validateBody(InsertSchema, { title: "" }, rules)); + const f = failed(r); + expect(f.status).toBe(400); + expect(f.error.error).toBe("validation"); + }); + + test("a write-denied key is dropped, not written", () => { + expect(validateBody(InsertSchema, { title: "a", secret: "s" }, rules)).toEqual({ title: "a" }); + }); + + test("with no known-field list an unknown key is dropped by the schema", () => { + expect(validateBody(InsertSchema, { title: "a", colour: "red" }, {})).toEqual({ title: "a" }); + }); +}); + +describe("keyCondition, loadForWrite, updateRow and deleteRows", () => { + test("an id that is no key of the column is refused with invalid_id", async () => { + const r = await inReadScope(db, undefined, async () => keyCondition(notes, "id", "0x1")); + expect(failed(r)).toEqual({ ok: false, status: 400, error: { error: "invalid_id" } } as never); + }); + + test("update and delete address the row the key names", async () => { + await insertRow(db, notes, { title: "a" }, "sqlite"); + await insertRow(db, notes, { title: "b" }, "sqlite"); + const r = await inWriteTransaction(db, undefined, async (tx) => { + const cond = keyCondition(notes, "id", "2"); + expect(await loadForWrite(tx, notes, cond, "sqlite")).toEqual({ id: 2, title: "b", secret: null }); + return updateRow(tx, notes, { title: "B" }, cond, "sqlite"); + }); + expect(r).toEqual({ ok: true, value: { id: 2, title: "B", secret: null } }); + expect(await deleteRows(db, notes, keyCondition(notes, "id", 1))).toBe(1); + expect(await titles()).toEqual(["B"]); + }); +}); + +describe("listRows", () => { + const spec = { filterAllowlist: allowlist, sortAllowlist, dialect: "sqlite" as const }; + + beforeEach(async () => { + for (const title of ["c", "a", "b"]) await insertRow(db, notes, { title }, "sqlite"); + }); + + test("with no sort the page is ordered by the key", async () => { + const r = await inReadScope(db, undefined, (d) => listRows(d, notes, {}, spec)); + expect(r.ok && r.value.rows.map((row) => row.title)).toEqual(["c", "a", "b"]); + expect(r.ok && r.value.total).toBeUndefined(); + }); + + test("a filter, a sort, a page and the count", async () => { + const r = await inReadScope(db, undefined, (d) => + listRows(d, notes, { filter: { title: { like: "_" } }, sort: "title:desc", limit: "2", withCount: "1" }, spec), + ); + expect(r.ok && r.value).toEqual({ + rows: [ + { id: 1, title: "c", secret: null }, + { id: 3, title: "b", secret: null }, + ], + total: 3, + }); + }); + + test("a field off the allowlist is refused as the REST contract refuses it", async () => { + const r = await inReadScope(db, undefined, (d) => listRows(d, notes, { filter: { secret: "x" } }, spec)); + const f = failed(r); + expect(f.status).toBe(400); + expect(f.error.error).toBe("invalid_filter_field"); + }); +}); diff --git a/spec/decisions/ADR-0067-layering-and-the-service-seam.md b/spec/decisions/ADR-0067-layering-and-the-service-seam.md index c80c89772d..dce592f46c 100644 --- a/spec/decisions/ADR-0067-layering-and-the-service-seam.md +++ b/spec/decisions/ADR-0067-layering-and-the-service-seam.md @@ -16,8 +16,12 @@ Amendment 3, as ADR-0066 §8 restates it. The core is the contracts and the conf and every generator below is a helper. Layer 0 and layer 1 are generated: `rules-names` and `contract-types` write in TypeScript, and C# -writes its own names and create and update records. The service shells and the per-package choice -of generators are later work. ADR-0066's vocabulary is inert at run time until they land. +writes its own names and create and update records. In TypeScript, layers 4 and 5 have started: +`service` writes each package's derived list, get, create, update and delete in one transaction with +the declared write rules, and `service-routes` the thin Fastify transport over it (the `service` +layer label of §5.6). Transitions, declared operations, the policy, bodies and events interfaces, +the other ports' shells and the per-package choice of generators are later work. ADR-0066's +vocabulary is inert at run time until they land. **Experimental.** The vocabulary this design generates from is experimental (ADR-0066 Status, `docs/compatibility-policy.md`): it may change in a MINOR, including removals and renames, until From 6802eeeb49a42783640950b89a8253c15337db34 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 03:20:30 -0500 Subject: [PATCH 2/7] no-mistakes(review): apply reviewer inline fixes --- .../packages/codegen-ts/src/generators/service-routes-file.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts b/server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts index ef2a809ff4..f04944688a 100644 --- a/server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts @@ -12,7 +12,7 @@ import { renderFastifyTransport } from "../templates/service-file.js"; export interface ServiceRoutesFileOpts { /** Narrow which entities get routes. Keep it the same as the service generator's. */ filter?: (entity: MetaObject) => boolean; - /** Where the emitted file imports `@metaobjectsdev/runtime-ts/drizzle-fastify` from. Absent: the package. */ + /** Where the emitted file imports `@metaobjectsdev/runtime-ts/service/fastify` from. Absent: the package. */ runtimeImport?: string; /** Named output target. It must be the entity module's target. */ target?: string; From 5d9f1bd311334ca237b259f21e67f4db9190fc2e Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 03:24:58 -0500 Subject: [PATCH 3/7] no-mistakes(review): Narrow sqlite service Db to async drivers; fix cli build --- docs/features/business-rules.md | 4 ++++ docs/ports/typescript.md | 3 ++- server/typescript/packages/cli/src/lib/catalog-listing.ts | 1 + .../typescript/packages/codegen-ts/src/dialect-module.ts | 7 +++++-- .../packages/codegen-ts/src/generators/service-file.ts | 3 +++ .../packages/codegen-ts/src/templates/service-file.ts | 5 +++-- 6 files changed, 18 insertions(+), 5 deletions(-) diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index 0bcd8f5e30..83b614d7c6 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -360,6 +360,10 @@ savepoint inside it. A refusal rolls the transaction back. A query opens no writ An operation answers an `OpResult`: the value, or a failure carrying the code and the HTTP status the [API contract](api-contract.md) gives it, so every transport maps it the same way. +On SQLite the service needs an async Drizzle driver such as libsql: `ServiceDeps.db` is typed +`BaseSQLiteDatabase<"async", …>`, so a sync driver (better-sqlite3, bun:sqlite) fails to type-check, +because a write awaits inside its transaction callback. The flat generators still accept both. + `serviceRoutesFile()` (stable name `service-routes`, layer `api`, Fastify) writes the thin transport (layer 5) beside it, `/transport/fastify.ts`: one plugin per package, registered with the service it calls. Each route parses the request, calls one operation and diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index 8d0c9c9e22..d02084c7f6 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -758,7 +758,8 @@ one transaction with the declared write rules) and `service/index.ts` with the ` interface and `createService(deps)`. `serviceRoutesFile()` (stable name `service-routes`) writes `/transport/fastify.ts`, the routes that call it. Both need `entity` and `contract-types` in the same target. Neither is scaffolded; add them to `generators` or `meta eject` -them. See [Business rules](../features/business-rules.md#the-service-layer-typescript). +them. On SQLite the service needs an async Drizzle driver such as libsql (`Db` is +`BaseSQLiteDatabase<"async", …>`). See [Business rules](../features/business-rules.md#the-service-layer-typescript). ### Prove it works diff --git a/server/typescript/packages/cli/src/lib/catalog-listing.ts b/server/typescript/packages/cli/src/lib/catalog-listing.ts index fdc21dd0aa..df1f0e496d 100644 --- a/server/typescript/packages/cli/src/lib/catalog-listing.ts +++ b/server/typescript/packages/cli/src/lib/catalog-listing.ts @@ -486,6 +486,7 @@ export function declaredDepsOf(projectRoot: string): Set | undefined { const LAYER_BLURB: Record = { model: "the entity modules and the constants beside them", persistence: "how rows are read and written", + service: "the operations a route, a job or an agent tool calls — one transaction per write", api: "the HTTP surface — pick ONE framework", client: "the browser tier — form + hooks + grid compose, they do not conflict", docs: "pages about the model and the code — listed like the rest, written to the `docs` target", diff --git a/server/typescript/packages/codegen-ts/src/dialect-module.ts b/server/typescript/packages/codegen-ts/src/dialect-module.ts index 1f247c1ea2..e7e83a3d96 100644 --- a/server/typescript/packages/codegen-ts/src/dialect-module.ts +++ b/server/typescript/packages/codegen-ts/src/dialect-module.ts @@ -34,8 +34,11 @@ export function dialectModule(dialect: Dialect): DialectModule { * (ADR-0008 — `db` is passed in). Every type argument is as open as Drizzle's own constraint * allows, so any driver's database handle assigns — a schema-carrying `drizzle(client, * { schema })` as well as a schema-less one. + * + * SQLite accepts a sync and an async driver by default. `asyncOnly` narrows it to async drivers + * (libsql), for a tier that awaits inside a transaction callback, which a sync driver rejects. */ -export function dbTypeBlock(dialect: Dialect): { import: string; alias: string } { +export function dbTypeBlock(dialect: Dialect, opts?: { asyncOnly?: boolean }): { import: string; alias: string } { switch (dialect) { case "postgres": return { @@ -50,7 +53,7 @@ export function dbTypeBlock(dialect: Dialect): { import: string; alias: string } case "sqlite": return { import: `import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core";`, - alias: `type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>;`, + alias: `type Db = BaseSQLiteDatabase<${opts?.asyncOnly ? '"async"' : '"sync" | "async"'}, unknown, Record>;`, }; } } diff --git a/server/typescript/packages/codegen-ts/src/generators/service-file.ts b/server/typescript/packages/codegen-ts/src/generators/service-file.ts index 4fcad9ceee..e11825e9d7 100644 --- a/server/typescript/packages/codegen-ts/src/generators/service-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/service-file.ts @@ -9,6 +9,9 @@ import { renderServiceFiles } from "../templates/service-file.js"; * create, update and delete; every write runs in one transaction with the declared write rules * (ADR-0045). Hand-written code calls the service; a transport (`serviceRoutesFile()`) mounts it. * + * SQLite needs an async Drizzle driver (libsql): the emitted `Db` type is `BaseSQLiteDatabase<"async", …>`, + * so a sync driver (better-sqlite3, bun:sqlite) fails to type-check instead of failing at run time. + * * Imports the entity module (the Drizzle table and allowlists, `entityFile()`) and the contract * types (`contractTypes()`), so list both. The built-in twin of `src/reference/service.ts` * (ADR-0034 scaffold-and-own); the reference-byte-identical gate holds the two to the same output. diff --git a/server/typescript/packages/codegen-ts/src/templates/service-file.ts b/server/typescript/packages/codegen-ts/src/templates/service-file.ts index a51ac5cb34..c277c0b8f2 100644 --- a/server/typescript/packages/codegen-ts/src/templates/service-file.ts +++ b/server/typescript/packages/codegen-ts/src/templates/service-file.ts @@ -243,9 +243,10 @@ function renderServiceIndex(pkg: ServicePackage, path: string, ctx: RenderContex const timestampWire = w.use("timestampWire", runtime); const withWire = w.use("withWire", runtime); const type = serviceTypeName(pkg.package); - const { import: dbImport, alias: dbAlias } = dbTypeBlock(ctx.dialect); + const { import: dbImport, alias: dbAlias } = dbTypeBlock(ctx.dialect, { asyncOnly: true }); - // The dialect's Drizzle base type, the same one the queries generator types `db` with. + // The dialect's Drizzle base type, the queries generator's, except that SQLite is async-only: + // a write awaits inside its transaction callback, which a sync driver (better-sqlite3, bun:sqlite) rejects. const dbModule = /from "([^"]+)"/.exec(dbImport)![1]!; for (const t of /import type \{ ([^}]+) \}/.exec(dbImport)![1]!.split(",").map((s) => s.trim())) w.useType(t, dbModule); w.line(dbAlias); From 70cd7f8cff6fddfb7de633d4ca3ff4b377211388 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 03:27:00 -0500 Subject: [PATCH 4/7] no-mistakes(review): Test sqlite async Db; regen agent-context goldens --- ...6974256b798cf22.md => c99d78077736fd2d.md} | 3 +- agent-context-shipped/manifest.json | 56 +++++++++---------- .../skills/metaobjects-codegen/SKILL.md | 3 +- .../skills/metaobjects-codegen/SKILL.md | 3 +- .../skills/metaobjects-codegen/SKILL.md | 3 +- .../skills/metaobjects-codegen/SKILL.md | 3 +- .../skills/metaobjects-codegen/SKILL.md | 3 +- .../skills/metaobjects-codegen/SKILL.md | 3 +- .../codegen-ts/test/service-file.test.ts | 9 ++- 9 files changed, 50 insertions(+), 36 deletions(-) rename agent-context-shipped/files/{86974256b798cf22.md => c99d78077736fd2d.md} (99%) diff --git a/agent-context-shipped/files/86974256b798cf22.md b/agent-context-shipped/files/c99d78077736fd2d.md similarity index 99% rename from agent-context-shipped/files/86974256b798cf22.md rename to agent-context-shipped/files/c99d78077736fd2d.md index c30d6fc156..5331ea6a0a 100644 --- a/agent-context-shipped/files/86974256b798cf22.md +++ b/agent-context-shipped/files/c99d78077736fd2d.md @@ -344,12 +344,13 @@ A library row also carries `provides` (what is in the box) and, under `--probe`, added here, which of your entities `extends` into it, and any generator the library implies that you have not wired. -### The six layers, and what picks them +### The seven layers, and what picks them | layer | what it is | chosen by | |---|---|---| | `model` | entity/DTO/value-object modules and the constants beside them | app shape | | `persistence` | how rows are read and written | app shape | +| `service` | one module per package that runs each operation in a transaction with the write rules (ADR-0067); its transport is on `api` | app shape | | `api` | the HTTP surface — pick one framework | app shape | | `client` | the browser tier | app shape | | `docs` | model pages, api reference, agent pages, requirement ledger — each its own generator entry, like any other | app shape | diff --git a/agent-context-shipped/manifest.json b/agent-context-shipped/manifest.json index b616f775dd..8c6a5a8b5b 100644 --- a/agent-context-shipped/manifest.json +++ b/agent-context-shipped/manifest.json @@ -117,7 +117,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -332,7 +332,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -552,7 +552,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -775,7 +775,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -988,7 +988,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -1179,7 +1179,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -1375,7 +1375,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -1574,7 +1574,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -1763,7 +1763,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -1954,7 +1954,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -2150,7 +2150,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -2349,7 +2349,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -2538,7 +2538,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -2729,7 +2729,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -2925,7 +2925,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -3124,7 +3124,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -3313,7 +3313,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -3504,7 +3504,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -3700,7 +3700,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -3899,7 +3899,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -4080,7 +4080,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -4251,7 +4251,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -4427,7 +4427,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -4606,7 +4606,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -4792,7 +4792,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -5004,7 +5004,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -5221,7 +5221,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", @@ -5441,7 +5441,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/SKILL.md", - "file": "86974256b798cf22.md" + "file": "c99d78077736fd2d.md" }, { "path": ".claude/skills/metaobjects-codegen/references/any-stack.md", diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/SKILL.md index c30d6fc156..5331ea6a0a 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -344,12 +344,13 @@ A library row also carries `provides` (what is in the box) and, under `--probe`, added here, which of your entities `extends` into it, and any generator the library implies that you have not wired. -### The six layers, and what picks them +### The seven layers, and what picks them | layer | what it is | chosen by | |---|---|---| | `model` | entity/DTO/value-object modules and the constants beside them | app shape | | `persistence` | how rows are read and written | app shape | +| `service` | one module per package that runs each operation in a transaction with the write rules (ADR-0067); its transport is on `api` | app shape | | `api` | the HTTP surface — pick one framework | app shape | | `client` | the browser tier | app shape | | `docs` | model pages, api reference, agent pages, requirement ledger — each its own generator entry, like any other | app shape | diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md index c30d6fc156..5331ea6a0a 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -344,12 +344,13 @@ A library row also carries `provides` (what is in the box) and, under `--probe`, added here, which of your entities `extends` into it, and any generator the library implies that you have not wired. -### The six layers, and what picks them +### The seven layers, and what picks them | layer | what it is | chosen by | |---|---|---| | `model` | entity/DTO/value-object modules and the constants beside them | app shape | | `persistence` | how rows are read and written | app shape | +| `service` | one module per package that runs each operation in a transaction with the write rules (ADR-0067); its transport is on `api` | app shape | | `api` | the HTTP surface — pick one framework | app shape | | `client` | the browser tier | app shape | | `docs` | model pages, api reference, agent pages, requirement ledger — each its own generator entry, like any other | app shape | diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/SKILL.md index c30d6fc156..5331ea6a0a 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -344,12 +344,13 @@ A library row also carries `provides` (what is in the box) and, under `--probe`, added here, which of your entities `extends` into it, and any generator the library implies that you have not wired. -### The six layers, and what picks them +### The seven layers, and what picks them | layer | what it is | chosen by | |---|---|---| | `model` | entity/DTO/value-object modules and the constants beside them | app shape | | `persistence` | how rows are read and written | app shape | +| `service` | one module per package that runs each operation in a transaction with the write rules (ADR-0067); its transport is on `api` | app shape | | `api` | the HTTP surface — pick one framework | app shape | | `client` | the browser tier | app shape | | `docs` | model pages, api reference, agent pages, requirement ledger — each its own generator entry, like any other | app shape | diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/SKILL.md index c30d6fc156..5331ea6a0a 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -344,12 +344,13 @@ A library row also carries `provides` (what is in the box) and, under `--probe`, added here, which of your entities `extends` into it, and any generator the library implies that you have not wired. -### The six layers, and what picks them +### The seven layers, and what picks them | layer | what it is | chosen by | |---|---|---| | `model` | entity/DTO/value-object modules and the constants beside them | app shape | | `persistence` | how rows are read and written | app shape | +| `service` | one module per package that runs each operation in a transaction with the write rules (ADR-0067); its transport is on `api` | app shape | | `api` | the HTTP surface — pick one framework | app shape | | `client` | the browser tier | app shape | | `docs` | model pages, api reference, agent pages, requirement ledger — each its own generator entry, like any other | app shape | diff --git a/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-codegen/SKILL.md index c30d6fc156..5331ea6a0a 100644 --- a/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -344,12 +344,13 @@ A library row also carries `provides` (what is in the box) and, under `--probe`, added here, which of your entities `extends` into it, and any generator the library implies that you have not wired. -### The six layers, and what picks them +### The seven layers, and what picks them | layer | what it is | chosen by | |---|---|---| | `model` | entity/DTO/value-object modules and the constants beside them | app shape | | `persistence` | how rows are read and written | app shape | +| `service` | one module per package that runs each operation in a transaction with the write rules (ADR-0067); its transport is on `api` | app shape | | `api` | the HTTP surface — pick one framework | app shape | | `client` | the browser tier | app shape | | `docs` | model pages, api reference, agent pages, requirement ledger — each its own generator entry, like any other | app shape | diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md index c30d6fc156..5331ea6a0a 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -344,12 +344,13 @@ A library row also carries `provides` (what is in the box) and, under `--probe`, added here, which of your entities `extends` into it, and any generator the library implies that you have not wired. -### The six layers, and what picks them +### The seven layers, and what picks them | layer | what it is | chosen by | |---|---|---| | `model` | entity/DTO/value-object modules and the constants beside them | app shape | | `persistence` | how rows are read and written | app shape | +| `service` | one module per package that runs each operation in a transaction with the write rules (ADR-0067); its transport is on `api` | app shape | | `api` | the HTTP surface — pick one framework | app shape | | `client` | the browser tier | app shape | | `docs` | model pages, api reference, agent pages, requirement ledger — each its own generator entry, like any other | app shape | diff --git a/server/typescript/packages/codegen-ts/test/service-file.test.ts b/server/typescript/packages/codegen-ts/test/service-file.test.ts index 589b3c249d..3c514a7238 100644 --- a/server/typescript/packages/codegen-ts/test/service-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/service-file.test.ts @@ -6,7 +6,7 @@ import { describe, expect, test } from "bun:test"; import { join, resolve, dirname } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { InMemoryStringSource, loadUris, MetaDataLoader, type MetaRoot } from "@metaobjectsdev/metadata"; -import { contractTypes, entityFile, serviceFile, serviceRoutesFile } from "../src/generators/index.js"; +import { contractTypes, entityFile, queriesFile, serviceFile, serviceRoutesFile } from "../src/generators/index.js"; import { defineConfig, runGen, type OutputLayout } from "../src/index.js"; import { serviceModelOf, serviceRoutesName, serviceTypeName } from "../src/service-walk.js"; import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; @@ -90,6 +90,13 @@ describe("service generators — what they write", () => { expect(files["acme/shop/service/createOrder.ts"]).toContain('from "../../../Order.js";'); }); + test("on sqlite the service takes an async Drizzle driver only; the flat queries module still takes both", async () => { + const root = await load("acme::shop", [entity("Order")]); + const files = await gen(root, [entityFile(), contractTypes(), serviceFile(), queriesFile()], "package", { dialect: "sqlite" }); + expect(files["acme/shop/service/index.ts"]).toContain('type Db = BaseSQLiteDatabase<"async", unknown, Record>;'); + expect(files["acme/shop/Order.queries.ts"]).toContain('type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>;'); + }); + test("the service is named for the package's last segment; the root package's is ModelService", () => { expect(serviceTypeName("acme::purchasing")).toBe("PurchasingService"); expect(serviceTypeName("acme::purchase_orders")).toBe("PurchaseOrdersService"); From b0d350e07138d5810194377cd6c9b0e959f0ab3e Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 03:28:15 -0500 Subject: [PATCH 5/7] no-mistakes(review): apply reviewer inline fixes --- fixtures/generator-registry-conformance/registry.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index 0e9d02fe5e..06727f26e9 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -1,5 +1,5 @@ { - "$comment": "CANONICAL generator stable-name manifest (ADR-0021 D3). The single cross-port source of truth for generator stable names. Every port's generator registry is conformance-tested against this file: (1) every generator a port exposes MUST use a name listed here; (2) for each generator, the `ports` array lists exactly the ports expected to expose it (presence is checked both ways); (3) because all ports validate against this one file, a shared concept (e.g. `routes`) is spelled identically everywhere. Port ids: typescript, csharp, java, kotlin, python, and rust (ADR-0065, held to the same four checks by its own test). `tier`: native (idiomatic per-port code) or neutral (language-neutral pages that describe the model the same way in every port; a description of the output, not a door: every generator runs when the project's generator list declares it, ADR-0034 Amendment 9). `layer`: one of model, persistence, api, client, docs, capability — the grouping an adopter SELECTS BY, gated in every port exactly as `tier` is (see README.md). `eject`: \"full\" (the owned copy holds the generator's emit) or an exemption with a written reason and the ruling that grants it; the top-level `eject` block carries the engine surface, the exempt non-generator emitters and the pending list (ADR-0034 Amendment 8, see README.md). Adding/renaming a generator = edit THIS file + the port registry together; the conformance gate fails otherwise.", + "$comment": "CANONICAL generator stable-name manifest (ADR-0021 D3). The single cross-port source of truth for generator stable names. Every port's generator registry is conformance-tested against this file: (1) every generator a port exposes MUST use a name listed here; (2) for each generator, the `ports` array lists exactly the ports expected to expose it (presence is checked both ways); (3) because all ports validate against this one file, a shared concept (e.g. `routes`) is spelled identically everywhere. Port ids: typescript, csharp, java, kotlin, python, and rust (ADR-0065, held to the same four checks by its own test). `tier`: native (idiomatic per-port code) or neutral (language-neutral pages that describe the model the same way in every port; a description of the output, not a door: every generator runs when the project's generator list declares it, ADR-0034 Amendment 9). `layer`: one of model, persistence, service, api, client, docs, capability — the grouping an adopter SELECTS BY, gated in every port exactly as `tier` is (see README.md). `eject`: \"full\" (the owned copy holds the generator's emit) or an exemption with a written reason and the ruling that grants it; the top-level `eject` block carries the engine surface, the exempt non-generator emitters and the pending list (ADR-0034 Amendment 8, see README.md). Adding/renaming a generator = edit THIS file + the port registry together; the conformance gate fails otherwise.", "ports": ["typescript", "csharp", "java", "kotlin", "python", "rust"], "generators": { "entity": { From 713944a81f60811861cc5f14a9b198d1f052e30e Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 04:01:51 -0500 Subject: [PATCH 6/7] no-mistakes(test): Narrow C# drift temp-dir test to own GUID names --- .../CodegenDriftTests.cs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/server/csharp/MetaObjects.Codegen.Tests/CodegenDriftTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CodegenDriftTests.cs index 77ad79a791..a0edfa2659 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/CodegenDriftTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/CodegenDriftTests.cs @@ -159,15 +159,22 @@ public void Verify_renders_in_memory_and_leaves_no_temp_files_behind() // never create a rendered tree (or any meta-verify-codegen-* directory) under the temp dir. Gen(); var tempRoot = Path.GetTempPath(); - var before = Directory.EnumerateFileSystemEntries(tempRoot, "meta-verify-codegen-*").ToHashSet(); + // The temp dir is shared with every other process on the machine (an older Node `meta` CLI + // also makes `meta-verify-codegen-<6 chars>` entries there). Only this port's own naming + // (CodegenDrift: "meta-verify-codegen-" + Guid "N", 32 lowercase hex) is under test. + var before = OwnVerifyTempEntries(tempRoot).ToHashSet(); var result = RunDrift(); - var after = Directory.EnumerateFileSystemEntries(tempRoot, "meta-verify-codegen-*").ToHashSet(); + var after = OwnVerifyTempEntries(tempRoot).ToHashSet(); Assert.True(result.Clean); Assert.Equal(before, after); - Assert.Empty(Directory.EnumerateFileSystemEntries(tempRoot, "meta-verify-codegen-*") - .Except(before)); + Assert.Empty(OwnVerifyTempEntries(tempRoot).Except(before)); } + private static IEnumerable OwnVerifyTempEntries(string tempRoot) => + Directory.EnumerateFileSystemEntries(tempRoot, "meta-verify-codegen-*") + .Where(p => System.Text.RegularExpressions.Regex.IsMatch( + Path.GetFileName(p), "^meta-verify-codegen-[0-9a-f]{32}$")); + private static Dictionary SnapshotDir(string dir) { var snap = new Dictionary(StringComparer.Ordinal); From 119b31d3176c79410af1578cf0d0c7608a1c2f02 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 04:11:59 -0500 Subject: [PATCH 7/7] no-mistakes(document): Add service rows to eject table --- docs/features/own-your-codegen.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index 9777cb5bfd..9da8915093 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -396,6 +396,8 @@ calls it copies the adapter's source too: | `routes` | `routes.ts` — the whole route composition (CRUD, read-only projections, M:N traversal, TPH per-subtype sets), not a call into the engine | `drizzle-fastify/*` (mounts, filter parser, list params, M:N and read-only mounts, error handler), `route-errors.ts`, `constraint-errors.ts`, `timestamp-wire.ts`, `decimal-wire.ts`, `duration-wire.ts`, `wire-format.ts`, `sql-dialect.ts`, `canonical-key.ts`, `errors.ts` | | `routes-hono` | `routes-hono.ts`, likewise self-contained | `hono/*`, plus the shared parser, allowlist, envelope and timestamp files it reaches | | `entity` | `entity.ts` | `drizzle-fastify/filter-allowlist.ts` — the `FilterAllowlist` / `SortAllowlist` types the entity module's allowlists are typed by | +| `service` | `service.ts` | `service/index.ts` — the store mechanics the generated service modules call (transaction, row lock, write-rule stamping) | +| `service-routes` | `service-routes.ts` | `service/fastify.ts` — the request and reply helpers the generated Fastify transport imports | The ejected generators point their output at that copy (`import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index.js"`), so