diff --git a/.claude/rules/codegen-architecture.md b/.claude/rules/codegen-architecture.md index d63bdf87ac..58b5a29651 100644 --- a/.claude/rules/codegen-architecture.md +++ b/.claude/rules/codegen-architecture.md @@ -116,7 +116,7 @@ const { data } = useSubscribers({ **Server validation:** every request validated against the allowlist. Unknown field / disallowed op / invalid value → 400 with structured error code. -**Leading wildcards are rejected by default (TS generated routes):** the generated allowlist ships `leadingWildcard: false` on every field, so a `like` pattern starting with `%` (e.g. `"%@example.com"`) → 400 `filter.leading_wildcard_disallowed` — an unanchored LIKE defeats index usage, so it is fail-closed. Opt in per field by hand-editing that field's entry in the generated `FilterAllowlist` to `leadingWildcard: true` (hand edits inside generated files are preserved by the three-way merge). This gate is a TS-only extension — the other ports do not enforce it (see `docs/features/api-contract.md`, "TS-only filter extensions"). +**Leading wildcards are rejected by default (TS generated routes):** the generated allowlist ships `leadingWildcard: false` on every field, so a `like` pattern starting with `%` (e.g. `"%@example.com"`) → 400 `filter.leading_wildcard_disallowed` — an unanchored LIKE defeats index usage, so it is fail-closed. Opt in per field by hand-editing that field's entry in the generated `FilterAllowlist` to `leadingWildcard: true` (hand edits inside generated files are preserved by the three-way merge). The gate is part of the REST contract since 1.3.0 (`docs/features/api-contract.md`, "The list query: search, combinators and refusals"), and each other port takes it on in its 1.3.0 REST-standard work. **Architecture:** `parseFilterParams` (in `@metaobjectsdev/runtime-ts/drizzle-fastify`) translates parsed qs into a Drizzle expression tree. `buildFilterQs` (in `@metaobjectsdev/runtime-web` and `@metaobjectsdev/tanstack`) serializes a typed filter object back to a bracketed qs URL. diff --git a/AGENTS.md b/AGENTS.md index 81d09c4325..beb954aed3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,7 +74,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (KotlinPoet on JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (578 fixtures; 43 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (578 fixtures; 45 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / C# / Java / Kotlin / Python byte-identical. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/CHANGELOG.md b/CHANGELOG.md index 58140a2a8d..534327d4c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,11 @@ here.** ## [Unreleased] +- **Java: a standalone `{{! comment }}` line leaves no blank line.** mustache.java kept the line break + after a standalone comment tag, so a Java render had one extra blank line where TypeScript, C# and + Python had none. `Renderer` now strips standalone comment lines before mustache.java parses them. A + template with such a line renders differently in Java, so a prompt body with one changes bytes (and + its prompt-cache prefix) on upgrade. The `render-standalone-*` fixtures pin the whitespace rules. - **C#: an unchanged file is never rewritten.** `dotnet meta gen` already left identical output alone when the project keeps a hash manifest. It now does the same on the path with no manifest (output written outside the project, or a program that runs the generators with no state directory), which @@ -83,6 +88,52 @@ here.** because a newer MetaObjects may have written it, but each one is now named once on standard error with the known keys, in the words TypeScript uses. A key inside a block C# owns (`csharp`, `naming`, `wire` and the rest) is refused as before. +- **The REST standard's list handling is part of the cross-port contract.** `?search`, + `filter[or]` / `filter[and]`, the nesting cap, the bare-field and leading-`%` refusals, the + filter-value format check, and the `invalid_json`, `invalid_id`, `pagination.invalid_value` and + `constraint_violation` responses were TypeScript-only extensions. `docs/features/api-contract.md` + now states them as contract, with TypeScript's wire names unchanged. Two corpora hold the ports + to it: + - a new shared corpus, `fixtures/list-query-conformance/`: 95 parse cases, each a query string + in and either a filter tree in neutral values or the exact 400 body out, run with no server + and no database; + - a 20-scenario `list-query/` sub-corpus of `api-contract-conformance/`, over a 60-row seed, in + the generated lane. + + TypeScript passes both. The other ports take them on in their 1.3.0 REST-standard work. The + decision is [ADR-0068](spec/decisions/ADR-0068-list-query-cross-port-contract.md). A + scenario can now send a body that is not JSON with `rawBody`. +- **runtime-ts: one list-query parse for every mount.** `parseListQuery` (exported from + `@metaobjectsdev/runtime-ts`; it does not depend on Drizzle) reads a list request into a + port-neutral `ListQuery`, and each mount compiles that for its own query library. The Drizzle + and Hono mounts and the `ObjectManager` Fastify mount all use it. The `ObjectManager` mount + (`@metaobjectsdev/runtime-ts/fastify`) takes two new options: + - `filterAllowlist`: it then serves `filter[...]`, `filter[or]` / `filter[and]` and `?search` + and refuses what the Drizzle mount refuses, with the same bodies; + - `pagination`: the `api.pagination` page size. + + With no sort, the `ObjectManager` mount now orders by the primary key. The `ObjectManager` + `Filter` gains `$or` and a case-insensitive `$ilike`, and the class gains `keyFields()` and + `fieldNames()`. +- **codegen-ts: the filter and sort allowlists are available as data.** + `filterAllowlistRules(entity)` and `sortAllowlistRules(entity)` return the rules that + `FilterAllowlist` / `SortAllowlist` are printed from. The generated files are + byte-identical. + +- **Fixed: the filter nesting cap could not be reached.** `qs`'s default depth of 5 kept the sixth + bracket pair as part of the key, so `filter[or][0][or][0][or][0][a][eq]=1` read as a field named + `[0][a][eq]` and answered `invalid_filter_field` instead of `filter.nesting_too_deep`. Every + TypeScript mount now parses with `parseListQueryString`, whose depth is sized to the cap. As part + of the same fix, a combinator branch that names no field (`filter[or][0]=x`) is now + `400 invalid_filter_value` with `field: "or"`; before, it was an unknown field named `0`. +- **Fixed: on SQLite, `like` through the `ObjectManager` was case-insensitive.** The Kysely and + Drizzle drivers sent SQLite's native LIKE, which folds ASCII case, against ADR-0049. They now + lower `like` to GLOB on SQLite, as the generated routes already did, and to a binary comparison + on MySQL. +- **Fixed: `?search` on an entity with an int-backed enum answered 500 on Postgres.** The search + included every filterable text field, and an int-backed (`@intValueMap`) enum is an integer + column, so Postgres refused the ILIKE. Search now covers only fields whose operator band + includes `like`. - **C#: a `@sequenceStart` whose migrations project lacks the design-time services line is a generation error.** When `dotnet meta gen` can see the context's `ModelSnapshot.cs` in another project and that project does not carry `[assembly: DesignTimeServicesReference]`, the next `dotnet ef migrations add` diff --git a/agent-context/skills/metaobjects-audit/references/calibration.md b/agent-context/skills/metaobjects-audit/references/calibration.md index 8642c4e397..70ab55926b 100644 --- a/agent-context/skills/metaobjects-audit/references/calibration.md +++ b/agent-context/skills/metaobjects-audit/references/calibration.md @@ -20,9 +20,11 @@ `invalid-op` / `in`-over-cap 400s) is **generated in every port** (Java `SpringControllerGenerator`, C# `RoutesGenerator`, Python `router_generator`, Kotlin `KotlinSpringControllerGenerator`, TS) — gated by the api-contract corpus in BOTH lanes. **Flag hand-rolled filter parsing anywhere.** - Only the *richer* surface is genuinely **TS-only**: free-text `?search=`, the explicit - `filter[or][N]` / `filter[and][N]` nested boolean combinators (+ their nesting-depth cap), and - leading-wildcard gating — do NOT flag the absence of those in a non-TS port. + The *richer* list surface — free-text `?search=`, the explicit `filter[or][N]` / + `filter[and][N]` nested boolean combinators (+ their nesting-depth cap), and leading-wildcard + gating (ADR-0068) — passes in TypeScript and is **pending** in each other port until that port's + 1.3.0 REST-standard work lands. Do NOT flag the absence of those in a port that has not landed + them yet. - **Output-parser codegen** ships in **all five ports** — Java's `SpringOutputParserGenerator` *generates* the `Parser` (the Jackson `readValue` lives inside that generated file). A hand-rolled parser in a **non-generated** file where a **responding `template.prompt`** diff --git a/agent-context/skills/metaobjects-audit/references/capability-checklist.md b/agent-context/skills/metaobjects-audit/references/capability-checklist.md index 0a892f296c..bc71a99054 100644 --- a/agent-context/skills/metaobjects-audit/references/capability-checklist.md +++ b/agent-context/skills/metaobjects-audit/references/capability-checklist.md @@ -348,8 +348,10 @@ to nothing, and does not check that each claimed node complies). - **CALIBRATION — per-port codegen gaps:** the core `?filter[field][op]` filter grammar (all 9 operators + the generated allowlist + `invalid-field` / `invalid-op` / `in`-over-cap 400s) is **generated in all five ports** (api-contract corpus, both lanes) — **flag hand-rolled - filter parsing anywhere.** Only the richer surface (`?search=`, explicit - `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating) is TS-only. + filter parsing anywhere.** The richer list surface (`?search=`, explicit + `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating; ADR-0068) passes in + TypeScript and is pending in each other port until its 1.3.0 REST-standard work lands — do not + flag its absence in a port before then. Output-parser codegen also ships in **all five ports**, keyed on a **responding `template.prompt`** (`@responseRef`), never on a `template.output` (ADR-0052) — Java's `SpringOutputParserGenerator` *generates* the parser (the Jackson `readValue` lives inside diff --git a/agent-context/skills/metaobjects-audit/references/csharp.md b/agent-context/skills/metaobjects-audit/references/csharp.md index b2abf45c41..0a1d6a3fd3 100644 --- a/agent-context/skills/metaobjects-audit/references/csharp.md +++ b/agent-context/skills/metaobjects-audit/references/csharp.md @@ -158,9 +158,10 @@ version across these packages is an intra-port skew finding. generator (`Routes.cs`, Minimal API) generates the `?filter[field][op]=value` grammar (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`) via the runtime `FilterParser` + `EfCoreFilterDispatch`, validated against the generated filter allowlist (api-contract corpus, - both lanes). **Flag a hand-rolled filter parser as a finding.** Only the richer surface - (`?search=`, `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating) is - TS-only — do NOT flag its absence in C#. + both lanes). **Flag a hand-rolled filter parser as a finding.** The richer list surface + (`?search=`, `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating; ADR-0068) + passes in TypeScript and is pending in C# until the C# port's 1.3.0 REST-standard work lands — + do NOT flag its absence in C# until then. - **Output-parser codegen ships in C#.** `output-parser` / `extractor` / `render-helper` generators are available (list `OutputParserGenerator` in `codegen/Generators.cs`). Absence of wired output parsers where a **responding `template.prompt`** (`@responseRef`) exists IS a diff --git a/agent-context/skills/metaobjects-audit/references/java.md b/agent-context/skills/metaobjects-audit/references/java.md index 84e37604d3..b39b6d6862 100644 --- a/agent-context/skills/metaobjects-audit/references/java.md +++ b/agent-context/skills/metaobjects-audit/references/java.md @@ -157,8 +157,9 @@ versioning — **do not flag it** (only intra-port skew matters). `eq/ne/gt/gte/lt/lte/in/like/isNull`): it parses via the runtime `FilterParser`, validates against the generated `FilterAllowlist`, and 400s on unknown field / disallowed op / over-cap `in`-list (api-contract corpus, both lanes). **Flag a hand-rolled filter parser as a - finding.** Only the *richer* surface is TS-only — `?search=`, `filter[or][N]` / `filter[and][N]` - combinators, leading-wildcard gating — do NOT flag the absence of those in Java. + finding.** The *richer* list surface — `?search=`, `filter[or][N]` / `filter[and][N]` + combinators, leading-wildcard gating (ADR-0068) — passes in TypeScript and is pending in Java + until the Java port's 1.3.0 REST-standard work lands — do NOT flag its absence in Java until then. - **Repository interface is a hand-implemented stub.** `SpringRepositoryGenerator` emits `Repository.java` as a stub `interface`; the consumer hand-writes the implementation against OMDB (or any persistence layer). Hand-written repository diff --git a/agent-context/skills/metaobjects-audit/references/kotlin.md b/agent-context/skills/metaobjects-audit/references/kotlin.md index 8b94ba2482..f047af58ed 100644 --- a/agent-context/skills/metaobjects-audit/references/kotlin.md +++ b/agent-context/skills/metaobjects-audit/references/kotlin.md @@ -165,7 +165,8 @@ cross-port versioning — **do not flag it** (only intra-port skew matters). `KotlinSpringControllerGenerator` generates the `?filter[field][op]=value` grammar (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`) validated against the generated filter allowlist (api-contract corpus, both lanes). **Flag a hand-rolled filter parser as a finding.** Only the - richer surface (`?search=`, `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard - gating) is TS-only — do NOT flag its absence in Kotlin. + richer list surface (`?search=`, `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard + gating; ADR-0068) passes in TypeScript and is pending in Kotlin until the Kotlin port's 1.3.0 + REST-standard work lands — do NOT flag its absence in Kotlin until then. - **No JVM migrate goal.** Schema migration is Node-`meta`-owned for every port (ADR-0015). The Maven plugin has no migrate goal; `meta migrate` is correct. diff --git a/agent-context/skills/metaobjects-audit/references/python.md b/agent-context/skills/metaobjects-audit/references/python.md index d8f9baf9e9..1968fb15f3 100644 --- a/agent-context/skills/metaobjects-audit/references/python.md +++ b/agent-context/skills/metaobjects-audit/references/python.md @@ -159,9 +159,10 @@ another) matters. generator emits an `APIRouter` whose list route parses the `?filter[field][op]=value` grammar (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`) via the generated `filter_parser` module, validated against the generated filter allowlist (api-contract corpus, both lanes). **Flag a - hand-rolled filter parser as a finding.** Only the richer surface (`?search=`, - `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating) is TS-only — do NOT - flag its absence in Python. + hand-rolled filter parser as a finding.** The richer list surface (`?search=`, + `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating; ADR-0068) passes in + TypeScript and is pending in Python until the Python port's 1.3.0 REST-standard work lands — do + NOT flag its absence in Python until then. - **Partial relationship + flattened-object codegen.** Relationship navigation, non-`table` source kinds, and `field.object @storage: flattened` codegen are partially implemented in the Python port. Do NOT flag these gaps as adopter defects. diff --git a/agent-context/skills/metaobjects-audit/references/typescript.md b/agent-context/skills/metaobjects-audit/references/typescript.md index ce4485c972..12990f46cb 100644 --- a/agent-context/skills/metaobjects-audit/references/typescript.md +++ b/agent-context/skills/metaobjects-audit/references/typescript.md @@ -211,7 +211,7 @@ via `metamodelVersion` (see the Phase 0 cross-language consistency item). TypeScript is the reference implementation — it ships the full feature set: -- Filter-operator codegen: **complete** — the core `?filter[field][op]` grammar (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`, `FilterAllowlist`) generates in every port; TS additionally ships the richer surface (`?search=`, `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating). +- Filter-operator codegen: **complete** — the core `?filter[field][op]` grammar (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`, `FilterAllowlist`) generates in every port; the richer list surface (`?search=`, `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating; ADR-0068) passes in TypeScript; each other port is pending until its 1.3.0 REST-standard work lands. - Output-parser codegen: **complete** (`outputParser()` generator; `parse*`/`safeParse*`/`extract*` emitted as `.response.ts` per **responding `template.prompt`** — one carrying `@responseRef`; ADR-0052). - ObjectManager: **complete** (`@metaobjectsdev/runtime-ts`; `kyselyDriver` / `inMemoryDriver`). - Schema migrate / `meta verify --db`: **complete** (TS owns the shared migrate engine — ADR-0015). diff --git a/agent-context/skills/metaobjects-codegen/references/typescript-mysql.md b/agent-context/skills/metaobjects-codegen/references/typescript-mysql.md index 3e40002a0b..ec7c7b3762 100644 --- a/agent-context/skills/metaobjects-codegen/references/typescript-mysql.md +++ b/agent-context/skills/metaobjects-codegen/references/typescript-mysql.md @@ -123,7 +123,8 @@ emitted too, and a measure with `@default` is a `COALESCE` whose column MySQL re - The generated `deleteById` checks that the row exists before deleting it. - **`like` is case-sensitive**, as the API contract requires (ADR-0049). MySQL's default collation is case-insensitive, so the generated routes compare with - `COLLATE utf8mb4_bin`. The TypeScript-only `?search` stays case-insensitive. + `COLLATE utf8mb4_bin`. `?search` stays case-insensitive, as the list contract states + ([api-contract.md](../features/api-contract.md)). - **Timestamps use Drizzle's `date` mode.** A `DATETIME` rejects the ISO wire form (`2026-05-28T20:26:40.002Z` is `ERROR 1292`). The generated Zod schema coerces the ISO string to a `Date`, Drizzle stores the UTC wall clock, and the JSON response carries ISO with `Z`. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index d564c614ea..7d8211268b 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -1,6 +1,6 @@ # Conformance coverage -The MetaObjects standard ships **43 shared conformance corpora** under +The MetaObjects standard ships **45 shared conformance corpora** under [`fixtures/`](../fixtures/). Every port runs every corpus that is *applicable to it* and asserts the same expected behaviour against the same fixtures. **This page is the inverse index**: fixture → feature doc + per-port pass status, and it is the @@ -30,13 +30,13 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | -| [`fixtures/render-conformance/`](../fixtures/render-conformance/) | 18 | ✓ | ✓ | inherits via Java | ✓ | ✓ | +| [`fixtures/render-conformance/`](../fixtures/render-conformance/) | 21 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/jinja-render-conformance/`](../fixtures/jinja-render-conformance/) (ADR-0061 — Jinja bodies render the same in jinja2 and nunjucks) | 15 | ✓ (nunjucks) | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | refuses, via Java | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | ✓ (jinja2) | | [`fixtures/jinja-verify-conformance/`](../fixtures/jinja-verify-conformance/) (ADR-0061 — the payload check over a Jinja body) | 31 | ✓ | refuses Jinja | refuses, via Java | refuses Jinja | ✓ | | [`fixtures/extract-conformance/`](../fixtures/extract-conformance/) | 58 | ✓ | ✓ | inherits the shared JVM engine | ✓ | ✓ | | [`fixtures/output-prompt-conformance/`](../fixtures/output-prompt-conformance/) | 17 | ✓ | ✓ | ✓ | ✓ | ✓ | | [`fixtures/persistence-conformance/`](../fixtures/persistence-conformance/) | 67 (55 query + 12 migration) | all 67; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` also on MySQL (a scenario's `engines:` key is exact) | 55 query (migrations TS-only, ADR-0015); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (via Exposed); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query; the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (pg8000); the `report-*` and `engines:` scenarios also on SQLite (`sqlite3`) and MySQL (PyMySQL) | -| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 141 (34 core + 14 tph + 9 m2m + 6 jsonb + 2 write-through + 4 secret-fields + 2 enum-default + 12 projection + 37 report + 11 decimal + 2 duration + 8 api-settings) | ✓ (Fastify reference + generated lane); `report/`, `decimal/` and `duration/` also on SQLite, MySQL and D1 | ✓ (embedded HTTP + JDBC); `report/`, `decimal/` and `duration/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | +| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 161 (34 core + 14 tph + 9 m2m + 6 jsonb + 2 write-through + 4 secret-fields + 2 enum-default + 12 projection + 37 report + 11 decimal + 2 duration + 8 api-settings + 20 list-query) | ✓ (Fastify reference + generated lane); `report/`, `decimal/` and `duration/` also on SQLite, MySQL and D1; `list-query/` is TypeScript-only until each port's 1.3.0 REST-standard work | ✓ (embedded HTTP + JDBC); `report/`, `decimal/` and `duration/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | | [`fixtures/decimal-wire/`](../fixtures/decimal-wire/) | 1 vector file (format, parse, filter operand, 15-digit read) | ✓ (`runtime-ts` and the generated helper) | ✓ (`CanonicalDecimal`) | ✓ (the generated wire file) | ✓ (`DecimalWire`) | ✓ (`decimal_wire`) | | [`fixtures/duration-wire/`](../fixtures/duration-wire/) | 1 vector file: the `wire` vectors (parse, precision, refused) every port passes, and the `codecs` groups (Postgres text read and write, stored microseconds) each port passes only for the codecs it has | ✓ (`metadata` / `runtime-ts` and the generated helper) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/validation-conformance/`](../fixtures/validation-conformance/) | 42 cases + 43 cross-field cases (`cross-field-cases.json`, generated record model only) | ✓ (generated Zod + run-time `runValidators`) | ✓ | ✓ | ✓ | ✓ (generated Pydantic + run-time `run_validators`) | @@ -52,6 +52,8 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/dependency-conformance/`](../fixtures/dependency-conformance/) | 47 cases (36 resolution, 7 of them with a ledger arm, + 11 check) + 32 transport cases | ✓ (reference implementation; all four arms) | ✓ (resolution arm, all 36, ledger included; check arm, all 11) | inherits via Java | ✓ (resolution arm, all 36, ledger included; check arm, all 11, as `verify --deps`) | ✓ (resolution arm, all 36 identically, ledger included; check arm, all 11, as `deps check` and `verify --deps`; the transport arm is Node-only) | | [`fixtures/shared-model-conformance/`](../fixtures/shared-model-conformance/) | 15 cases (9 publish + 6 refusal) | ✓ (reference implementation) | ✓ (all 15; `SharedModelConformanceTest`) | inherits via Java (`KotlinSharedModelGeneratorTest` pins the generator) | ✓ (all 15; `SharedModelConformanceTests`) | ✓ (all 15; `test_shared_model_conformance.py`) | | [`fixtures/agent-context-conformance/`](../fixtures/agent-context-conformance/) | 5 | ✓ (the emitter is TS-owned) | — | — | — | — | +| [`fixtures/list-query-conformance/`](../fixtures/list-query-conformance/) (how a list route reads its query string: filter tree, search, sort, page, or the named 400) | 95 cases | ✓ (reference; the source of the expected answers) | planned (R-JV) | planned (R-KT) | planned (R-CS) | planned (R-PY) | +| [`fixtures/docs-page-conformance/`](../fixtures/docs-page-conformance/) (the requirements pages and the model-only schema page: each page's data and bytes) | 4 cases | ✓ (reference; the source of the expected bytes) | planned | planned (through Java) | planned | planned | | [`fixtures/metamodel-docs/`](../fixtures/metamodel-docs/) | 1 | ✓ (docs emit is TS-owned) | — | — | — | — | | [`fixtures/fmt-conformance/`](../fixtures/fmt-conformance/) (#304 — `meta fmt`) | 13 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/field-lint-conformance/`](../fixtures/field-lint-conformance/) (the `verify` field authoring lint) | 15 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | @@ -123,7 +125,8 @@ the contracts and the conformance kits that hold every port to them. `requirement-check-conformance/` (the requirement gate every port's `verify` runs; a drift gate is core, and it is not ejectable in any port), `rules-check-conformance/` (the business-rules gate every port's `verify` runs, ADR-0066) and - `codegen-skip-conformance/` (ADR-0064: which changes make `gen` render, and what a local `verify --codegen` may answer from the stored key), core for the same reason. + `codegen-skip-conformance/` (ADR-0064: which changes make `gen` render, and what a local `verify --codegen` may answer from the stored key), core for the same reason, and + `list-query-conformance/` (how a list route reads its query string: the REST wire contract, which is core like the reference-server lane below). A red cell here is a MetaObjects bug. - **Generator quality checks — a supported helper's tests, not a core promise.** The generated lane of `api-contract-conformance/`, `generator-registry-conformance/` (stable generator names), @@ -466,14 +469,15 @@ on a reporting measure, etc.) and 7 `error-yaml-*` fixtures that pin the YAML 1.1 coercion guards (bool / null / hex in string contexts; numeric in enum contexts; reserved-as-attr). -### `fixtures/render-conformance/` (18) +### `fixtures/render-conformance/` (21) -All 18 fixtures → [features/templates-and-payloads.md](features/templates-and-payloads.md) +All 21 fixtures → [features/templates-and-payloads.md](features/templates-and-payloads.md) (render engine output section). 5 are end-to-end shape and escape examples (prompt / email / -spreadsheet / CSV-injection escape / CSV numeric-literal exemption); 13 pin Mustache-engine +spreadsheet / CSV-injection escape / CSV numeric-literal exemption); 16 pin Mustache-engine semantics — dotted-path lookup, parent-context fallthrough, falsy/empty-array section behavior, inverted sections, nested partials, a comment tag beside a partial, standalone-tag whitespace -stripping, raw-HTML bypass, trailing-newline preservation, unicode multibyte handling, the derived +stripping (including two standalone tags in a row, a standalone tag at the end of the file and an +indented standalone tag, which shared docs templates rely on), raw-HTML bypass, trailing-newline preservation, unicode multibyte handling, the derived `has` accessor, and the `-last` list-separator accessor. ### `fixtures/jinja-render-conformance/` (15) and `fixtures/jinja-verify-conformance/` (31) @@ -513,9 +517,9 @@ REAL, a MySQL `DECIMAL` keeps its scale, a MySQL `DATETIME` is the UTC wall cloc `report-relative-date` carries a per-engine seed (`seed-data-engine`). `op: relate` and the write ops stay Postgres-only. See [features/reporting.md](features/reporting.md#what-the-corpus-gates). -### `fixtures/api-contract-conformance/` (141) +### `fixtures/api-contract-conformance/` (161) -All 141 scenarios → [features/api-contract.md](features/api-contract.md) (cross-port +All 161 scenarios → [features/api-contract.md](features/api-contract.md) (cross-port REST API URL grammar + JSON wire format). Verifies every backend's emitted CRUD routes answer identically over HTTP — list / get / create / patch+put / delete, plus pagination (`limit`/`offset`), sort (`sort=field:dir`), the `withCount=1` @@ -528,7 +532,7 @@ and 2 error shapes (`invalid_filter_field` / `invalid_filter_op`) under the URL grammar `?filter[][]=` (FR-009). On top of the 34 core scenarios (among them the write-input rules: server-owned keys dropped, an undeclared key refused under the default `api.unknownFields: reject`, and every validation issue listed) -the corpus carries eleven sub-corpora — `tph/` (14, single-table +the corpus carries twelve sub-corpora — `tph/` (14, single-table inheritance; a subtype decimal filters and refuses extra digits, and the input rules hold over the whole hierarchy), `m2m/` (9 — 3 plain, 5 gating TPH x M:N together, the combination each corpus alone could not reach, and 1 pinning the collection-URL spelling), @@ -542,7 +546,7 @@ canonical string, read exactly, filtered exactly and refused past its declared d in a calendar or clock spelling, and filtered and sorted as a span on every engine), `api-settings/` (8, the project's `api` block: `api.pagination`'s default page, `limit_too_large` cap and refused negative `limit`, an empty page for `limit=0`, and -`api.unknownFields: drop`) and `report/` (37, +`api.unknownFields: drop`), `list-query/` (20, the REST standard's list handling against a real store: search ignores case and `like` does not, `filter[or]`/`filter[and]`, the nesting cap, bare fields, a leading `%`, value formats, paging past 50, and the `invalid_json`, `invalid_id`, `pagination.invalid_value` and `constraint_violation` refusals; generated lane, TypeScript only until each port's 1.3.0 REST-standard work) and `report/` (37, FR-044: a view-backed `object.report` is listed, filtered, sorted and paged on its derived fields, answers `POST` with 405 and mounts no `/{id}`; a `@spine` report keeps a row with no facts, and a measure with `@default` filters and sorts as its default). All 5 ports — TS, Java, @@ -754,6 +758,36 @@ a port that disagrees with one is wrong. The case list, and what each pins, is i (Kotlin inherits it, through the shared Maven goal) and `server/csharp/MetaObjects.Conformance.Tests/RequirementCheckConformanceTests.cs`. +### `fixtures/list-query-conformance/` (95 cases) + +All 95 cases → [features/api-contract.md](features/api-contract.md) ("The list query: search, +combinators and refusals", and the bad-request responses). Each case is a raw query string, and +what it pins is the answer a list route gives before any store is reached: the parsed query +(a filter tree in neutral values, the search term and the fields it covers, the sort and the +page) or the exact 400 body. With several faults in one query, it also pins which is reported +first. The allowlist is not in the fixture: a runner derives it from `meta.json` the way its +generator does, so a port that derives a different allowlist fails here. What a parsed query +matches in a store is the `list-query/` sub-corpus of `api-contract-conformance/`. + +**Held to it:** `server/typescript/packages/integration-tests/test/list-query-conformance.test.ts` +(the source of the expected answers). **Conformance status:** TypeScript passes; C#, Java, +Kotlin, Python and Rust are pending until their 1.3.0 REST-standard work lands, and each port's +change flips its own entry. The decision is +[ADR-0068](../spec/decisions/ADR-0068-list-query-cross-port-contract.md). + +### `fixtures/docs-page-conformance/` (4 cases) + +All 4 cases → [features/requirements.md](features/requirements.md) (the documentation +surfaces) and [features/templates-and-payloads.md](features/templates-and-payloads.md) (the +shared templates). Each case is a model under `input/` and, under `expected/`, every page it +yields (`requirements.md`, `requirements.toon`, `agent/requirements.md`, the model-only +`agent/schema.md`) plus the data each page's shared template is fed. The TypeScript +builders are the source of the expected bytes. The corpus README writes down what a +non-TypeScript schema page contains and what it leaves out. + +**Held to it:** `server/typescript/packages/cli/test/docs-page-conformance.test.ts`. The +other ports' page generators are planned. + ### `fixtures/requirement-test-identity-conformance/` (27 cases) All 27 cases → [features/requirements.md](features/requirements.md) ("Generated @@ -826,9 +860,9 @@ JSON and verify payload feeds it unchanged. ## Orphaned fixtures (tested but not yet documented) The fixtures in the nine corpora mapped above (metamodel 578 + yaml 19 + verify 45 -+ render 18 + persistence 67 + api-contract 141 + source-resolution 28 + scope 10 + ++ render 21 + persistence 67 + api-contract 161 + source-resolution 28 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `rules-check-conformance`, `shared-model-conformance`, the -`cube-model` corpus and `explorer-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining +`cube-model` corpus, `explorer-conformance` and `list-query-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining corpora in the totals table gate tooling contracts (registry manifests, provider composition, agent context, docs emit) rather than user-facing metamodel behaviour, so they have no feature-doc row. diff --git a/docs/features/api-contract.md b/docs/features/api-contract.md index 5a415be800..dae71b81eb 100644 --- a/docs/features/api-contract.md +++ b/docs/features/api-contract.md @@ -141,8 +141,8 @@ Filters use a **bracketed qs** shape: `filter[][]=`. A bare value (`filter[]=`) is sugar for `eq`. Multiple filters AND together. -> **`filter[or]` / `filter[and]` nesting is a TS-only extension**, not part of -> the cross-port contract — see "TS-only filter extensions" below. +> **`filter[or]` / `filter[and]` nesting, `?search` and the refusals that go with them are part +> of the contract** since 1.3.0 — see "The list query: search, combinators and refusals" below. | Operator | Strings | Numbers / Dates | Booleans | |---|---|---|---| @@ -163,68 +163,77 @@ single character) are the only wildcards, there is no `%`-wrapping and no case folding — identically on every port and every engine. Engines whose native LIKE is not case-sensitive are lowered around, not deferred to: on SQLite/D1 (whose built-in LIKE folds ASCII case) the TS runtime lowers -`like` to GLOB with an exactly-translated pattern. Case-insensitive +`like` to GLOB with an exactly-translated pattern; on MySQL, whose LIKE follows the column's +collation, it compares the binary value. Case-insensitive matching is deliberately NOT in the operator vocabulary (FR-009 §7 / ADR-0036 reserve `ilike` as a future additive operator, gated on real consumer demand); until then, normalize case in the data or the pattern — -or use the TS-only `?search` extension, which IS case-insensitive. +or use `?search`, which IS case-insensitive. -### TS-only filter extensions (not part of the cross-port contract) +### The list query: search, combinators and refusals -The TypeScript runtime parser ships seven filter behaviors beyond the nine -operators. They are **NOT part of the cross-port REST contract** — the other -ports (Java, Kotlin, Python, C#) do not implement them, and a relying adopter -must not assume them on a non-TS backend. They are deliberately deferred until -real consumer demand (none touch the metamodel vocabulary, so any of them can be -added cross-port later as a purely additive, non-breaking change): +Until 1.3.0 these were TypeScript-only extensions. **They are now part of the contract**, with +TypeScript's wire names unchanged. Two corpora hold every port to them: -| Extension | What it does | +- [`fixtures/list-query-conformance/`](../../fixtures/list-query-conformance/) — the parse. + A query string goes in, and a filter tree or the named 400 body comes out, with no server + and no database. It also pins the order faults are reported in. +- [`fixtures/api-contract-conformance/list-query/`](../../fixtures/api-contract-conformance/list-query/) + — what a parsed query matches in a real store, over HTTP, in the generated lane: search + ignores case and `like` does not, plus or/and, the nesting cap, bare fields, paging past 50, + and the body, id and constraint refusals below. + +The decision is recorded in [ADR-0068](../../spec/decisions/ADR-0068-list-query-cross-port-contract.md). + +**Conformance status:** TypeScript passes both corpora; C#, Java, Kotlin, Python and Rust are pending +until their 1.3.0 REST-standard work lands. Each port's change flips its own entry, and its +runner holds it to them from then on; [`docs/CONFORMANCE.md`](../CONFORMANCE.md) says which ports +run them today. + +| Behaviour | What it does | |---|---| -| `?search=` | ORs a case-INSENSITIVE substring match (`%term%`) across the entity's `@filterable` string fields — deliberately looser than the case-sensitive `like` operator (it is a human search box; ILIKE on Postgres, native LIKE on SQLite) | -| `filter[or][N]` / `filter[and][N]` | boolean combinators (recursive nesting) | -| leading-wildcard gating | a `like` pattern starting with `%` → HTTP 400 (`filter.leading_wildcard_disallowed`) | -| filter nesting-depth cap | rejects deeply-nested `or`/`and` (tied to the combinators) | +| `?search=` | ORs a case-INSENSITIVE substring match (`%term%`) across the entity's `@filterable` text fields whose operator band includes `like`. That is plain strings and string-backed enums; it excludes a uuid or other formatted string and an int-backed enum, whose columns have no text match. It is deliberately looser than the case-sensitive `like` operator, because it is a human search box: ILIKE on Postgres, LIKE on SQLite, `LOWER() LIKE LOWER()` on MySQL. An empty `search` is no search. With `withCount`, the total counts the rows the search and filter match | +| `filter[or][N]` / `filter[and][N]` | Boolean combinators, nesting recursively. Branches are taken in index order, not the order sent. A combinator with one branch is that branch. Conditions side by side (`filter[a][eq]=1&filter[or][0]…`) AND together. A branch that names no field (`filter[or][0]=x`) or an `or` that is not a list → `400 { "error": "invalid_filter_value", "field": "or" }` | +| filter nesting-depth cap | Five levels of `or`/`and` are served; the sixth → `400 { "error": "filter.nesting_too_deep", "limit": 5 }`. A query-string parser has to be able to reach the cap: `qs`'s default depth of 5 keeps the sixth bracket pair as part of the key, so before 1.3.0 an over-deep TypeScript filter answered an unknown field named `[0][a][eq]` | +| leading-wildcard gating | A `like` pattern starting with `%` → `400 { "error": "filter.leading_wildcard_disallowed", "field": "" }` | | bare field parameter | `?priority=low` where `priority` is in the allowlist → HTTP 400 `{ "error": "filter.bare_field", "field": "priority", "expected": "filter[priority][eq]=low" }` instead of silently returning every row. A bare parameter named after a field of the entity that is NOT filterable (a column of the table or view the mount reads, off the allowlist) → HTTP 400 `{ "error": "filter.bare_field", "field": "kind", "filterable": false, "expected": "a filterable field — \"kind\" is not @filterable", "allowed": [] }` — declare `@filterable: true` on the field to filter by it. Any other unknown parameter (a cache-buster, a tracking tag) is still ignored, and the reserved list parameters (`filter`, `sort`, `limit`, `offset`, `search`, `withCount`) are never claimed | -| filter-value format check | a comparison value (`eq`/`ne`/`gt`/`gte`/`lt`/`lte`, and every element of an `in` list) that cannot be the field's type → HTTP 400 `{ "error": "invalid_filter_value", "field": "publishedOn", "op": "gte", "expected": "date (YYYY-MM-DD)" }` instead of reaching SQL, where SQLite compared the text and silently returned `[]` and Postgres failed the cast. Checked per field: `field.date` (a real calendar day), `field.time` (`HH:MM[:SS[.fff]]`), `field.timestamp` (a date, optionally with a time and a `Z`/offset), `field.uuid` (`8-4-4-4-12` hex), `field.enum` (a declared member — the response adds `allowed`), numbers (an empty value is not `0`; on `field.int` / `field.long` / `field.currency` a fractional value such as `40.5` → `"expected": "integer (a whole number)"`) and booleans. A timestamp value whose offset arrived as a space — `…T00:00:00+00:00` sent unencoded, where `+` decodes to a space — adds `"hint"` saying to URL-encode the `+` as `%2B` or to use `Z`. A comparison value on a `field.timestamp` that is not `@localTime` is compared as an instant in the stored UTC spelling: a zoned value at its instant, a zoneless one read as UTC and a date alone as midnight UTC — the same rule the generated insert/update schemas store such a field by (`"2026-10-06"` is stored as `2026-10-06T00:00:00Z`: the canonical wire spelling, no fraction when it is zero; a value already spelled `YYYY-MM-DDTHH:MM:SS[.f]Z` is kept byte-for-byte), because SQLite and D1 compare the text; an `@localTime` value is kept as sent on both paths. The generated `FilterAllowlist` carries the `format` / `enumValues` / `instant` / `integer` this needs; an allowlist generated before them still has a temporal value checked against all three temporal formats and an enum checked against the Drizzle column's own members. The envelope is the cross-port one; what is TS-only is refusing a malformed comparison value — the other ports pass it through to the database and only the `isNull` value is corpus-gated | +| filter-value format check | a comparison value (`eq`/`ne`/`gt`/`gte`/`lt`/`lte`, and every element of an `in` list) that cannot be the field's type → HTTP 400 `{ "error": "invalid_filter_value", "field": "publishedOn", "op": "gte", "expected": "date (YYYY-MM-DD)" }` instead of reaching SQL, where SQLite compared the text and silently returned `[]` and Postgres failed the cast. Checked per field: `field.date` (a real calendar day), `field.time` (`HH:MM[:SS[.fff]]`), `field.timestamp` (a date, optionally with a time and a `Z`/offset), `field.uuid` (`8-4-4-4-12` hex), `field.enum` (a declared member — the response adds `allowed`), numbers (an empty value is not `0`; on `field.int` / `field.long` / `field.currency` a fractional value such as `40.5` → `"expected": "integer (a whole number)"`) and booleans. A timestamp value whose offset arrived as a space — `…T00:00:00+00:00` sent unencoded, where `+` decodes to a space — adds `"hint"` saying to URL-encode the `+` as `%2B` or to use `Z`. A comparison value on a `field.timestamp` that is not `@localTime` is compared as an instant in the stored UTC spelling: a zoned value at its instant, a zoneless one read as UTC and a date alone as midnight UTC — the same rule the generated insert/update schemas store such a field by (`"2026-10-06"` is stored as `2026-10-06T00:00:00Z`: the canonical wire spelling, no fraction when it is zero; a value already spelled `YYYY-MM-DDTHH:MM:SS[.f]Z` is kept byte-for-byte), because SQLite and D1 compare the text; an `@localTime` value is kept as sent on both paths. The generated `FilterAllowlist` carries the `format` / `enumValues` / `instant` / `integer` this needs; an allowlist generated before them still has a temporal value checked against all three temporal formats and an enum checked against the Drizzle column's own members. Before 1.3.0 only TypeScript refused a malformed comparison value; the other ports passed it through to the database | **Leading-wildcard gating is fail-closed with no metadata opt-in.** The -generated `FilterAllowlist` hardcodes `leadingWildcard: false` on every -field — an unanchored LIKE (`"%@example.com"`) cannot use a btree index, so the -generated TS routes reject it by default. The runtime honors -`leadingWildcard: true` per field, but codegen never emits it: to opt a field -in, hand-edit that field's entry in the generated allowlist (hand edits inside -generated files survive regeneration via the three-way merge). There is -deliberately no `@`-attribute for this (ADR-0037/ADR-0023: the gate is a -TS-only generated-code behavior, not cross-port metamodel semantics — the other -ports accept leading wildcards, which is exactly why it is listed here as a -TS-only extension). +generated filter allowlist refuses a leading `%` on every field, because an unanchored LIKE +(`"%@example.com"`) cannot use a btree index. The runtime honours a per-field opt-in +(`leadingWildcard: true` in TypeScript's `FilterAllowlist`), but codegen never emits +it. To opt a field in, hand-edit that field's entry in the generated allowlist; hand edits +inside generated files survive regeneration through the three-way merge. There is +deliberately no `@`-attribute for this (ADR-0037/ADR-0023): it is a property of the generated +route, not metamodel semantics. The **`in`-list size cap** (reject an `in` list longer than 100 → HTTP 400) is a safety limit, not a feature, and every port enforces it: TypeScript -(`DEFAULT_MAX_IN_LIST` in the `runtime-ts` filter parser), Python (`MAX_IN_LIST`), +(`DEFAULT_MAX_IN_LIST` in the `runtime-ts` list parser), Python (`MAX_IN_LIST`), Java (`FilterParser.MAX_IN_LIST`), C# (`FilterParser.MaxInList`) and Kotlin (a generated file-private constant that matches the TypeScript default). -### TS-only error responses (not part of the cross-port contract) +### Error responses for a bad request or a failed write -The TypeScript mount helpers (`@metaobjectsdev/runtime-ts/drizzle-fastify`, -`/fastify` and `/hono`) pin five responses the contract leaves open — HTTP 5xx is -implementation-defined below, and no corpus scenario sends a malformed body, a write the database rejects, a -malformed page bound to an entity, or a value only the generated schema's format check refuses. All five use the contract's -`{ "error": "" }` envelope, and all five are scoped to the -routes the helpers mount: an adopter's own routes, and a Fastify `setErrorHandler` -or Hono `onError` the adopter installed, answer exactly as they did before. +Before 1.3.0 these were TypeScript-only. They are now part of the contract, and +`api-contract-conformance/list-query/` sends each one (`invalid-json`, `invalid-id`, +`pagination-invalid-value`, `constraint-violation`). All of them use the contract's +`{ "error": "" }` envelope. In TypeScript they come from the mount helpers +(`@metaobjectsdev/runtime-ts/drizzle-fastify`, `/fastify` and `/hono`) and apply only to the +routes those helpers mount: an adopter's own routes, and a Fastify `setErrorHandler` or Hono +`onError` the adopter installed, answer exactly as they did before. | Response | When | |---|---| | malformed JSON body | a `POST`/`PATCH`/`PUT` body that does not parse as JSON (an empty body sent as `application/json` included) → HTTP 400 `{ "error": "invalid_json" }`. An EMPTY body on a method that takes none (`GET`, `DELETE`, `HEAD`) is accepted even when the request declares `content-type: application/json`, as many clients do on every request; a non-empty `DELETE` body is still parsed. Before, Fastify answered its own `{ "statusCode": 400, "code": "FST_ERR_CTP_INVALID_JSON_BODY", … }` and Hono a Zod `validation` error about a missing object | -| malformed id | a `:id` the key column cannot hold (a malformed uuid on a Postgres uuid key, a non-numeric id on an integer key, or numeric text that is not the canonical spelling of a number, such as `0x1` or `1e0`) → HTTP 400 `{ "error": "invalid_id" }` on GET, PATCH and DELETE. A malformed uuid in a POST or PATCH body's foreign key → HTTP 400 `{ "error": "validation" }`, from the insert/update schema's `8-4-4-4-12` hex check. Postgres used to answer 500 for both. The check is TS-only. The TypeScript, Java and Python ObjectManagers apply the numeric rule to a key passed as text to `findById`, `update`, `delete` and `load`: an optional `-` and ASCII digits with no leading zero (a decimal key may add `.` and digits), and no exponent, hex, plus sign, whitespace or negative zero, so the caller passes the decimal spelling. A string or uuid key is untouched | -| malformed page bound | a `?limit=` or `?offset=` that is not a non-negative integer (`abc`, `-5`, `1.5`, an empty value) → HTTP 400 `{ "error": "pagination.invalid_value", "param": "limit", "value": "abc", "expected": "a non-negative integer (0 or more)" }`. Before, a non-numeric bound was dropped (every row came back) and a negative or fractional one reached SQL. An entity or a projection with declared columns has no page-size maximum unless the project sets `api.pagination` (see "A page size is a project setting" below, which answers `limit_too_large`); an opaque view (no declared columns, served by raw SQL) pages to at most 1000 rows, so there a `limit` above 1000 is refused too, with `"expected": "an integer from 0 to 1000"` (it used to be clamped silently). The same answer comes from the Drizzle mounts and the ObjectManager Fastify mount. The corpus sends a malformed bound only to a report (`report/bad-page-bound`), where every port answers this same envelope and also refuses `limit=0`; on an entity or a projection the other ports answer it as their framework does | +| malformed id | a `:id` the key column cannot hold (a malformed uuid on a Postgres uuid key, a non-numeric id on an integer key, or numeric text that is not the canonical spelling of a number, such as `0x1` or `1e0`) → HTTP 400 `{ "error": "invalid_id" }` on GET, PATCH and DELETE. A malformed uuid in a POST or PATCH body's foreign key → HTTP 400 `{ "error": "validation" }`, from the insert/update schema's `8-4-4-4-12` hex check. Postgres used to answer 500 for both. The TypeScript, Java and Python ObjectManagers apply the numeric rule to a key passed as text to `findById`, `update`, `delete` and `load`: an optional `-` and ASCII digits with no leading zero (a decimal key may add `.` and digits), and no exponent, hex, plus sign, whitespace or negative zero, so the caller passes the decimal spelling. A string or uuid key is untouched | +| malformed page bound | a `?limit=` or `?offset=` that is not a non-negative integer (`abc`, `-5`, `1.5`, an empty value) → HTTP 400 `{ "error": "pagination.invalid_value", "param": "limit", "value": "abc", "expected": "a non-negative integer (0 or more)" }`. Before, a non-numeric bound was dropped (every row came back) and a negative or fractional one reached SQL. An entity or a projection with declared columns has no page-size maximum unless the project sets `api.pagination` (see "A page size is a project setting" below, which answers `limit_too_large`); an opaque view (no declared columns, served by raw SQL) pages to at most 1000 rows, so there a `limit` above 1000 is refused too, with `"expected": "an integer from 0 to 1000"` (it used to be clamped silently). The same answer comes from the Drizzle mounts and the ObjectManager Fastify mount. The corpus pins it on an entity (`list-query/pagination-invalid-value`) and on a report (`report/bad-page-bound`, where `limit=0` is refused too) | | database constraint violation | a write the database itself rejects → `{ "error": "constraint_violation", "constraint": "" }`, HTTP **409** for `unique` and `foreign_key` (a conflict with another row) and HTTP **400** for `check` and `not_null` (the request's own value), per the status rule under "Error response". The body names the constraint KIND only — never the SQL, the table or the bound values. A `CHECK` the model derives (an enum, a `validator.numeric`/`length`/`regex` range) is normally refused earlier by the route's own validation, as the corpus's `{ "error": "validation" }` 400; this row is the database's backstop | -| schema validation failure | a body that fails the insert/update schema → HTTP 400 `{ "error": "validation", "issues": [...] }`, each issue as Zod reports it **minus `pattern`**: Zod 4 attaches a failed `.regex()` check's source there, which for a generated `field.date` / `field.time` / `field.timestamp` check is a ~300-character calendar regex (and an authored `validator.regex` pattern is the server's to keep). The generated temporal checks carry a short `message` naming the expected format instead (`"must be an ISO date (YYYY-MM-DD)"`) | -| unexpected server error | anything that is not a filter, validation, not-found or constraint answer — a query against a column the database no longer has, a driver failure → HTTP 500 `{ "error": "internal" }`, the code the cross-port reference servers already use. The body names no SQL, table, column or bound parameter; the full error goes to the server log (`console.error`). Before, Fastify's default handler echoed the driver message, which for Drizzle is the query text and its parameter values | +| schema validation failure | a body that fails the insert/update schema → HTTP 400 `{ "error": "validation", "issues": [...] }` (see "A validation error lists every issue" below). In TypeScript each issue is as Zod reports it **minus `pattern`**: Zod 4 attaches a failed `.regex()` check's source there, which for a generated `field.date` / `field.time` / `field.timestamp` check is a ~300-character calendar regex (and an authored `validator.regex` pattern is the server's to keep). The generated temporal checks carry a short `message` naming the expected format instead (`"must be an ISO date (YYYY-MM-DD)"`) | +| unexpected server error | anything that is not a filter, validation, not-found or constraint answer — a query against a column the database no longer has, a driver failure → HTTP 500 `{ "error": "internal" }`, the code the cross-port reference servers already use (the 5xx body is otherwise implementation-defined; see "Error response"). The body names no SQL, table, column or bound parameter; the full error goes to the server log (`console.error`). Before, Fastify's default handler echoed the driver message, which for Drizzle is the query text and its parameter values | -How each framework scopes it: on Fastify, the helpers pass a **route-level** +How each TypeScript framework scopes it: on Fastify, the helpers pass a **route-level** `errorHandler` in the options of each route they register (Fastify applies it to that route only). A deliberate 4xx raised on such a route — an auth `preHandler`'s 401, schema validation, 413, 415 — is rethrown to the enclosing scope's handler @@ -263,8 +272,8 @@ each handler they register instead; an `HTTPException` is rethrown to your sorts by its mapped integers. To sort by declared order, back the enum with an `@intValueMap` whose integers follow that order. - `limit=N` — page size. -- `offset=N` — page offset. Both are non-negative integers; the TS mounts refuse - anything else with a 400 (see "TS-only error responses"). +- `offset=N` — page offset. Both are non-negative integers, and anything else is refused + with `400 pagination.invalid_value` (see "Error responses for a bad request or a failed write"). - **A report is the exception: one cap in every port.** A served `object.report` list returns every row when `limit` is omitted, up to 10,000 (a generator option), and answers `400 { "error": "report_too_large", "maxRows": N }` for one row more, or for a `limit` above the cap. @@ -533,9 +542,9 @@ Non-2xx responses MUST return: - HTTP 400 — validation and filter/sort-parser errors. - HTTP 404 — `{ "error": "not_found" }`. -- HTTP 409 — a declared constraint conflicting with existing state (a uniqueness or referential violation); a constraint rejecting the request's own value — a `CHECK` or `NOT NULL` violation — stays a 400, because resending the same body can never succeed while a 409 can clear once the other row changes (the TS body is under "TS-only error responses"). +- HTTP 409 — a declared constraint conflicting with existing state (a uniqueness or referential violation); a constraint rejecting the request's own value — a `CHECK` or `NOT NULL` violation — stays a 400, because resending the same body can never succeed while a 409 can clear once the other row changes (the body is under "Error responses for a bad request or a failed write"). - HTTP 5xx — implementation-defined (the TS mount helpers answer - `{ "error": "internal" }` and nothing more — see "TS-only error responses"). + `{ "error": "internal" }` and nothing more — see "Error responses for a bad request or a failed write"). #### A validation error lists every issue @@ -563,7 +572,7 @@ one, in one shape in every port: know a code should treat it as `custom`. - `message` is the port's own wording and is not part of the contract. - A port may add keys to an issue (TypeScript keeps Zod's `minimum`, `maximum`, `origin` and so - on, minus `pattern`; see "TS-only error responses"), and a client must ignore keys it does not + on, minus `pattern`; see "Error responses for a bad request or a failed write"), and a client must ignore keys it does not know. Before 1.3.0 only TypeScript listed issues; the C#, Java, Kotlin and Python routes answered a @@ -914,9 +923,9 @@ async def delete_author(id: int) -> None: ``` The filter-parser implementation is the bulk of the work; the route -shapes themselves are trivial. The TS `parseFilterParams` (in -`@metaobjectsdev/runtime-ts/drizzle-fastify`) is the reference — port it -into your framework's idiomatic query-builder, gated by the generated +shapes themselves are trivial. The TS `parseListQuery` (in `@metaobjectsdev/runtime-ts`) is the +reference for the parse, and `fixtures/list-query-conformance/` pins its answers. Port it, then +compile the parsed query into your framework's idiomatic query-builder, gated by the generated `FilterAllowlist`. ## Future direction @@ -929,17 +938,10 @@ codegen status" above and "Verified by" below, and What's still genuinely open: -- The seven **TS-only filter extensions** (`?search=`, `filter[or]` / - `filter[and]` nesting, leading-wildcard gating, the nesting-depth cap, - the `in`-list size cap, the bare filterable-field 400, and the - filter-value format check) — see "TS-only filter extensions" above. - None touch the metamodel vocabulary, so any of them can be promoted - cross-port later as a purely additive, non-breaking change if real - consumer demand shows up. - The `error` code vocabulary is not yet a hard cross-port invariant - beyond `not_found` and the filter-parser error codes. + beyond `not_found`, the list-query codes and the bad-request codes above. -Neither item blocks adoption on any port today. +It does not block adoption on any port today. ## Verified by diff --git a/docs/features/codegen-data-shapes.md b/docs/features/codegen-data-shapes.md index 8841b258ff..b872de7bab 100644 --- a/docs/features/codegen-data-shapes.md +++ b/docs/features/codegen-data-shapes.md @@ -73,6 +73,14 @@ trivial and cross-port walkers don't have to re-derive the rules. file into your project; the project's `templates/` directory takes precedence over the framework defaults. Same for any partial under `templates/docs/`. +The requirements pages and the agent schema and requirements pages follow the same split: +`requirementsLedgerData`, `requirementsToonData`, `agentRequirementsPageData` and +`agentSchemaPageData` (exported from `@metaobjectsdev/codegen-ts`) return finished cells and +lines, and `templates/requirements/*.mustache` and `templates/agent/*.mustache` lay them out. +`fixtures/docs-page-conformance/` pins each page's data and bytes for the TypeScript builders +(the other ports' status is in [CONFORMANCE.md](../CONFORMANCE.md)), and its README states what the model-only schema page (`physical: false`, the page a port without +the expected schema writes) leaves out. + ### Neutral structural shapes → `EntityTemplateData` / `PackageTemplateData` / `ModelTemplateData` The declarative template scopes (`scope: "perEntity" | "perPackage" | "perModel"` diff --git a/docs/features/contract-emitters.md b/docs/features/contract-emitters.md index ac56bd8c13..16c8c0619e 100644 --- a/docs/features/contract-emitters.md +++ b/docs/features/contract-emitters.md @@ -200,8 +200,8 @@ openApiFile({ - The `default` keyword: a default belongs to the database or to `@autoSet`, and is not on the wire. - `readOnly` and `writeOnly`: the shapes are separate. -- The TypeScript-only `search`, `filter[or]` and `filter[and]` extensions: the document states the - cross-port contract ([api-contract.md](api-contract.md)). +- `search`, `filter[or]` and `filter[and]`: they are part of the list contract since 1.3.0 + ([api-contract.md](api-contract.md)), but this document does not describe them yet. - 405 answers as operations: a verb a read-only surface does not serve is absent from the document, and the surface's operations say so in prose. - Routes you wrote by hand. Eject `openapi` and add them in `buildOpenApiDocument` if you want them diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index 0fd4bf8f9c..94bd9be9a3 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -290,15 +290,20 @@ it yourself. |---|---|---| | `docs` | which objects and templates get a page, where a page lands, which page template renders, the whole overview page (`renderIndexPage`) | the page payloads (`buildEntityDocData`, `buildTemplateDocData`) and the ER diagram (`renderMermaidErBlock`) | | `api-docs` | which units get a page, where a page lands, whether the index and the agent form (`AGENT-API.md`) are written | the model of the generated API (`buildApiModelForRun`, which also reads the run: layout, `apiPrefix`, whether Hono routes are wired) and its renderers (`renderEntityApiPage`, `renderApiIndex`, `renderAgentApi`) | -| `requirements` | which files the ledger becomes and where they land (`requirements.md`, `requirements.toon`); a project with no `requirement.*` node gets none | the two writers (`requirements-markdown`, `requirements-toon`) and the projection they read (`requirements-view`) | -| `agent-docs` | which of the three pages are written and where; the schema page's inputs (lineage, cardinality, enums) | the three page renderers (`agent-schema-page`, `agent-ui-page`, `agent-requirements-page`) | +| `requirements` | which files the ledger becomes and where they land (`requirements.md`, `requirements.toon`); a project with no `requirement.*` node gets none | the two page builders (`requirements-markdown`, `requirements-toon`) and the projection they read (`requirements-view`) | +| `agent-docs` | which of the three pages are written and where | the three page builders (`agent-schema-page`, which also walks the model for the column-to-field map, lineage, relationships and enums; `agent-ui-page`; `agent-requirements-page`) | | `metamodel-docs` | where the pages land | nothing: the pages are rendered by `@metaobjectsdev/metadata`, which is core | The page templates themselves (the Mustache files the docs generators render) stay in the package. To change the wording of a model page you need no eject: put a file of the same name in your project (`templates/docs/entity-page.md.mustache` or `template-page.md.mustache`), or point `docsFile({ templates })` at another directory; it -wins over the packaged one. +wins over the packaged one. The requirements and agent pages work the same way: +`templates/requirements/requirements.md.mustache` and `requirements.toon.mustache` +(`requirementsFile({ templates })`), and `templates/agent/schema.md.mustache` and +`requirements.md.mustache` (`agentDocsFile({ templates })`; its embedded ledger is the +`requirements/requirements.md` template). The templates and the data they are fed are pinned in +`fixtures/docs-page-conformance/`; which ports run that corpus is in [CONFORMANCE.md](../CONFORMANCE.md). ### The docs site: `meta eject docs-site` copies the theme diff --git a/docs/features/templates-and-payloads.md b/docs/features/templates-and-payloads.md index faef254739..ea012f5ae1 100644 --- a/docs/features/templates-and-payloads.md +++ b/docs/features/templates-and-payloads.md @@ -796,6 +796,7 @@ for payload typing per #270) - [`fixtures/render-conformance/render-list-separator/`](../../fixtures/render-conformance/render-list-separator/) — the `-last` positional accessor: `{{^-last}}, {{/-last}}` separators, nested lists, single-element and empty lists, a scalar conditional and a single nested object inside a list, an authored key - [`fixtures/render-conformance/render-nested-partials/`](../../fixtures/render-conformance/render-nested-partials/) — `{{>partial}}` resolves through the provider, supports nesting - [`fixtures/render-conformance/render-standalone-tag-stripping/`](../../fixtures/render-conformance/render-standalone-tag-stripping/) — a line containing only a section/partial tag is removed (whitespace + newline) +- [`fixtures/render-conformance/render-standalone-consecutive/`](../../fixtures/render-conformance/render-standalone-consecutive/), [`render-standalone-at-eof/`](../../fixtures/render-conformance/render-standalone-at-eof/), [`render-standalone-indented/`](../../fixtures/render-conformance/render-standalone-indented/) — standalone tags on consecutive lines, on the last line with no line break after it, and indented by spaces or a tab each remove their whole line - [`fixtures/render-conformance/render-raw-html-bypass/`](../../fixtures/render-conformance/render-raw-html-bypass/) — `{{{x}}}` (or `{{&x}}`) emits raw, unescaped under `@format=html` - [`fixtures/render-conformance/render-trailing-newline-preservation/`](../../fixtures/render-conformance/render-trailing-newline-preservation/) — final-line newline preserved (prompt-cache stability invariant) - [`fixtures/render-conformance/render-unicode-multibyte/`](../../fixtures/render-conformance/render-unicode-multibyte/) — multibyte input handled without truncation or re-encoding diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index 06add2c7ee..5340dfc039 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -770,6 +770,18 @@ rejection, with no hand-written validation. If you set `apiPrefix` in The `runtime-ts` package supplies the helpers the generated routes lean on (`mountCrudRoutes`, `parseFilterParams`, the `ObjectManager` for full-runtime CRUD). +The list handling is done in two stages. `parseListQuery` (exported from +`@metaobjectsdev/runtime-ts`) reads the query string into a filter tree, a search, a sort and a +page, and raises every refusal the REST standard names. It does not depend on Drizzle. Each mount +then turns that tree into a query for its own library. The Drizzle and Hono mounts and the +`ObjectManager` Fastify mount (`@metaobjectsdev/runtime-ts/fastify`) all parse this way, so they +give the same answers to the same request. Give the `ObjectManager` mount +`filterAllowlist: FilterAllowlist` to serve `filter[...]`, `filter[or]` / `filter[and]` +and `?search`, and `pagination` for `api.pagination`'s page size. Without a filter allowlist it +reads only the page and the sort, as before. A list with no sort is ordered by the primary key. +Hand-written transports should parse with `parseListQueryString` too: `qs`'s default depth +cannot reach the five-level nesting cap. + ### Hono variant (Workers / Bun / edge) For Cloudflare Workers, Bun servers, and any other Hono-flavored runtime, swap diff --git a/docs/recipes/mysql.md b/docs/recipes/mysql.md index a26f83a1b6..4db4fa62e4 100644 --- a/docs/recipes/mysql.md +++ b/docs/recipes/mysql.md @@ -140,7 +140,8 @@ emitted too, and a measure with `@default` is a `COALESCE` whose column MySQL re - The generated `deleteById` checks that the row exists before deleting it. - **`like` is case-sensitive**, as the API contract requires (ADR-0049). MySQL's default collation is case-insensitive, so the generated routes compare with - `COLLATE utf8mb4_bin`. The TypeScript-only `?search` stays case-insensitive. + `COLLATE utf8mb4_bin`. `?search` stays case-insensitive, as the list contract states + ([api-contract.md](../features/api-contract.md)). - **Timestamps use Drizzle's `date` mode.** A `DATETIME` rejects the ISO wire form (`2026-05-28T20:26:40.002Z` is `ERROR 1292`). The generated Zod schema coerces the ISO string to a `Date`, Drizzle stores the UTC wall clock, and the JSON response carries ISO with `Z`. diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-allowlist.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-allowlist.ts index e349d9cf03..53003a16de 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-allowlist.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-allowlist.ts @@ -124,5 +124,5 @@ export function sortOrderSpec( // The `?? "asc"` here is the ONLY place TypeScript's runtime spells the fallback. An // allowlist artifact carries declarations and nothing else — baking the default into // it would put the answer in two places per port, which is how a port drifts. - return supplied ?? allowlist[field]?.defaultOrder ?? "asc"; + return supplied ?? (Object.hasOwn(allowlist, field) ? allowlist[field]?.defaultOrder : undefined) ?? "asc"; } diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-parser.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-parser.ts index 534c2f7c3e..d8befb4565 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-parser.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-parser.ts @@ -1,25 +1,23 @@ import { is, Column, SQL as DrizzleSQL, - eq, ne, gt, gte, lt, lte, inArray, like, ilike, isNull, not, and, or, asc, desc, sql, + eq, ne, gt, gte, lt, lte, inArray, like, ilike, isNull, not, and, or, sql, + asc, desc, type SQL, type SQLWrapper, } from "drizzle-orm"; import type { SqlDialect } from "../sql-dialect.js"; -import type { FilterAllowlist, FilterOp, FilterFieldRule, SortAllowlist } from "./filter-allowlist.js"; -import { sortOrderSpec } from "./filter-allowlist.js"; -import { FilterParseError, parsePageBound, SORT_EXPECTED } from "./list-params.js"; +import type { FilterAllowlist, FilterFieldRule, SortAllowlist } from "./filter-allowlist.js"; +import { FilterParseError } from "./list-params.js"; +import { likePatternToGlob, parseListQuery, type FilterLeaf, type FilterNode, type FilterScalar, type ListSearch } from "./list-query.js"; // Re-exported so existing importers keep one door; the definitions live in the -// drizzle-free list-params module, which the ObjectManager Fastify mount also uses. +// drizzle-free list-params and list-query modules, which the ObjectManager Fastify mount also uses. export { FilterParseError, parsePageBound, pageLimit, ERROR_CODE_LIMIT_TOO_LARGE, type PageSize, PAGINATION_EXPECTED, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, parseReportPage, SORT_EXPECTED } from "./list-params.js"; -import { - ANY_TEMPORAL_EXPECTED, FORMAT_EXPECTED, PLUS_OFFSET_HINT, - looksLikeUnencodedPlusOffset, matchesAnyTemporal, matchesFormat, utcIsoIfZoned, utcIsoInstant, -} from "./filter-value-format.js"; -import { FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_TIMESTAMP } from "@metaobjectsdev/metadata"; -import { canonicalDecimal } from "../decimal-wire.js"; -import { - DURATION_MICROS_MAX, DURATION_MICROS_MIN, durationToStoredMicros, formatPostgresInterval, parseDurationLiteral, -} from "../duration-wire.js"; +export { + likePatternToGlob, parseListQuery, parseListQueryString, rawQueryOf, searchFields, DEFAULT_MAX_IN_LIST, DEFAULT_MAX_NESTING, + type FilterLeaf, type FilterNode, type FilterScalar, type ListQuery, type ListSearch, type ListSort, type ParseListQueryOpts, +} from "./list-query.js"; +import { FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_DURATION } from "@metaobjectsdev/metadata"; +import { durationToStoredMicros, formatPostgresInterval, parseDurationLiteral } from "../duration-wire.js"; // biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user's Drizzle table type AnyTable = any; @@ -39,56 +37,10 @@ export interface ParseFilterResult { orderBy?: SQLWrapper[]; limit?: number; offset?: number; - /** Search predicate — OR(like('%term%')) across @filterable string fields. */ + /** Search predicate — OR(case-insensitive '%term%') across @filterable text fields. */ searchWhere?: SQL; } - -const DEFAULT_MAX_NESTING = 5; -const DEFAULT_MAX_IN_LIST = 100; - -/** Top-level list-query parameters this parser (or the mount around it) reads. A - * filterable field that happens to share one of these names is addressed only through - * `filter[]`, so the bare-field check below never claims them. */ -const RESERVED_LIST_PARAMS: ReadonlySet = new Set([ - "filter", "sort", "limit", "offset", "search", "withCount", -]); - -/** - * `?priority=low` on a list whose allowlist has `priority` is almost always a caller who - * meant `?filter[priority][eq]=low` — and silently ignoring it returns EVERY row, which - * reads as "the filter matched everything". Refuse it, naming the syntax that works. - * - * A bare name that is a field of the entity but NOT on the filter allowlist is refused - * too — the caller plainly meant that field — saying it is not filterable and listing - * the fields that are. Any other unknown parameter — a cache-buster, a tracking tag, a - * param some proxy appends — is left alone, as before. - * TS-only (the other ports ignore unknown parameters): see docs/features/api-contract.md, - * "TS-only filter extensions". - */ -function rejectBareFieldParams(query: Record, allowlist: FilterAllowlist, table: AnyTable): void { - for (const [key, value] of Object.entries(query)) { - if (RESERVED_LIST_PARAMS.has(key)) continue; - if (Object.hasOwn(allowlist, key)) { - const shown = typeof value === "string" ? value : ""; - throw new FilterParseError( - "filter.bare_field", - `"${key}" is a filterable field, but a bare ?${key}= parameter is not a filter. Use filter[${key}][eq]=${shown}.`, - { field: key, expected: `filter[${key}][eq]=${shown}` }, - ); - } - if (isEntityColumn(table, key)) { - const allowed = Object.keys(allowlist); - throw new FilterParseError( - "filter.bare_field", - `"${key}" is a field of this entity, but it is not @filterable, so it cannot be filtered on` + - (allowed.length > 0 ? ` (filterable: ${allowed.join(", ")}).` : " (no field is filterable)."), - { field: key, filterable: false, expected: `a filterable field — "${key}" is not @filterable`, allowed }, - ); - } - } -} - /** Is `key` one of the table's (or view's) own columns? A Drizzle table exposes each * column as a property keyed by its field name; anything else found there (a function, * a symbol-backed config, a proxy that throws on an unknown key) is not a field. */ @@ -102,382 +54,122 @@ function isEntityColumn(table: AnyTable, key: string): boolean { } } +/** A Drizzle column's own enum members (`text(..., { enum })`, `pgEnum`), if it has them. */ +function columnEnumValues(col: unknown): readonly string[] | undefined { + const v = (col as { enumValues?: unknown } | null | undefined)?.enumValues; + return Array.isArray(v) && v.length > 0 && v.every((m) => typeof m === "string") ? (v as string[]) : undefined; +} +/** + * Parse a list query (`parseListQuery`, which raises every refusal) and compile it to + * Drizzle for `opts.table` on `opts.dialect`. + */ export function parseFilterParams(opts: ParseFilterOpts): ParseFilterResult { - rejectBareFieldParams(opts.query, opts.allowlist, opts.table); + const table = opts.table; + const parsed = parseListQuery({ + query: opts.query, + allowlist: opts.allowlist, + sortAllowlist: opts.sortAllowlist, + isField: (name) => isEntityColumn(table, name), + hasColumn: (name) => table[name] !== undefined, + enumValuesOf: (name) => columnEnumValues(table[name]), + ...(opts.maxNesting !== undefined ? { maxNesting: opts.maxNesting } : {}), + ...(opts.maxInListSize !== undefined ? { maxInListSize: opts.maxInListSize } : {}), + }); const result: ParseFilterResult = {}; - - const limit = parsePageBound(opts.query, "limit"); - if (limit !== undefined) result.limit = limit; - const offset = parsePageBound(opts.query, "offset"); - if (offset !== undefined) result.offset = offset; - - if (opts.query.filter && typeof opts.query.filter === "object") { - const where = parseNode( - opts.query.filter as Record, - opts.table, opts.allowlist, opts.dialect, - opts.maxNesting ?? DEFAULT_MAX_NESTING, - opts.maxInListSize ?? DEFAULT_MAX_IN_LIST, - 0, - ); - if (where) result.where = where; - } - - if (typeof opts.query.sort === "string") { - result.orderBy = parseSort(opts.query.sort, opts.table, opts.sortAllowlist, opts.dialect); - } - - if (typeof opts.query.search === "string" && opts.query.search !== "") { - const term = `%${opts.query.search}%`; - const stringCols = Object.entries(opts.allowlist) - // A rule with a `format` (uuid, …) is a typed column on the wire as a string, not - // text: ILIKE on a Postgres uuid column is "operator does not exist" (a 500). - .filter(([, rule]) => { - const r = rule as FilterFieldRule; - return r.subType === "string" && r.format === undefined; - }) - .map(([field]) => opts.table[field]); - if (stringCols.length > 0) { - // `?search` is a TS-only extension (docs/features/api-contract.md) and is - // deliberately case-INSENSITIVE — it is a human search box, not the - // contract's `like` operator (which is case-sensitive SQL LIKE, ADR-0049). - // Postgres uses ILIKE; SQLite's native LIKE folds ASCII case by default, - // which is the intended behavior here. MySQL's LIKE follows the column's - // collation, which is case-insensitive by default and case-sensitive on a - // `_bin` column, so it folds both sides explicitly. - const parts = stringCols.map((col) => - opts.dialect === "postgres" ? ilike(col, term) - : opts.dialect === "mysql" ? sql`LOWER(${col}) LIKE LOWER(${term})` - : like(col, term)); - // or() is defined as returning SQL | undefined but will always return - // SQL when given a non-empty array. parts[0] is always defined here - // because stringCols.length > 0 guarantees at least one element. - // biome-ignore lint/style/noNonNullAssertion: parts is guaranteed non-empty - result.searchWhere = (parts.length === 1 ? parts[0] : or(...parts)) as SQL; - } - } - + if (parsed.limit !== undefined) result.limit = parsed.limit; + if (parsed.offset !== undefined) result.offset = parsed.offset; + if (parsed.filter !== undefined) result.where = compileFilterNode(parsed.filter, table, opts.allowlist, opts.dialect); + if (parsed.sort !== undefined) result.orderBy = nullsAsLargest(table[parsed.sort.field], parsed.sort.order, opts.dialect); + if (parsed.search !== undefined) result.searchWhere = compileSearch(parsed.search, table, opts.dialect); return result; } -function parseNode( - node: Record, - table: AnyTable, - allowlist: FilterAllowlist, - dialect: SqlDialect, - maxNesting: number, - maxInList: number, - depth: number, -): SQL | undefined { - if (depth > maxNesting) { - throw new FilterParseError("filter.nesting_too_deep", `Filter nesting depth exceeds limit (${maxNesting}).`, { limit: maxNesting }); - } - const parts: SQL[] = []; - for (const [key, value] of Object.entries(node)) { - if (key === "or") { - const subs = ensureArray(value, "or").map((sub) => - parseNode(sub as Record, table, allowlist, dialect, maxNesting, maxInList, depth + 1) - ).filter((s): s is SQL => !!s); - if (subs.length > 0) parts.push(or(...subs)!); - } else if (key === "and") { - const subs = ensureArray(value, "and").map((sub) => - parseNode(sub as Record, table, allowlist, dialect, maxNesting, maxInList, depth + 1) - ).filter((s): s is SQL => !!s); - if (subs.length > 0) parts.push(and(...subs)!); - } else { - // key is a field name - const rule = allowlist[key]; - if (!rule) { - throw new FilterParseError("filter.unknown_field", `Unknown filter field "${key}".`, { field: key, allowed: Object.keys(allowlist) }); - } - const col = table[key]; - if (col === undefined) { - throw new FilterParseError("filter.unknown_field", `Table has no column for field "${key}".`, { field: key }); - } - if (typeof value === "object" && value !== null && !Array.isArray(value)) { - for (const [opKey, opValue] of Object.entries(value)) { - const expr = compileOp(col, rule, key, opKey, opValue, dialect, maxInList); - if (expr) parts.push(expr); - } - } else { - // Bare value = eq sugar - const expr = compileOp(col, rule, key, "eq", value, dialect, maxInList); - if (expr) parts.push(expr); - } - } - } - if (parts.length === 0) return undefined; - if (parts.length === 1) return parts[0]; - return and(...parts); +/** Compile a parsed filter tree to a Drizzle condition over `table`. */ +export function compileFilterNode(node: FilterNode, table: AnyTable, allowlist: FilterAllowlist, dialect: SqlDialect): SQL { + if ("and" in node) return and(...node.and.map((n) => compileFilterNode(n, table, allowlist, dialect))) as SQL; + if ("or" in node) return or(...node.or.map((n) => compileFilterNode(n, table, allowlist, dialect))) as SQL; + return compileLeaf(node, table[node.field], allowlist[node.field] as FilterFieldRule, dialect); } -function compileOp( - col: unknown, - rule: FilterFieldRule, - field: string, - op: string, - value: unknown, - dialect: SqlDialect, - maxInList: number, -): SQL | undefined { - if (!rule.ops.includes(op as FilterOp)) { - throw new FilterParseError("filter.unsupported_op", `Op "${op}" not supported for field "${field}".`, { field, op, allowed: rule.ops }); - } - switch (op as FilterOp) { - case "eq": return eq(col as any, coerce(value, rule, col, field, op, dialect)); - case "ne": return ne(col as any, coerce(value, rule, col, field, op, dialect)); - case "gt": return gt(col as any, coerce(value, rule, col, field, op, dialect)); - case "gte": return gte(col as any, coerce(value, rule, col, field, op, dialect)); - case "lt": return lt(col as any, coerce(value, rule, col, field, op, dialect)); - case "lte": return lte(col as any, coerce(value, rule, col, field, op, dialect)); - case "in": { - const list = String(value).split(",").map((v) => coerce(v.trim(), rule, col, field, op, dialect)); - if (list.length > maxInList) { - throw new FilterParseError("filter.in_too_large", `In-list size ${list.length} exceeds limit ${maxInList}.`, { field, limit: maxInList }); - } - return inArray(col as any, list); - } +/** + * `?search` is deliberately case-INSENSITIVE — a human search box, not the contract's `like` + * operator (case-sensitive SQL LIKE, ADR-0049). Postgres uses ILIKE; SQLite's native LIKE + * folds ASCII case, which is the intended behavior here. MySQL's LIKE follows the column's + * collation (case-insensitive by default, case-sensitive on a `_bin` column), so it folds + * both sides explicitly. + */ +function compileSearch(search: ListSearch, table: AnyTable, dialect: SqlDialect): SQL { + const term = `%${search.term}%`; + const parts = search.fields.map((field) => { + const col = table[field]; + return dialect === "postgres" ? ilike(col, term) + : dialect === "mysql" ? sql`LOWER(${col}) LIKE LOWER(${term})` + : like(col, term); + }); + return (parts.length === 1 ? parts[0] : or(...parts)) as SQL; +} + +function compileLeaf(leaf: FilterLeaf, col: unknown, rule: FilterFieldRule, dialect: SqlDialect): SQL { + // biome-ignore lint/suspicious/noExplicitAny: a column of the adopter's Drizzle table + const c = col as any; + const bind = (v: FilterScalar): unknown => bindOperand(v, rule, leaf, dialect); + switch (leaf.op) { + case "eq": return eq(c, bind(leaf.value as FilterScalar)); + case "ne": return ne(c, bind(leaf.value as FilterScalar)); + case "gt": return gt(c, bind(leaf.value as FilterScalar)); + case "gte": return gte(c, bind(leaf.value as FilterScalar)); + case "lt": return lt(c, bind(leaf.value as FilterScalar)); + case "lte": return lte(c, bind(leaf.value as FilterScalar)); + case "in": return inArray(c, (leaf.value as readonly FilterScalar[]).map(bind)); case "like": { - const s = String(value); - if (s.startsWith("%") && !rule.leadingWildcard) { - throw new FilterParseError("filter.leading_wildcard_disallowed", `Leading wildcard not allowed for field "${field}".`, { field }); - } - // Cross-port contract (ADR-0049): `like` is case-SENSITIVE SQL LIKE — - // verbatim author-supplied pattern, `%`/`_` wildcards. Postgres LIKE is - // already case-sensitive. SQLite's built-in LIKE folds ASCII case by - // default (and `PRAGMA case_sensitive_like` is connection-global on a - // consumer-owned connection), so the sqlite branch lowers to GLOB with - // an exactly-translated pattern instead. - // MySQL's LIKE follows the column's collation, which is case-INSENSITIVE by - // default, so the pattern carries an explicit binary collation. + const s = leaf.value as string; + // Cross-port contract (ADR-0049): `like` is case-SENSITIVE SQL LIKE — verbatim + // pattern, `%`/`_` wildcards. Postgres LIKE already is. SQLite's built-in LIKE folds + // ASCII case by default (and `PRAGMA case_sensitive_like` is connection-global on a + // consumer-owned connection), so sqlite lowers to GLOB with an exactly-translated + // pattern. MySQL's LIKE follows the column's collation, so the pattern carries an + // explicit binary collation. return dialect === "postgres" - ? like(col as any, s) + ? like(c, s) : dialect === "mysql" - ? sql`${col} LIKE ${s} COLLATE utf8mb4_bin` - : sql`${col} GLOB ${likePatternToGlob(s)}`; - } - case "isNull": { - // isNull's value is always coerced as boolean (true/false), regardless of the - // field's declared subType — the operator is "is the value null?", not "is X - // equal to null?". Field subtype is irrelevant. - const b = coerceAs(value, "boolean", field, op) as boolean; - return b ? isNull(col as any) : not(isNull(col as any)); + ? sql`${c} LIKE ${s} COLLATE utf8mb4_bin` + : sql`${c} GLOB ${likePatternToGlob(s)}`; } + case "isNull": + return leaf.value === true ? isNull(c) : not(isNull(c)); } } /** - * Translate a SQL LIKE pattern into an equivalent SQLite GLOB pattern: - * `%` → `*`, `_` → `?`, and GLOB's own metacharacters (`*`, `?`, `[`) are - * wrapped in single-character classes so they match literally. `]` is only - * special inside a class, so it passes through. GLOB is case-sensitive, - * which is why the sqlite `like` branch uses it (ADR-0049) — SQLite's - * native LIKE folds ASCII case by default. + * Spell a checked operand the way the column binds it. A decimal operand is exact text + * (ADR-0019 Amendment 1, W2); MySQL compares a DECIMAL column with a string operand as + * DOUBLES, so there it is cast to a wide DECIMAL, and SQLite / D1 hold a decimal as a double + * (W4) and order every number before any text, so there it is bound as the number it is. A + * duration is the microsecond integer on SQLite / D1 / MySQL and the interval spelling on + * Postgres (which refuses a signed ISO-8601 duration). A timestamp on a column emitted under + * `timestampMode: "date"` (`dateValues`) binds a real `Date`: Drizzle calls `toISOString()` + * on it. */ -export function likePatternToGlob(pattern: string): string { - let out = ""; - for (const ch of pattern) { - if (ch === "%") out += "*"; - else if (ch === "_") out += "?"; - else if (ch === "*") out += "[*]"; - else if (ch === "?") out += "[?]"; - else if (ch === "[") out += "[[]"; - else out += ch; - } - return out; -} - -function invalidValue( - field: string, - op: string, - s: string, - expected: string, - extra: Record = {}, -): FilterParseError { - const hint = typeof extra["hint"] === "string" ? ` Hint: ${extra["hint"]}.` : ""; - return new FilterParseError( - "filter.invalid_value", - `Field "${field}" op "${op}" requires ${expected}, got "${s}".${hint}`, - { field, op, expected, ...extra }, - ); -} - -/** A Drizzle column's own enum members (`text(..., { enum })`, `pgEnum`), if it has them. */ -function columnEnumValues(col: unknown): readonly string[] | undefined { - const v = (col as { enumValues?: unknown } | null | undefined)?.enumValues; - return Array.isArray(v) && v.length > 0 && v.every((m) => typeof m === "string") ? (v as string[]) : undefined; -} - -/** - * Refuse a value that cannot be the field's type BEFORE it is bound. Without this a - * malformed date on SQLite compared as text and silently matched nothing (200 `[]`), - * and on Postgres the driver refused the cast (a 500) — either way the caller could not - * tell a typo from an empty result. The envelope is the cross-port `invalid_filter_value`, - * carrying `op` and `expected` as the number/boolean checks already did. - */ -function assertWellFormed(s: string, rule: FilterFieldRule, col: unknown, field: string, op: string): void { - const members = rule.enumValues ?? columnEnumValues(col); - if (members !== undefined && !members.includes(s)) { - throw invalidValue(field, op, s, `one of: ${members.join(", ")}`, { allowed: [...members] }); - } - if (rule.format !== undefined) { - if (!matchesFormat(rule.format, s)) { - // `filter[dueAt][lt]=2026-10-06T00:00:00+00:00` sent unencoded arrives with a space - // where the `+` was; "expected timestamp" alone does not say why a valid-looking - // value failed, so the answer names the fix. - const hint = rule.format === FIELD_SUBTYPE_TIMESTAMP && looksLikeUnencodedPlusOffset(s) - ? { hint: PLUS_OFFSET_HINT } - : {}; - throw invalidValue(field, op, s, FORMAT_EXPECTED[rule.format], hint); - } - } else if (rule.subType === "datetime" && !matchesAnyTemporal(s)) { - throw invalidValue(field, op, s, ANY_TEMPORAL_EXPECTED); - } -} - -/** Check a comparison value against the field's rule, then coerce it for binding. */ -function coerce(value: unknown, rule: FilterFieldRule, col: unknown, field: string, op: string, dialect: SqlDialect): unknown { - if (value === null || value === undefined) return null; - const s = typeof value === "string" ? value : String(value); - assertWellFormed(s, rule, col, field, op); - // A decimal operand is exact text, never a number (ADR-0019 Amendment 1, W2): parsed with - // the JSON-number grammar and bound as its canonical string. MySQL compares a DECIMAL column - // with a string operand as DOUBLES, so there the operand is cast to a wide DECIMAL first. - // SQLite and D1 hold a decimal as a double (W4) and order every number before any text, so a - // text operand against a computed column (a view's sum or average has no NUMERIC affinity) - // would compare false in the wrong direction: the operand is bound as the number it is, exact - // to the 15 digits W4 promises. +function bindOperand(v: FilterScalar, rule: FilterFieldRule, leaf: FilterLeaf, dialect: SqlDialect): unknown { if (rule.format === FIELD_SUBTYPE_DECIMAL) { - const canonical = canonicalDecimal(s) as string; - if (dialect === "mysql") return sql`CAST(${canonical} AS DECIMAL(65,30))`; - return dialect === "sqlite" ? Number(canonical) : canonical; + if (dialect === "mysql") return sql`CAST(${v} AS DECIMAL(65,30))`; + return dialect === "sqlite" ? Number(v) : v; } - // A duration bound is spelled the way the column stores it: the microsecond integer on SQLite / - // D1 / MySQL, the interval spelling on Postgres (which refuses a signed ISO-8601 duration). Both - // compare and order as the span does. if (rule.format === FIELD_SUBTYPE_DURATION) { - const micros = parseDurationLiteral(s) as bigint; - // A well-formed span past 64 bits of microseconds is no stored value on any database, so it is - // a bad operand (400), not an error out of the binder. - if (micros > DURATION_MICROS_MAX || micros < DURATION_MICROS_MIN) throw invalidValue(field, op, s, DURATION_IN_RANGE); + const micros = parseDurationLiteral(String(v)) as bigint; return dialect === "sqlite" || dialect === "mysql" ? durationToStoredMicros(micros) : formatPostgresInterval(micros); } - // A timestamp bound is compared in the same UTC spelling the generated schemas store: - // on SQLite/D1 the column is TEXT and compares as text. An instant field (`instant`, i.e. - // not @localTime) reads a zoneless or date-only bound as UTC, as its write schema does — - // also before a Date-bound (`dateValues`) column's `new Date(...)`, which would otherwise - // read a zoneless string in the SERVER's local zone. Without `instant`, only a zoned - // bound is rewritten, and a Date-bound column parses the value itself. - if (rule.format === FIELD_SUBTYPE_TIMESTAMP) { - const bound = rule.instant === true ? utcIsoInstant(s) : rule.dateValues === true ? s : utcIsoIfZoned(s); - return coerceAs(bound, rule.subType, field, op, rule.dateValues); - } - const coerced = coerceAs(s, rule.subType, field, op, rule.dateValues); - // field.int / field.long / field.currency: a fractional bound is not a value of the field. - if (rule.integer === true && typeof coerced === "number" && !Number.isInteger(coerced)) { - throw invalidValue(field, op, s, INTEGER_EXPECTED); - } - return coerced; -} - -/** `expected` for a non-whole bound on an integer-valued field (`integer: true`). */ -const INTEGER_EXPECTED = "integer (a whole number)"; -const DURATION_IN_RANGE = "duration within the 64-bit microsecond range"; - -function coerceAs(value: unknown, subType: string, field: string, op: string, dateValues?: boolean): unknown { - if (value === null || value === undefined) return null; - const s = typeof value === "string" ? value : String(value); - switch (subType) { - case "string": return s; - case "boolean": { - if (s === "true" || s === "1") return true; - if (s === "false" || s === "0") return false; - throw new FilterParseError("filter.invalid_value", `Field "${field}" op "${op}" requires boolean, got "${s}".`, { field, op, expected: "boolean" }); - } - case "number": { - // `Number("")` and `Number(" ")` are 0 — an empty bound is not the number zero. - const n = s.trim() === "" ? Number.NaN : Number(s); - if (!Number.isFinite(n)) { - throw new FilterParseError("filter.invalid_value", `Field "${field}" op "${op}" requires number, got "${s}".`, { field, op, expected: "number" }); - } - return n; + if (rule.subType === "datetime" && rule.dateValues === true) { + const d = new Date(String(v)); + // `new Date("garbage")` is an Invalid Date rather than a throw; binding one would emit + // `NaN`-shaped SQL. + if (Number.isNaN(d.getTime())) { + throw new FilterParseError("filter.invalid_value", `Field "${leaf.field}" op "${leaf.op}" requires a date, got "${String(v)}".`, { field: leaf.field, op: leaf.op, expected: "date" }); } - // Under codegen's Postgres-only `timestampMode: "date"` the Drizzle column is - // Date-typed and calls `value.toISOString()` on any bound value, so passing the - // raw qs string through threw `TypeError: value.toISOString is not a function` - // for every op except isNull. The generated allowlist now carries `dateValues` - // for exactly those columns (see FilterFieldRule), so the value is bound as a - // real Date. In the default "string" mode — and for field.date / field.time, - // which Drizzle types as strings under every dialect — the flag is absent and - // the value stays a string, unchanged. - case "datetime": { - if (dateValues !== true) return s; - const d = new Date(s); - // `new Date("garbage")` yields an Invalid Date rather than throwing; binding - // one would emit `NaN`-shaped SQL. Reject at the boundary, matching how the - // number and boolean cases report a malformed value. - if (Number.isNaN(d.getTime())) { - throw new FilterParseError("filter.invalid_value", `Field "${field}" op "${op}" requires a date, got "${s}".`, { field, op, expected: "date" }); - } - return d; - } - default: return s; - } -} - -function ensureArray(v: unknown, key: string): unknown[] { - if (Array.isArray(v)) return v; - if (v && typeof v === "object") { - // qs.parse may produce { "0": ..., "1": ... } shape for filter[or][0]... - return Object.values(v); - } - // Defensive — qs.parse normally produces an object/array; this branch is - // only reachable if a caller hand-constructs a malformed query object. - // - // `field` (not `key`) because this maps to the cross-port `invalid_filter_value` - // envelope, which REQUIRES `field` naming the offending filter key — here the - // `or`/`and` connector that was handed a non-array. - throw new FilterParseError("filter.invalid_value", `Expected array for "${key}".`, { field: key }); -} - -function parseSort(spec: string, table: AnyTable, sortAllowlist: SortAllowlist, dialect: SqlDialect | undefined): SQLWrapper[] { - const colonIdx = spec.indexOf(":"); - const field = colonIdx === -1 ? spec : spec.slice(0, colonIdx); - if (!sortAllowlist[field]) { - throw new FilterParseError( - "sort.unknown_field", - `Unknown sort field "${field}". The syntax is ${SORT_EXPECTED}.`, - { field, expected: SORT_EXPECTED, allowed: Object.keys(sortAllowlist) }, - ); - } - // `?sort=field` with no `:order` takes the field's DECLARED default order. - // - // This is the read side of `@sortableDefaultOrder`, and until now there was none. - // The attribute was authored by an adopter, carried through the loader, and emitted - // into the generated `SortAllowlist` as `{ defaultOrder: "desc" }` — and then - // nothing read it back. One door in, no door out: the adopter authored a promise the - // product never kept, and every unqualified sort came back ascending regardless. - // - // Scoped deliberately to "field named, order omitted". Applying it when `?sort` is - // ABSENT ENTIRELY would give every endpoint a default ordering it does not have - // today — a behaviour change for every consumer, to honour an attribute about how a - // FIELD sorts. The declaration says which way this column runs when you do not say; - // it does not say which column to sort by. - const orderRaw = sortOrderSpec( - sortAllowlist, - field, - colonIdx === -1 ? undefined : spec.slice(colonIdx + 1), - ); - const order = orderRaw.toLowerCase(); - if (order !== "asc" && order !== "desc") { - throw new FilterParseError( - "sort.invalid_order", - `Sort order must be asc|desc, got "${orderRaw}". The syntax is ${SORT_EXPECTED}.`, - { field, expected: SORT_EXPECTED, allowed: Object.keys(sortAllowlist) }, - ); + return d; } - const col = table[field]; - return nullsAsLargest(col as any, order, dialect); + return v; } /** diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/index.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/index.ts index 9eb84fd2a9..225721b86a 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/index.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/index.ts @@ -23,7 +23,7 @@ import type { FastifyInstance, RouteShorthandOptions } from "fastify"; import { classifyConstraintError, RedactedDatabaseError, logAndRedact } from "../constraint-errors.js"; import type { ZodTypeAny } from "zod"; import { eq, count, and, asc } from "drizzle-orm"; -import qs from "qs"; +import { parseListQueryString } from "./list-query.js"; import type { FilterAllowlist, SortAllowlist } from "./filter-allowlist.js"; export type { FilterAllowlist, SortAllowlist } from "./filter-allowlist.js"; import { parseFilterParams, parsePageBound, pageLimit, FilterParseError, type PageSize } from "./filter-parser.js"; @@ -35,6 +35,10 @@ import { withContractErrorHandler } from "./route-error-handler.js"; import { validationErrorBody } from "../route-errors.js"; export { isTruthyFlag, contractErrorCode, parseId, coerceIdForColumn } from "./util.js"; export { pageLimit, ERROR_CODE_LIMIT_TOO_LARGE, type PageSize } from "./list-params.js"; +export { + parseListQuery, parseListQueryString, rawQueryOf, FilterParseError, + type FilterNode, type ListQuery, type ParseListQueryOpts, +} from "./filter-parser.js"; export { ERROR_CODE_UNKNOWN_FIELDS, unknownBodyKeys } from "../wire-format.js"; export { timestampWire, canonicalTimestamp } from "../timestamp-wire.js"; export { decimalWire, withDecimals, decimalToNative, canonicalDecimal, parseDecimalInput, parseDecimalOperand } from "../decimal-wire.js"; @@ -210,7 +214,7 @@ export function mountListRoute(opts: VerbOptions): void { const rawSearch = req.raw.url?.includes("?") ? req.raw.url.slice(req.raw.url.indexOf("?") + 1) : ""; - const qsParsed = qs.parse(rawSearch) as Record; + const qsParsed = parseListQueryString(rawSearch); const withCount = isTruthyFlag(qsParsed.withCount); // FR-017 TPH: when subtype-scoped, AND the discriminator predicate into diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/list-params.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/list-params.ts index f8499489b1..1a1bdc3412 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/list-params.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/list-params.ts @@ -27,9 +27,9 @@ export const PAGINATION_EXPECTED = "a non-negative integer (0 or more)"; * Read `?limit=` / `?offset=` as a non-negative integer, or refuse it. Before, a value * that was not a finite number (`?limit=abc`) was dropped — every row came back — and a * negative or fractional one reached SQL. `max` is the ceiling a mount clamps to, when it - * has one: a bound above it is refused rather than silently lowered. TS-only (no corpus - * scenario sends a malformed page bound): see docs/features/api-contract.md, "TS-only - * error responses". + * has one: a bound above it is refused rather than silently lowered. Part of the REST + * contract (docs/features/api-contract.md, "Error responses for a bad request or a failed + * write"), pinned by `list-query/pagination-invalid-value` and `report/bad-page-bound`. */ export function parsePageBound( query: Record, diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/list-query.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/list-query.ts new file mode 100644 index 0000000000..05c4fd2c20 --- /dev/null +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/list-query.ts @@ -0,0 +1,385 @@ +/** + * The list query a REST list route reads, parsed into a port-neutral form BEFORE any query + * library sees it: a filter tree, a search, a sort, a page. Every refusal of the REST standard + * is raised here (`docs/features/api-contract.md`, "List handling"), so the Drizzle mounts and + * the ObjectManager mount refuse a request identically and differ only in how they run the + * tree. Deliberately free of drizzle-orm (an OPTIONAL peer), like `list-params.ts`. + * + * `fixtures/list-query-conformance/` pins this function's answers — a query string and a + * field list in, a tree or a named error out — for every port. + */ + +import qs from "qs"; +import { FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_TIMESTAMP } from "@metaobjectsdev/metadata"; +import type { FilterAllowlist, FilterFieldRule, FilterOp, SortAllowlist } from "./filter-allowlist.js"; +import { sortOrderSpec } from "./filter-allowlist.js"; +import { FilterParseError, parsePageBound, SORT_EXPECTED } from "./list-params.js"; +import { + ANY_TEMPORAL_EXPECTED, FORMAT_EXPECTED, PLUS_OFFSET_HINT, + looksLikeUnencodedPlusOffset, matchesAnyTemporal, matchesFormat, utcIsoIfZoned, utcIsoInstant, +} from "./filter-value-format.js"; +import { canonicalDecimal } from "../decimal-wire.js"; +import { DURATION_MICROS_MAX, DURATION_MICROS_MIN, parseDurationLiteral } from "../duration-wire.js"; + +/** A scalar operand after its checks: a number or boolean as that type, everything else text. */ +export type FilterScalar = string | number | boolean; + +/** One comparison. `in` carries a list; `isNull` a boolean; every other op one scalar. */ +export interface FilterLeaf { + readonly field: string; + readonly op: FilterOp; + readonly value: FilterScalar | readonly FilterScalar[]; +} + +/** A filter tree: a comparison, or an AND / OR of subtrees (never empty). */ +export type FilterNode = FilterLeaf | { readonly and: readonly FilterNode[] } | { readonly or: readonly FilterNode[] }; + +export interface ListSearch { + /** The term as sent; matched case-insensitively as a substring. */ + readonly term: string; + /** The `@filterable` text fields it is matched against (OR), in allowlist order. */ + readonly fields: readonly string[]; +} + +export interface ListSort { + readonly field: string; + readonly order: "asc" | "desc"; +} + +export interface ListQuery { + readonly filter?: FilterNode; + readonly search?: ListSearch; + readonly sort?: ListSort; + readonly limit?: number; + readonly offset?: number; +} + +export interface ParseListQueryOpts { + /** The bracketed query, as `parseListQueryString` returns it. */ + readonly query: Record; + readonly allowlist: FilterAllowlist; + readonly sortAllowlist: SortAllowlist; + /** + * Is `name` a field of the entity (a column of the table or view the list reads)? A bare + * `?name=` naming one that is not filterable is refused as `filter.bare_field`; absent, only + * a bare FILTERABLE field is refused. + */ + readonly isField?: (name: string) => boolean; + /** A field on the allowlist the read source has no column for (an allowlist out of step + * with its table) is `invalid_filter_field`. Absent, every allowlisted field has one. */ + readonly hasColumn?: (name: string) => boolean; + /** The enum members of a field whose rule carries none (an allowlist generated before + * `enumValues` existed: the Drizzle column's own members). */ + readonly enumValuesOf?: (name: string) => readonly string[] | undefined; + readonly maxNesting?: number; + readonly maxInListSize?: number; +} + +/** The deepest `or` / `and` nesting a filter may use; one level deeper is `filter.nesting_too_deep`. */ +export const DEFAULT_MAX_NESTING = 5; +/** The most elements an `in` list may carry; one more is `filter.in_too_large`. */ +export const DEFAULT_MAX_IN_LIST = 100; + +/** + * Parse a raw query string (no leading `?`) into the bracketed tree the list routes read. + * + * qs's defaults would cut the tree short: past 5 brackets it keeps the rest of a key as one + * literal string (`filter[or][0][or][0][or][0][a][eq]` became a field named `[0][a][eq]`, an + * `invalid_filter_field` naming a field nobody sent), so the nesting cap could never be reached + * and a three-level filter was refused for the wrong reason. The depth here admits one level + * past the cap — two brackets per level plus the field and the op — so a too-deep filter is + * answered as one, and an index above 20 stays an index rather than becoming an object key. + */ +export function parseListQueryString(raw: string, maxNesting: number = DEFAULT_MAX_NESTING): Record { + return qs.parse(raw, { depth: 2 * (maxNesting + 1) + 3, arrayLimit: DEFAULT_MAX_IN_LIST }) as Record; +} + +/** The query string of a request URL (`/x?a=1` → `a=1`; no `?` → ""). */ +export function rawQueryOf(url: string | undefined): string { + if (url === undefined) return ""; + const i = url.indexOf("?"); + return i === -1 ? "" : url.slice(i + 1); +} + +/** Top-level list-query parameters this parser (or the mount around it) reads. A + * filterable field that happens to share one of these names is addressed only through + * `filter[]`, so the bare-field check below never claims them. */ +const RESERVED_LIST_PARAMS: ReadonlySet = new Set([ + "filter", "sort", "limit", "offset", "search", "withCount", +]); + +/** + * Parse and check a list query. The checks run in a fixed order, which is part of the + * contract when a request carries more than one fault: bare field parameters, `limit`, + * `offset`, the filter (depth-first, in the order its keys were sent), `sort`, `search`. + */ +export function parseListQuery(opts: ParseListQueryOpts): ListQuery { + rejectBareFieldParams(opts.query, opts.allowlist, opts.isField); + const out: { -readonly [K in keyof ListQuery]: ListQuery[K] } = {}; + + const limit = parsePageBound(opts.query, "limit"); + if (limit !== undefined) out.limit = limit; + const offset = parsePageBound(opts.query, "offset"); + if (offset !== undefined) out.offset = offset; + + if (opts.query.filter && typeof opts.query.filter === "object") { + const filter = parseNode(opts.query.filter as Record, opts, 0); + if (filter) out.filter = filter; + } + + if (typeof opts.query.sort === "string") out.sort = parseSort(opts.query.sort, opts.sortAllowlist); + + if (typeof opts.query.search === "string" && opts.query.search !== "") { + const fields = searchFields(opts.allowlist); + if (fields.length > 0) out.search = { term: opts.query.search, fields }; + } + return out; +} + +/** + * The fields `?search` matches: `@filterable` text fields. A rule with a `format` (uuid, …) + * is a typed column that is a string on the wire, not text — a case-insensitive LIKE on a + * Postgres uuid column is "operator does not exist" (a 500). + */ +export function searchFields(allowlist: FilterAllowlist): string[] { + return Object.entries(allowlist) + // A search term is a `like` pattern, so only a field whose band has `like` takes part: a + // typed column spelled as a string (uuid, a `format`) and an int-backed enum (an integer + // column, no `like` in its band) would make Postgres answer "operator does not exist". + .filter(([, rule]) => rule.subType === "string" && rule.format === undefined && rule.ops.includes("like")) + .map(([field]) => field); +} + +/** + * `?priority=low` on a list whose allowlist has `priority` is almost always a caller who + * meant `?filter[priority][eq]=low` — and silently ignoring it returns EVERY row, which + * reads as "the filter matched everything". Refuse it, naming the syntax that works. + * + * A bare name that is a field of the entity but NOT on the filter allowlist is refused + * too — the caller plainly meant that field — saying it is not filterable and listing + * the fields that are. Any other unknown parameter — a cache-buster, a tracking tag, a + * param some proxy appends — is left alone. + */ +function rejectBareFieldParams( + query: Record, + allowlist: FilterAllowlist, + isField: ((name: string) => boolean) | undefined, +): void { + for (const [key, value] of Object.entries(query)) { + if (RESERVED_LIST_PARAMS.has(key)) continue; + if (Object.hasOwn(allowlist, key)) { + const shown = typeof value === "string" ? value : ""; + throw new FilterParseError( + "filter.bare_field", + `"${key}" is a filterable field, but a bare ?${key}= parameter is not a filter. Use filter[${key}][eq]=${shown}.`, + { field: key, expected: `filter[${key}][eq]=${shown}` }, + ); + } + if (isField?.(key) === true) { + const allowed = Object.keys(allowlist); + throw new FilterParseError( + "filter.bare_field", + `"${key}" is a field of this entity, but it is not @filterable, so it cannot be filtered on` + + (allowed.length > 0 ? ` (filterable: ${allowed.join(", ")}).` : " (no field is filterable)."), + { field: key, filterable: false, expected: `a filterable field — "${key}" is not @filterable`, allowed }, + ); + } + } +} + +function parseNode(node: Record, opts: ParseListQueryOpts, depth: number): FilterNode | undefined { + const maxNesting = opts.maxNesting ?? DEFAULT_MAX_NESTING; + if (depth > maxNesting) { + throw new FilterParseError("filter.nesting_too_deep", `Filter nesting depth exceeds limit (${maxNesting}).`, { limit: maxNesting }); + } + const parts: FilterNode[] = []; + for (const [key, value] of Object.entries(node)) { + if (key === "or" || key === "and") { + const subs = ensureArray(value, key) + .map((sub) => parseNode(asNode(sub, key), opts, depth + 1)) + .filter((s): s is FilterNode => s !== undefined); + if (subs.length === 0) continue; + // One branch is that branch: `or` of one condition is the condition. + parts.push(subs.length === 1 ? (subs[0] as FilterNode) : key === "or" ? { or: subs } : { and: subs }); + continue; + } + const rule = Object.hasOwn(opts.allowlist, key) ? opts.allowlist[key] : undefined; + if (!rule) { + throw new FilterParseError("filter.unknown_field", `Unknown filter field "${key}".`, { field: key, allowed: Object.keys(opts.allowlist) }); + } + if (opts.hasColumn !== undefined && !opts.hasColumn(key)) { + throw new FilterParseError("filter.unknown_field", `Table has no column for field "${key}".`, { field: key }); + } + if (typeof value === "object" && value !== null && !Array.isArray(value)) { + for (const [op, operand] of Object.entries(value)) parts.push(leaf(key, rule, op, operand, opts)); + } else { + // A bare value is `eq` sugar. + parts.push(leaf(key, rule, "eq", value, opts)); + } + } + if (parts.length === 0) return undefined; + return parts.length === 1 ? parts[0] : { and: parts }; +} + +/** A combinator's branch must itself be a filter object; a scalar there (`filter[or][0]=x`) + * names no field. */ +function asNode(sub: unknown, key: string): Record { + if (sub !== null && typeof sub === "object" && !Array.isArray(sub)) return sub as Record; + throw new FilterParseError("filter.invalid_value", `Each "${key}" branch must be a filter object.`, { field: key }); +} + +function ensureArray(v: unknown, key: string): unknown[] { + if (Array.isArray(v)) return v; + // qs gives `{ "0": …, "1": … }` for sparse or very large indexes; integer keys iterate + // in ascending order, so the branches keep their numeric order. + if (v && typeof v === "object") return Object.values(v); + // `field` (not `key`) because this is the cross-port `invalid_filter_value` envelope, + // which REQUIRES `field` naming the offending filter key — here the connector. + throw new FilterParseError("filter.invalid_value", `Expected array for "${key}".`, { field: key }); +} + +function leaf(field: string, rule: FilterFieldRule, op: string, operand: unknown, opts: ParseListQueryOpts): FilterLeaf { + if (!rule.ops.includes(op as FilterOp)) { + throw new FilterParseError("filter.unsupported_op", `Op "${op}" not supported for field "${field}".`, { field, op, allowed: rule.ops }); + } + const filterOp = op as FilterOp; + switch (filterOp) { + case "in": { + const maxInList = opts.maxInListSize ?? DEFAULT_MAX_IN_LIST; + const list = String(operand).split(",").map((v) => operandOf(v.trim(), rule, field, op, opts)); + if (list.length > maxInList) { + throw new FilterParseError("filter.in_too_large", `In-list size ${list.length} exceeds limit ${maxInList}.`, { field, limit: maxInList }); + } + return { field, op: filterOp, value: list }; + } + case "like": { + const s = String(operand); + if (s.startsWith("%") && !rule.leadingWildcard) { + throw new FilterParseError("filter.leading_wildcard_disallowed", `Leading wildcard not allowed for field "${field}".`, { field }); + } + // `like` is case-SENSITIVE SQL LIKE (ADR-0049): the pattern is kept verbatim. + return { field, op: filterOp, value: s }; + } + case "isNull": + // The operand is "is the value null?" — a boolean whatever the field's type. + return { field, op: filterOp, value: asBoolean(operand, field, op) }; + default: + return { field, op: filterOp, value: operandOf(operand, rule, field, op, opts) }; + } +} + +/** `expected` for a non-whole bound on an integer-valued field (`integer: true`). */ +const INTEGER_EXPECTED = "integer (a whole number)"; +const DURATION_IN_RANGE = "duration within the 64-bit microsecond range"; + +function invalidValue(field: string, op: string, s: string, expected: string, extra: Record = {}): FilterParseError { + const hint = typeof extra["hint"] === "string" ? ` Hint: ${extra["hint"]}.` : ""; + return new FilterParseError( + "filter.invalid_value", + `Field "${field}" op "${op}" requires ${expected}, got "${s}".${hint}`, + { field, op, expected, ...extra }, + ); +} + +/** + * Check a comparison operand against the field's rule and give it its neutral form: a + * number or boolean as that type; a decimal as its canonical text (never through a double, + * ADR-0019 Amendment 1); an instant timestamp in the stored UTC spelling (a zoneless or + * date-only bound read as UTC), any other timestamp with only a zoned bound rewritten to + * UTC; everything else as sent. Refusing a malformed operand here is what keeps SQLite from + * comparing it as text (a silent `[]`) and Postgres from failing the cast (a 500). + */ +function operandOf(value: unknown, rule: FilterFieldRule, field: string, op: string, opts: ParseListQueryOpts): FilterScalar { + const s = typeof value === "string" ? value : String(value); + const members = rule.enumValues ?? opts.enumValuesOf?.(field); + if (members !== undefined && !members.includes(s)) { + throw invalidValue(field, op, s, `one of: ${members.join(", ")}`, { allowed: [...members] }); + } + if (rule.format !== undefined) { + if (!matchesFormat(rule.format, s)) { + // `filter[dueAt][lt]=2026-10-06T00:00:00+00:00` sent unencoded arrives with a space + // where the `+` was; the answer names the fix. + const hint = rule.format === FIELD_SUBTYPE_TIMESTAMP && looksLikeUnencodedPlusOffset(s) ? { hint: PLUS_OFFSET_HINT } : {}; + throw invalidValue(field, op, s, FORMAT_EXPECTED[rule.format], hint); + } + } else if (rule.subType === "datetime" && !matchesAnyTemporal(s)) { + throw invalidValue(field, op, s, ANY_TEMPORAL_EXPECTED); + } + if (rule.format === FIELD_SUBTYPE_DECIMAL) return canonicalDecimal(s) as string; + if (rule.format === FIELD_SUBTYPE_DURATION) { + // A well-formed span past 64 bits of microseconds is no stored value on any database. + const micros = parseDurationLiteral(s) as bigint; + if (micros > DURATION_MICROS_MAX || micros < DURATION_MICROS_MIN) throw invalidValue(field, op, s, DURATION_IN_RANGE); + return s; + } + if (rule.format === FIELD_SUBTYPE_TIMESTAMP) return rule.instant === true ? utcIsoInstant(s) : utcIsoIfZoned(s); + switch (rule.subType) { + case "boolean": + return asBoolean(s, field, op); + case "number": { + // `Number("")` and `Number(" ")` are 0 — an empty bound is not the number zero. + const n = s.trim() === "" ? Number.NaN : Number(s); + if (!Number.isFinite(n)) { + throw new FilterParseError("filter.invalid_value", `Field "${field}" op "${op}" requires number, got "${s}".`, { field, op, expected: "number" }); + } + // field.int / field.long / field.currency: a fractional bound is not a value of the field. + if (rule.integer === true && !Number.isInteger(n)) throw invalidValue(field, op, s, INTEGER_EXPECTED); + return n; + } + default: + return s; + } +} + +function asBoolean(value: unknown, field: string, op: string): boolean { + const s = typeof value === "string" ? value : String(value); + if (s === "true" || s === "1") return true; + if (s === "false" || s === "0") return false; + throw new FilterParseError("filter.invalid_value", `Field "${field}" op "${op}" requires boolean, got "${s}".`, { field, op, expected: "boolean" }); +} + +function parseSort(spec: string, sortAllowlist: SortAllowlist): ListSort { + const colonIdx = spec.indexOf(":"); + const field = colonIdx === -1 ? spec : spec.slice(0, colonIdx); + if (!Object.hasOwn(sortAllowlist, field)) { + throw new FilterParseError( + "sort.unknown_field", + `Unknown sort field "${field}". The syntax is ${SORT_EXPECTED}.`, + { field, expected: SORT_EXPECTED, allowed: Object.keys(sortAllowlist) }, + ); + } + // `?sort=field` with no `:order` takes the field's DECLARED `@sortableDefaultOrder`. + // Applying it when `?sort` is absent entirely would give every endpoint an ordering it + // does not have: the declaration says which way a column runs, not which column to sort by. + const orderRaw = sortOrderSpec(sortAllowlist, field, colonIdx === -1 ? undefined : spec.slice(colonIdx + 1)); + const order = orderRaw.toLowerCase(); + if (order !== "asc" && order !== "desc") { + throw new FilterParseError( + "sort.invalid_order", + `Sort order must be asc|desc, got "${orderRaw}". The syntax is ${SORT_EXPECTED}.`, + { field, expected: SORT_EXPECTED, allowed: Object.keys(sortAllowlist) }, + ); + } + return { field, order }; +} + +/** + * Translate a SQL LIKE pattern into an equivalent SQLite GLOB pattern: + * `%` → `*`, `_` → `?`, and GLOB's own metacharacters (`*`, `?`, `[`) are + * wrapped in single-character classes so they match literally. `]` is only + * special inside a class, so it passes through. GLOB is case-sensitive, + * which is why the sqlite `like` branch uses it (ADR-0049) — SQLite's + * native LIKE folds ASCII case by default. + */ +export function likePatternToGlob(pattern: string): string { + let out = ""; + for (const ch of pattern) { + if (ch === "%") out += "*"; + else if (ch === "_") out += "?"; + else if (ch === "*") out += "[*]"; + else if (ch === "?") out += "[?]"; + else if (ch === "[") out += "[[]"; + else out += ch; + } + return out; +} diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts index 93e97cffde..c06f5fdaec 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts @@ -1,7 +1,7 @@ import type { FastifyInstance, RouteShorthandOptions } from "fastify"; import { quoteIdent, type SqlDialect } from "../sql-dialect.js"; import { sql, eq, and, count } from "drizzle-orm"; -import qs from "qs"; +import { parseListQueryString } from "./list-query.js"; import { parseFilterParams, parsePageBound, pageLimit, parseReportPage, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, FilterParseError, type PageSize } from "./filter-parser.js"; import { ReportExportError, assertExportWithinCap, exportContentDisposition, exportWithCountError, isExportCountFlag, @@ -194,7 +194,7 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const url = req.raw.url ?? ""; const qIdx = url.indexOf("?"); const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = qs.parse(queryString) as Record; + const parsed = parseListQueryString(queryString); // A bound that is not an integer in range is a 400, not silently clamped. const reportPage = isReport ? parseReportPage(parsed, reportMaxRows) : undefined; const limitVal = reportPage?.limit ?? parsePageBound(parsed, "limit", RAW_VIEW_MAX_LIMIT) ?? RAW_VIEW_MAX_LIMIT; @@ -214,7 +214,7 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const url = req.raw.url ?? ""; const qIdx = url.indexOf("?"); const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = qs.parse(queryString) as Record; + const parsed = parseListQueryString(queryString); const withCount = isTruthyFlag(parsed["withCount"]); // Export mode: the selector is validated before any query runs, and the export cap governs. const format = exportSpec ? readExportFormat(parsed, exportSpec) : undefined; diff --git a/examples/advanced-modeling/codegen/runtime/route-errors.ts b/examples/advanced-modeling/codegen/runtime/route-errors.ts index 0a1a0e187c..b01d7a9f45 100644 --- a/examples/advanced-modeling/codegen/runtime/route-errors.ts +++ b/examples/advanced-modeling/codegen/runtime/route-errors.ts @@ -18,9 +18,9 @@ * mount folded it into a Zod `validation` error. Both now answer * `400 { "error": "invalid_json" }`. * - * The api-contract corpus pins neither response (5xx is implementation-defined there, and - * no scenario sends a malformed body), so both are TS-helper extensions — documented in - * docs/features/api-contract.md, "TS-only error responses". + * Both are in the REST contract (docs/features/api-contract.md, "Error responses for a bad + * request or a failed write"); `api-contract-conformance/list-query/invalid-json` sends a + * malformed body. A 5xx body is otherwise implementation-defined there. */ import { RedactedDatabaseError, logAndRedact } from "./constraint-errors.js"; diff --git a/examples/advanced-modeling/codegen/templates/drizzle-schema.ts b/examples/advanced-modeling/codegen/templates/drizzle-schema.ts index 026d00f5be..b5a79e86e0 100644 --- a/examples/advanced-modeling/codegen/templates/drizzle-schema.ts +++ b/examples/advanced-modeling/codegen/templates/drizzle-schema.ts @@ -590,16 +590,16 @@ function buildCompositeKeyCallback( return code`${primaryKeySym}({ columns: [${columnRefs}] })`; } -/** Build a JS-style object literal string (not JSON.stringify which uses quoted keys). - * Array values get `as const` appended so Drizzle's text(...,{ enum: [...] }) - * narrows the inferred column type to a literal union instead of bare `string`. */ -function inlineObjectLiteral(obj: Record): string { +/** Build a JS-style object literal string (not JSON.stringify, which quotes every key): + * `{ length: 200 }`, not `{ "length": 200 }`. A key that is not a bare identifier keeps + * its quotes. Array values get `as const` appended so Drizzle's text(...,{ enum: [...] }) + * narrows the inferred column type to a literal union instead of bare `string`. Shared by + * the table template and the existing-view declaration (`view-decl.ts`). */ +export function inlineObjectLiteral(obj: Record): string { const entries = Object.entries(obj).map(([k, v]) => { + const name = /^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k); const lit = JSON.stringify(v); - if (Array.isArray(v)) { - return `${k}: ${lit} as const`; - } - return `${k}: ${lit}`; + return Array.isArray(v) ? `${name}: ${lit} as const` : `${name}: ${lit}`; }); return `{ ${entries.join(", ")} }`; } diff --git a/examples/advanced-modeling/codegen/templates/filter-allowlist.ts b/examples/advanced-modeling/codegen/templates/filter-allowlist.ts index 5d1527373a..b8ef1b2bcd 100644 --- a/examples/advanced-modeling/codegen/templates/filter-allowlist.ts +++ b/examples/advanced-modeling/codegen/templates/filter-allowlist.ts @@ -93,24 +93,45 @@ const INTEGER_SUBTYPES = new Set([ * as UTC, the same rule the generated write schema stores it by. Scalar fields only: an * array field's filter value is not one element of the declared type. */ -function valueShape(f: MetaField): string { - if (f.resolvedIsArray()) return ""; - if (INTEGER_SUBTYPES.has(f.subType)) return ", integer: true as const"; +function valueShape(f: MetaField): FilterRuleValueShape { + if (f.resolvedIsArray()) return {}; + if (INTEGER_SUBTYPES.has(f.subType)) return { integer: true }; if (VALUE_FORMAT_SUBTYPES.has(f.subType)) { - const instant = f.subType === FIELD_SUBTYPE_TIMESTAMP && f.attr(FIELD_ATTR_LOCAL_TIME) !== true - ? ", instant: true as const" - : ""; - return `, format: ${JSON.stringify(f.subType)} as const${instant}`; + const instant = f.subType === FIELD_SUBTYPE_TIMESTAMP && f.attr(FIELD_ATTR_LOCAL_TIME) !== true; + return instant ? { format: f.subType, instant: true } : { format: f.subType }; } if (f.subType === FIELD_SUBTYPE_ENUM) { // Member SYMBOLS for string- and int-backed enums alike: an int-backed column's codec // maps the symbol to its integer when the value is bound. const members = enumValues(f); - if (members !== undefined && members.length > 0) { - return `, enumValues: [${members.map((m) => JSON.stringify(m)).join(", ")}] as const`; - } + if (members !== undefined && members.length > 0) return { enumValues: members }; } - return ""; + return {}; +} + +/** The optional members of a rule beyond `ops` / `subType` / `leadingWildcard`. */ +interface FilterRuleValueShape { + readonly dateValues?: true; + readonly format?: string; + readonly instant?: true; + readonly integer?: true; + readonly enumValues?: readonly string[]; +} + +/** + * One field's filter rule, as data: what `FilterAllowlist` carries for it. The + * runtime-ts `FilterFieldRule` shape, kept structural here so codegen does not depend on + * the runtime package. + */ +export interface FilterAllowlistRule extends FilterRuleValueShape { + readonly ops: readonly string[]; + readonly subType: "string" | "number" | "boolean" | "datetime"; + readonly leadingWildcard: false; +} + +/** One sortable field's rule, as data: what `SortAllowlist` carries for it. */ +export interface SortAllowlistRule { + readonly defaultOrder?: "asc" | "desc"; } function filterableFields(entity: MetaObject, exclude: string | undefined, ctx: RenderContext | undefined): MetaField[] { @@ -134,29 +155,49 @@ function filterableFields(entity: MetaObject, exclude: string | undefined, ctx: * normalized to `"string"` for sqlite/D1 at both config choke points, so no dialect * branching is needed here. Absent `ctx`, or in the default mode, output is unchanged. */ +export function filterAllowlistRules( + entity: MetaObject, + exclude?: string, + ctx?: RenderContext, +): ReadonlyArray { + return filterableFields(entity, exclude, ctx).map((f) => { + // opsForField, not opsForSubType — an int-backed field.enum (@intValueMap) + // stores as an integer, so `like` (a substring match) is not in its band. + const rule: FilterAllowlistRule = { + ops: opsForField(f), + subType: filterSubTypeFor(f.subType), + leadingWildcard: false, + // Only field.timestamp is governed by timestampMode — Drizzle types + // field.date / field.time as strings under every dialect. + ...(ctx?.timestampMode === "date" && f.subType === FIELD_SUBTYPE_TIMESTAMP ? { dateValues: true as const } : {}), + ...valueShape(f), + }; + return [f.name, rule] as const; + }); +} + +/** One rule as the generated allowlist spells it (members in a fixed order, `as const` on each). */ +function filterRuleLiteral(rule: FilterAllowlistRule): string { + const ops = rule.ops.map((o) => JSON.stringify(o)).join(", "); + let out = `{ ops: [${ops}] as const, subType: ${JSON.stringify(rule.subType)} as const, leadingWildcard: false`; + if (rule.dateValues) out += ", dateValues: true as const"; + if (rule.integer) out += ", integer: true as const"; + if (rule.format !== undefined) out += `, format: ${JSON.stringify(rule.format)} as const`; + if (rule.instant) out += ", instant: true as const"; + if (rule.enumValues !== undefined) out += `, enumValues: [${rule.enumValues.map((m) => JSON.stringify(m)).join(", ")}] as const`; + return `${out} }`; +} + export function renderFilterAllowlist(entity: MetaObject, exclude?: string, ctx?: RenderContext): Code { - const fields = filterableFields(entity, exclude, ctx); - if (fields.length === 0) { + const rules = filterAllowlistRules(entity, exclude, ctx); + if (rules.length === 0) { return code` import type { FilterAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; export const ${entity.name}FilterAllowlist = {} as const satisfies FilterAllowlist; `; } - const rows = fields - .map((f) => { - // opsForField, not opsForSubType — an int-backed field.enum (@intValueMap) - // stores as an integer, so `like` (a substring match) is not in its band. - const ops = opsForField(f).map((o) => JSON.stringify(o)).join(", "); - const sub = filterSubTypeFor(f.subType); - // Only field.timestamp is governed by timestampMode — Drizzle types - // field.date / field.time as strings under every dialect. - const dateValues = ctx?.timestampMode === "date" && f.subType === FIELD_SUBTYPE_TIMESTAMP - ? ", dateValues: true as const" - : ""; - return ` ${f.name}: { ops: [${ops}] as const, subType: ${JSON.stringify(sub)} as const, leadingWildcard: false${dateValues}${valueShape(f)} }`; - }) - .join(",\n"); + const rows = rules.map(([name, rule]) => ` ${name}: ${filterRuleLiteral(rule)}`).join(",\n"); return code` import type { FilterAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; @@ -166,34 +207,39 @@ ${rows} `; } -export function renderSortAllowlist(entity: MetaObject, exclude?: string, ctx?: RenderContext): Code { +/** The sortable fields and their rules, as data (what `SortAllowlist` carries). */ +export function sortAllowlistRules( + entity: MetaObject, + exclude?: string, + ctx?: RenderContext, +): ReadonlyArray { // Sortable = explicit @sortable === true, OR (no @sortable AND @filterable === true). - // @sortable: false explicitly opts out. - // Uses shared isSortableField predicate — must stay in sync with renderFilterType. - // `exclude` (FR-017): per-subtype TPH allowlists omit the discriminator. - // A credential is never sortable (isSortableField), nor a column a sibling subtype marks as one. + // @sortable: false explicitly opts out. A credential is never sortable, nor a column a + // sibling subtype marks as one. `exclude` (FR-017): per-subtype TPH allowlists omit the + // discriminator. const credentials = credentialFieldNames(entity, ctx?.loadedRoot); - const sortable = flatSurfaceFields(entity).filter((f) => isSortableField(f) && !credentials.has(f.name) && f.name !== exclude); - if (sortable.length === 0) { + return flatSurfaceFields(entity) + .filter((f) => isSortableField(f) && !credentials.has(f.name) && f.name !== exclude) + .map((f) => { + // The DECLARED order only — an undeclared field stays `{}` so the runtime's own + // `?? "asc"` remains the single place the fallback is spelled. + const defaultOrder = declaredSortDefaultOrder(f); + return [f.name, defaultOrder === undefined ? {} : { defaultOrder }] as const; + }); +} + +export function renderSortAllowlist(entity: MetaObject, exclude?: string, ctx?: RenderContext): Code { + const rules = sortAllowlistRules(entity, exclude, ctx); + if (rules.length === 0) { return code` import type { SortAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; export const ${entity.name}SortAllowlist = {} as const satisfies SortAllowlist; `; } - const rows = sortable - .map((f) => { - // The DECLARED order only — an undeclared field stays `{}` so the runtime's own - // `?? "asc"` remains the single place the fallback is spelled. Read through the - // shared resolver, never off the attr here, so this allowlist and the grid tier - // cannot answer one declaration two ways. - const defaultOrder = declaredSortDefaultOrder(f); - const rule = - defaultOrder === undefined - ? `{}` - : `{ defaultOrder: ${JSON.stringify(defaultOrder)} as const }`; - return ` ${f.name}: ${rule}`; - }) + const rows = rules + .map(([name, rule]) => + ` ${name}: ${rule.defaultOrder === undefined ? "{}" : `{ defaultOrder: ${JSON.stringify(rule.defaultOrder)} as const }`}`) .join(",\n"); return code` import type { SortAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; diff --git a/examples/advanced-modeling/codegen/templates/view-decl.ts b/examples/advanced-modeling/codegen/templates/view-decl.ts index 3dd02b2329..6f30828276 100644 --- a/examples/advanced-modeling/codegen/templates/view-decl.ts +++ b/examples/advanced-modeling/codegen/templates/view-decl.ts @@ -18,6 +18,7 @@ import { mapColumnType, DURATION_COLUMN_FN, type EnumIntCustomType } from "@meta import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; import { zodTypeFor } from "./field-meta.js"; +import { inlineObjectLiteral } from "./drizzle-schema.js"; import { columnExpr, type ObjectNames } from "@metaobjectsdev/codegen-ts/engine"; export interface ViewDeclOpts { @@ -111,7 +112,7 @@ function viewColumnLine( : imp(`${spec.fnName}@${spec.importModule}`); const optsArg = spec.fnOptions && Object.keys(spec.fnOptions).length > 0 - ? `, ${optionsLiteral(spec.fnOptions)}` + ? `, ${inlineObjectLiteral(spec.fnOptions)}` : ""; // #204 — of the table modifiers, only `.array()` (postgres native array element // typing) and `.notNull()` (shapes the SELECT type) carry to an existing view; @@ -252,12 +253,3 @@ export function renderViewReadZodObject(fields: readonly MetaField[], opts: View ${joinCode(lines, { on: ",\n" })} })`; } - -/** A column's options as a JS object literal: `{ length: 200 }`, not JSON's `{ "length": 200 }`. */ -function optionsLiteral(options: Record): string { - const entries = Object.entries(options).map(([key, value]) => { - const name = /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key); - return `${name}: ${JSON.stringify(value)}`; - }); - return `{ ${entries.join(", ")} }`; -} diff --git a/examples/dynamic-grid/test/no-sql-from-request.test.ts b/examples/dynamic-grid/test/no-sql-from-request.test.ts index 990affbd53..f221fb1880 100644 --- a/examples/dynamic-grid/test/no-sql-from-request.test.ts +++ b/examples/dynamic-grid/test/no-sql-from-request.test.ts @@ -27,8 +27,12 @@ beforeEach(() => { statements.length = 0; }); -/** A marker no schema name contains, so finding it in SQL text can only mean it was spliced in. */ -const MARKER = "zz_marker_zz"; +/** + * A marker no schema name contains, so finding it in SQL text can only mean it was spliced in. + * It holds no LIKE or GLOB wildcard (`%`, `_`, `*`, `?`, `[`): `like` is lowered to `glob` on + * SQLite and rewrites those, so a wildcard would change the bound value. + */ +const MARKER = "zzmarkerzz"; const ATTACK = `${MARKER}'; DROP TABLE customers; --`; const q = encodeURIComponent; @@ -54,9 +58,15 @@ test("a filter value is bound, never spliced into the statement", async () => { test("like and in values are bound too", async () => { expect((await demo.get(`/api/customers?filter[name][like]=${q(ATTACK)}`)).status).toBe(200); + const likeStatements = statements.splice(0); expect((await demo.get(`/api/customers?filter[name][in]=${q(`a,${ATTACK}`)}`)).status).toBe(200); - expectNotInSql(); - expect(statements.filter((s) => s.parameters.some((p) => typeof p === "string" && p.includes(MARKER))).length).toBe(2); + const inStatements = statements.splice(0); + for (const sent of [likeStatements, inStatements]) { + for (const statement of sent) expect(statement.sql).not.toContain(MARKER); + expect(sent.filter((s) => s.parameters.some((p) => typeof p === "string" && p.includes(MARKER))).length).toBe(1); + // The bound value reaches the driver unchanged. + expect(sent.some((s) => s.parameters.some((p) => p === ATTACK))).toBe(true); + } }); test("a field name the model does not declare is refused before any statement is sent", async () => { diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/filter-allowlist.ts b/examples/showcase/codegen/runtime/drizzle-fastify/filter-allowlist.ts index e349d9cf03..53003a16de 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/filter-allowlist.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/filter-allowlist.ts @@ -124,5 +124,5 @@ export function sortOrderSpec( // The `?? "asc"` here is the ONLY place TypeScript's runtime spells the fallback. An // allowlist artifact carries declarations and nothing else — baking the default into // it would put the answer in two places per port, which is how a port drifts. - return supplied ?? allowlist[field]?.defaultOrder ?? "asc"; + return supplied ?? (Object.hasOwn(allowlist, field) ? allowlist[field]?.defaultOrder : undefined) ?? "asc"; } diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/filter-parser.ts b/examples/showcase/codegen/runtime/drizzle-fastify/filter-parser.ts index 534c2f7c3e..d8befb4565 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/filter-parser.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/filter-parser.ts @@ -1,25 +1,23 @@ import { is, Column, SQL as DrizzleSQL, - eq, ne, gt, gte, lt, lte, inArray, like, ilike, isNull, not, and, or, asc, desc, sql, + eq, ne, gt, gte, lt, lte, inArray, like, ilike, isNull, not, and, or, sql, + asc, desc, type SQL, type SQLWrapper, } from "drizzle-orm"; import type { SqlDialect } from "../sql-dialect.js"; -import type { FilterAllowlist, FilterOp, FilterFieldRule, SortAllowlist } from "./filter-allowlist.js"; -import { sortOrderSpec } from "./filter-allowlist.js"; -import { FilterParseError, parsePageBound, SORT_EXPECTED } from "./list-params.js"; +import type { FilterAllowlist, FilterFieldRule, SortAllowlist } from "./filter-allowlist.js"; +import { FilterParseError } from "./list-params.js"; +import { likePatternToGlob, parseListQuery, type FilterLeaf, type FilterNode, type FilterScalar, type ListSearch } from "./list-query.js"; // Re-exported so existing importers keep one door; the definitions live in the -// drizzle-free list-params module, which the ObjectManager Fastify mount also uses. +// drizzle-free list-params and list-query modules, which the ObjectManager Fastify mount also uses. export { FilterParseError, parsePageBound, pageLimit, ERROR_CODE_LIMIT_TOO_LARGE, type PageSize, PAGINATION_EXPECTED, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, parseReportPage, SORT_EXPECTED } from "./list-params.js"; -import { - ANY_TEMPORAL_EXPECTED, FORMAT_EXPECTED, PLUS_OFFSET_HINT, - looksLikeUnencodedPlusOffset, matchesAnyTemporal, matchesFormat, utcIsoIfZoned, utcIsoInstant, -} from "./filter-value-format.js"; -import { FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_TIMESTAMP } from "@metaobjectsdev/metadata"; -import { canonicalDecimal } from "../decimal-wire.js"; -import { - DURATION_MICROS_MAX, DURATION_MICROS_MIN, durationToStoredMicros, formatPostgresInterval, parseDurationLiteral, -} from "../duration-wire.js"; +export { + likePatternToGlob, parseListQuery, parseListQueryString, rawQueryOf, searchFields, DEFAULT_MAX_IN_LIST, DEFAULT_MAX_NESTING, + type FilterLeaf, type FilterNode, type FilterScalar, type ListQuery, type ListSearch, type ListSort, type ParseListQueryOpts, +} from "./list-query.js"; +import { FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_DURATION } from "@metaobjectsdev/metadata"; +import { durationToStoredMicros, formatPostgresInterval, parseDurationLiteral } from "../duration-wire.js"; // biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user's Drizzle table type AnyTable = any; @@ -39,56 +37,10 @@ export interface ParseFilterResult { orderBy?: SQLWrapper[]; limit?: number; offset?: number; - /** Search predicate — OR(like('%term%')) across @filterable string fields. */ + /** Search predicate — OR(case-insensitive '%term%') across @filterable text fields. */ searchWhere?: SQL; } - -const DEFAULT_MAX_NESTING = 5; -const DEFAULT_MAX_IN_LIST = 100; - -/** Top-level list-query parameters this parser (or the mount around it) reads. A - * filterable field that happens to share one of these names is addressed only through - * `filter[]`, so the bare-field check below never claims them. */ -const RESERVED_LIST_PARAMS: ReadonlySet = new Set([ - "filter", "sort", "limit", "offset", "search", "withCount", -]); - -/** - * `?priority=low` on a list whose allowlist has `priority` is almost always a caller who - * meant `?filter[priority][eq]=low` — and silently ignoring it returns EVERY row, which - * reads as "the filter matched everything". Refuse it, naming the syntax that works. - * - * A bare name that is a field of the entity but NOT on the filter allowlist is refused - * too — the caller plainly meant that field — saying it is not filterable and listing - * the fields that are. Any other unknown parameter — a cache-buster, a tracking tag, a - * param some proxy appends — is left alone, as before. - * TS-only (the other ports ignore unknown parameters): see docs/features/api-contract.md, - * "TS-only filter extensions". - */ -function rejectBareFieldParams(query: Record, allowlist: FilterAllowlist, table: AnyTable): void { - for (const [key, value] of Object.entries(query)) { - if (RESERVED_LIST_PARAMS.has(key)) continue; - if (Object.hasOwn(allowlist, key)) { - const shown = typeof value === "string" ? value : ""; - throw new FilterParseError( - "filter.bare_field", - `"${key}" is a filterable field, but a bare ?${key}= parameter is not a filter. Use filter[${key}][eq]=${shown}.`, - { field: key, expected: `filter[${key}][eq]=${shown}` }, - ); - } - if (isEntityColumn(table, key)) { - const allowed = Object.keys(allowlist); - throw new FilterParseError( - "filter.bare_field", - `"${key}" is a field of this entity, but it is not @filterable, so it cannot be filtered on` + - (allowed.length > 0 ? ` (filterable: ${allowed.join(", ")}).` : " (no field is filterable)."), - { field: key, filterable: false, expected: `a filterable field — "${key}" is not @filterable`, allowed }, - ); - } - } -} - /** Is `key` one of the table's (or view's) own columns? A Drizzle table exposes each * column as a property keyed by its field name; anything else found there (a function, * a symbol-backed config, a proxy that throws on an unknown key) is not a field. */ @@ -102,382 +54,122 @@ function isEntityColumn(table: AnyTable, key: string): boolean { } } +/** A Drizzle column's own enum members (`text(..., { enum })`, `pgEnum`), if it has them. */ +function columnEnumValues(col: unknown): readonly string[] | undefined { + const v = (col as { enumValues?: unknown } | null | undefined)?.enumValues; + return Array.isArray(v) && v.length > 0 && v.every((m) => typeof m === "string") ? (v as string[]) : undefined; +} +/** + * Parse a list query (`parseListQuery`, which raises every refusal) and compile it to + * Drizzle for `opts.table` on `opts.dialect`. + */ export function parseFilterParams(opts: ParseFilterOpts): ParseFilterResult { - rejectBareFieldParams(opts.query, opts.allowlist, opts.table); + const table = opts.table; + const parsed = parseListQuery({ + query: opts.query, + allowlist: opts.allowlist, + sortAllowlist: opts.sortAllowlist, + isField: (name) => isEntityColumn(table, name), + hasColumn: (name) => table[name] !== undefined, + enumValuesOf: (name) => columnEnumValues(table[name]), + ...(opts.maxNesting !== undefined ? { maxNesting: opts.maxNesting } : {}), + ...(opts.maxInListSize !== undefined ? { maxInListSize: opts.maxInListSize } : {}), + }); const result: ParseFilterResult = {}; - - const limit = parsePageBound(opts.query, "limit"); - if (limit !== undefined) result.limit = limit; - const offset = parsePageBound(opts.query, "offset"); - if (offset !== undefined) result.offset = offset; - - if (opts.query.filter && typeof opts.query.filter === "object") { - const where = parseNode( - opts.query.filter as Record, - opts.table, opts.allowlist, opts.dialect, - opts.maxNesting ?? DEFAULT_MAX_NESTING, - opts.maxInListSize ?? DEFAULT_MAX_IN_LIST, - 0, - ); - if (where) result.where = where; - } - - if (typeof opts.query.sort === "string") { - result.orderBy = parseSort(opts.query.sort, opts.table, opts.sortAllowlist, opts.dialect); - } - - if (typeof opts.query.search === "string" && opts.query.search !== "") { - const term = `%${opts.query.search}%`; - const stringCols = Object.entries(opts.allowlist) - // A rule with a `format` (uuid, …) is a typed column on the wire as a string, not - // text: ILIKE on a Postgres uuid column is "operator does not exist" (a 500). - .filter(([, rule]) => { - const r = rule as FilterFieldRule; - return r.subType === "string" && r.format === undefined; - }) - .map(([field]) => opts.table[field]); - if (stringCols.length > 0) { - // `?search` is a TS-only extension (docs/features/api-contract.md) and is - // deliberately case-INSENSITIVE — it is a human search box, not the - // contract's `like` operator (which is case-sensitive SQL LIKE, ADR-0049). - // Postgres uses ILIKE; SQLite's native LIKE folds ASCII case by default, - // which is the intended behavior here. MySQL's LIKE follows the column's - // collation, which is case-insensitive by default and case-sensitive on a - // `_bin` column, so it folds both sides explicitly. - const parts = stringCols.map((col) => - opts.dialect === "postgres" ? ilike(col, term) - : opts.dialect === "mysql" ? sql`LOWER(${col}) LIKE LOWER(${term})` - : like(col, term)); - // or() is defined as returning SQL | undefined but will always return - // SQL when given a non-empty array. parts[0] is always defined here - // because stringCols.length > 0 guarantees at least one element. - // biome-ignore lint/style/noNonNullAssertion: parts is guaranteed non-empty - result.searchWhere = (parts.length === 1 ? parts[0] : or(...parts)) as SQL; - } - } - + if (parsed.limit !== undefined) result.limit = parsed.limit; + if (parsed.offset !== undefined) result.offset = parsed.offset; + if (parsed.filter !== undefined) result.where = compileFilterNode(parsed.filter, table, opts.allowlist, opts.dialect); + if (parsed.sort !== undefined) result.orderBy = nullsAsLargest(table[parsed.sort.field], parsed.sort.order, opts.dialect); + if (parsed.search !== undefined) result.searchWhere = compileSearch(parsed.search, table, opts.dialect); return result; } -function parseNode( - node: Record, - table: AnyTable, - allowlist: FilterAllowlist, - dialect: SqlDialect, - maxNesting: number, - maxInList: number, - depth: number, -): SQL | undefined { - if (depth > maxNesting) { - throw new FilterParseError("filter.nesting_too_deep", `Filter nesting depth exceeds limit (${maxNesting}).`, { limit: maxNesting }); - } - const parts: SQL[] = []; - for (const [key, value] of Object.entries(node)) { - if (key === "or") { - const subs = ensureArray(value, "or").map((sub) => - parseNode(sub as Record, table, allowlist, dialect, maxNesting, maxInList, depth + 1) - ).filter((s): s is SQL => !!s); - if (subs.length > 0) parts.push(or(...subs)!); - } else if (key === "and") { - const subs = ensureArray(value, "and").map((sub) => - parseNode(sub as Record, table, allowlist, dialect, maxNesting, maxInList, depth + 1) - ).filter((s): s is SQL => !!s); - if (subs.length > 0) parts.push(and(...subs)!); - } else { - // key is a field name - const rule = allowlist[key]; - if (!rule) { - throw new FilterParseError("filter.unknown_field", `Unknown filter field "${key}".`, { field: key, allowed: Object.keys(allowlist) }); - } - const col = table[key]; - if (col === undefined) { - throw new FilterParseError("filter.unknown_field", `Table has no column for field "${key}".`, { field: key }); - } - if (typeof value === "object" && value !== null && !Array.isArray(value)) { - for (const [opKey, opValue] of Object.entries(value)) { - const expr = compileOp(col, rule, key, opKey, opValue, dialect, maxInList); - if (expr) parts.push(expr); - } - } else { - // Bare value = eq sugar - const expr = compileOp(col, rule, key, "eq", value, dialect, maxInList); - if (expr) parts.push(expr); - } - } - } - if (parts.length === 0) return undefined; - if (parts.length === 1) return parts[0]; - return and(...parts); +/** Compile a parsed filter tree to a Drizzle condition over `table`. */ +export function compileFilterNode(node: FilterNode, table: AnyTable, allowlist: FilterAllowlist, dialect: SqlDialect): SQL { + if ("and" in node) return and(...node.and.map((n) => compileFilterNode(n, table, allowlist, dialect))) as SQL; + if ("or" in node) return or(...node.or.map((n) => compileFilterNode(n, table, allowlist, dialect))) as SQL; + return compileLeaf(node, table[node.field], allowlist[node.field] as FilterFieldRule, dialect); } -function compileOp( - col: unknown, - rule: FilterFieldRule, - field: string, - op: string, - value: unknown, - dialect: SqlDialect, - maxInList: number, -): SQL | undefined { - if (!rule.ops.includes(op as FilterOp)) { - throw new FilterParseError("filter.unsupported_op", `Op "${op}" not supported for field "${field}".`, { field, op, allowed: rule.ops }); - } - switch (op as FilterOp) { - case "eq": return eq(col as any, coerce(value, rule, col, field, op, dialect)); - case "ne": return ne(col as any, coerce(value, rule, col, field, op, dialect)); - case "gt": return gt(col as any, coerce(value, rule, col, field, op, dialect)); - case "gte": return gte(col as any, coerce(value, rule, col, field, op, dialect)); - case "lt": return lt(col as any, coerce(value, rule, col, field, op, dialect)); - case "lte": return lte(col as any, coerce(value, rule, col, field, op, dialect)); - case "in": { - const list = String(value).split(",").map((v) => coerce(v.trim(), rule, col, field, op, dialect)); - if (list.length > maxInList) { - throw new FilterParseError("filter.in_too_large", `In-list size ${list.length} exceeds limit ${maxInList}.`, { field, limit: maxInList }); - } - return inArray(col as any, list); - } +/** + * `?search` is deliberately case-INSENSITIVE — a human search box, not the contract's `like` + * operator (case-sensitive SQL LIKE, ADR-0049). Postgres uses ILIKE; SQLite's native LIKE + * folds ASCII case, which is the intended behavior here. MySQL's LIKE follows the column's + * collation (case-insensitive by default, case-sensitive on a `_bin` column), so it folds + * both sides explicitly. + */ +function compileSearch(search: ListSearch, table: AnyTable, dialect: SqlDialect): SQL { + const term = `%${search.term}%`; + const parts = search.fields.map((field) => { + const col = table[field]; + return dialect === "postgres" ? ilike(col, term) + : dialect === "mysql" ? sql`LOWER(${col}) LIKE LOWER(${term})` + : like(col, term); + }); + return (parts.length === 1 ? parts[0] : or(...parts)) as SQL; +} + +function compileLeaf(leaf: FilterLeaf, col: unknown, rule: FilterFieldRule, dialect: SqlDialect): SQL { + // biome-ignore lint/suspicious/noExplicitAny: a column of the adopter's Drizzle table + const c = col as any; + const bind = (v: FilterScalar): unknown => bindOperand(v, rule, leaf, dialect); + switch (leaf.op) { + case "eq": return eq(c, bind(leaf.value as FilterScalar)); + case "ne": return ne(c, bind(leaf.value as FilterScalar)); + case "gt": return gt(c, bind(leaf.value as FilterScalar)); + case "gte": return gte(c, bind(leaf.value as FilterScalar)); + case "lt": return lt(c, bind(leaf.value as FilterScalar)); + case "lte": return lte(c, bind(leaf.value as FilterScalar)); + case "in": return inArray(c, (leaf.value as readonly FilterScalar[]).map(bind)); case "like": { - const s = String(value); - if (s.startsWith("%") && !rule.leadingWildcard) { - throw new FilterParseError("filter.leading_wildcard_disallowed", `Leading wildcard not allowed for field "${field}".`, { field }); - } - // Cross-port contract (ADR-0049): `like` is case-SENSITIVE SQL LIKE — - // verbatim author-supplied pattern, `%`/`_` wildcards. Postgres LIKE is - // already case-sensitive. SQLite's built-in LIKE folds ASCII case by - // default (and `PRAGMA case_sensitive_like` is connection-global on a - // consumer-owned connection), so the sqlite branch lowers to GLOB with - // an exactly-translated pattern instead. - // MySQL's LIKE follows the column's collation, which is case-INSENSITIVE by - // default, so the pattern carries an explicit binary collation. + const s = leaf.value as string; + // Cross-port contract (ADR-0049): `like` is case-SENSITIVE SQL LIKE — verbatim + // pattern, `%`/`_` wildcards. Postgres LIKE already is. SQLite's built-in LIKE folds + // ASCII case by default (and `PRAGMA case_sensitive_like` is connection-global on a + // consumer-owned connection), so sqlite lowers to GLOB with an exactly-translated + // pattern. MySQL's LIKE follows the column's collation, so the pattern carries an + // explicit binary collation. return dialect === "postgres" - ? like(col as any, s) + ? like(c, s) : dialect === "mysql" - ? sql`${col} LIKE ${s} COLLATE utf8mb4_bin` - : sql`${col} GLOB ${likePatternToGlob(s)}`; - } - case "isNull": { - // isNull's value is always coerced as boolean (true/false), regardless of the - // field's declared subType — the operator is "is the value null?", not "is X - // equal to null?". Field subtype is irrelevant. - const b = coerceAs(value, "boolean", field, op) as boolean; - return b ? isNull(col as any) : not(isNull(col as any)); + ? sql`${c} LIKE ${s} COLLATE utf8mb4_bin` + : sql`${c} GLOB ${likePatternToGlob(s)}`; } + case "isNull": + return leaf.value === true ? isNull(c) : not(isNull(c)); } } /** - * Translate a SQL LIKE pattern into an equivalent SQLite GLOB pattern: - * `%` → `*`, `_` → `?`, and GLOB's own metacharacters (`*`, `?`, `[`) are - * wrapped in single-character classes so they match literally. `]` is only - * special inside a class, so it passes through. GLOB is case-sensitive, - * which is why the sqlite `like` branch uses it (ADR-0049) — SQLite's - * native LIKE folds ASCII case by default. + * Spell a checked operand the way the column binds it. A decimal operand is exact text + * (ADR-0019 Amendment 1, W2); MySQL compares a DECIMAL column with a string operand as + * DOUBLES, so there it is cast to a wide DECIMAL, and SQLite / D1 hold a decimal as a double + * (W4) and order every number before any text, so there it is bound as the number it is. A + * duration is the microsecond integer on SQLite / D1 / MySQL and the interval spelling on + * Postgres (which refuses a signed ISO-8601 duration). A timestamp on a column emitted under + * `timestampMode: "date"` (`dateValues`) binds a real `Date`: Drizzle calls `toISOString()` + * on it. */ -export function likePatternToGlob(pattern: string): string { - let out = ""; - for (const ch of pattern) { - if (ch === "%") out += "*"; - else if (ch === "_") out += "?"; - else if (ch === "*") out += "[*]"; - else if (ch === "?") out += "[?]"; - else if (ch === "[") out += "[[]"; - else out += ch; - } - return out; -} - -function invalidValue( - field: string, - op: string, - s: string, - expected: string, - extra: Record = {}, -): FilterParseError { - const hint = typeof extra["hint"] === "string" ? ` Hint: ${extra["hint"]}.` : ""; - return new FilterParseError( - "filter.invalid_value", - `Field "${field}" op "${op}" requires ${expected}, got "${s}".${hint}`, - { field, op, expected, ...extra }, - ); -} - -/** A Drizzle column's own enum members (`text(..., { enum })`, `pgEnum`), if it has them. */ -function columnEnumValues(col: unknown): readonly string[] | undefined { - const v = (col as { enumValues?: unknown } | null | undefined)?.enumValues; - return Array.isArray(v) && v.length > 0 && v.every((m) => typeof m === "string") ? (v as string[]) : undefined; -} - -/** - * Refuse a value that cannot be the field's type BEFORE it is bound. Without this a - * malformed date on SQLite compared as text and silently matched nothing (200 `[]`), - * and on Postgres the driver refused the cast (a 500) — either way the caller could not - * tell a typo from an empty result. The envelope is the cross-port `invalid_filter_value`, - * carrying `op` and `expected` as the number/boolean checks already did. - */ -function assertWellFormed(s: string, rule: FilterFieldRule, col: unknown, field: string, op: string): void { - const members = rule.enumValues ?? columnEnumValues(col); - if (members !== undefined && !members.includes(s)) { - throw invalidValue(field, op, s, `one of: ${members.join(", ")}`, { allowed: [...members] }); - } - if (rule.format !== undefined) { - if (!matchesFormat(rule.format, s)) { - // `filter[dueAt][lt]=2026-10-06T00:00:00+00:00` sent unencoded arrives with a space - // where the `+` was; "expected timestamp" alone does not say why a valid-looking - // value failed, so the answer names the fix. - const hint = rule.format === FIELD_SUBTYPE_TIMESTAMP && looksLikeUnencodedPlusOffset(s) - ? { hint: PLUS_OFFSET_HINT } - : {}; - throw invalidValue(field, op, s, FORMAT_EXPECTED[rule.format], hint); - } - } else if (rule.subType === "datetime" && !matchesAnyTemporal(s)) { - throw invalidValue(field, op, s, ANY_TEMPORAL_EXPECTED); - } -} - -/** Check a comparison value against the field's rule, then coerce it for binding. */ -function coerce(value: unknown, rule: FilterFieldRule, col: unknown, field: string, op: string, dialect: SqlDialect): unknown { - if (value === null || value === undefined) return null; - const s = typeof value === "string" ? value : String(value); - assertWellFormed(s, rule, col, field, op); - // A decimal operand is exact text, never a number (ADR-0019 Amendment 1, W2): parsed with - // the JSON-number grammar and bound as its canonical string. MySQL compares a DECIMAL column - // with a string operand as DOUBLES, so there the operand is cast to a wide DECIMAL first. - // SQLite and D1 hold a decimal as a double (W4) and order every number before any text, so a - // text operand against a computed column (a view's sum or average has no NUMERIC affinity) - // would compare false in the wrong direction: the operand is bound as the number it is, exact - // to the 15 digits W4 promises. +function bindOperand(v: FilterScalar, rule: FilterFieldRule, leaf: FilterLeaf, dialect: SqlDialect): unknown { if (rule.format === FIELD_SUBTYPE_DECIMAL) { - const canonical = canonicalDecimal(s) as string; - if (dialect === "mysql") return sql`CAST(${canonical} AS DECIMAL(65,30))`; - return dialect === "sqlite" ? Number(canonical) : canonical; + if (dialect === "mysql") return sql`CAST(${v} AS DECIMAL(65,30))`; + return dialect === "sqlite" ? Number(v) : v; } - // A duration bound is spelled the way the column stores it: the microsecond integer on SQLite / - // D1 / MySQL, the interval spelling on Postgres (which refuses a signed ISO-8601 duration). Both - // compare and order as the span does. if (rule.format === FIELD_SUBTYPE_DURATION) { - const micros = parseDurationLiteral(s) as bigint; - // A well-formed span past 64 bits of microseconds is no stored value on any database, so it is - // a bad operand (400), not an error out of the binder. - if (micros > DURATION_MICROS_MAX || micros < DURATION_MICROS_MIN) throw invalidValue(field, op, s, DURATION_IN_RANGE); + const micros = parseDurationLiteral(String(v)) as bigint; return dialect === "sqlite" || dialect === "mysql" ? durationToStoredMicros(micros) : formatPostgresInterval(micros); } - // A timestamp bound is compared in the same UTC spelling the generated schemas store: - // on SQLite/D1 the column is TEXT and compares as text. An instant field (`instant`, i.e. - // not @localTime) reads a zoneless or date-only bound as UTC, as its write schema does — - // also before a Date-bound (`dateValues`) column's `new Date(...)`, which would otherwise - // read a zoneless string in the SERVER's local zone. Without `instant`, only a zoned - // bound is rewritten, and a Date-bound column parses the value itself. - if (rule.format === FIELD_SUBTYPE_TIMESTAMP) { - const bound = rule.instant === true ? utcIsoInstant(s) : rule.dateValues === true ? s : utcIsoIfZoned(s); - return coerceAs(bound, rule.subType, field, op, rule.dateValues); - } - const coerced = coerceAs(s, rule.subType, field, op, rule.dateValues); - // field.int / field.long / field.currency: a fractional bound is not a value of the field. - if (rule.integer === true && typeof coerced === "number" && !Number.isInteger(coerced)) { - throw invalidValue(field, op, s, INTEGER_EXPECTED); - } - return coerced; -} - -/** `expected` for a non-whole bound on an integer-valued field (`integer: true`). */ -const INTEGER_EXPECTED = "integer (a whole number)"; -const DURATION_IN_RANGE = "duration within the 64-bit microsecond range"; - -function coerceAs(value: unknown, subType: string, field: string, op: string, dateValues?: boolean): unknown { - if (value === null || value === undefined) return null; - const s = typeof value === "string" ? value : String(value); - switch (subType) { - case "string": return s; - case "boolean": { - if (s === "true" || s === "1") return true; - if (s === "false" || s === "0") return false; - throw new FilterParseError("filter.invalid_value", `Field "${field}" op "${op}" requires boolean, got "${s}".`, { field, op, expected: "boolean" }); - } - case "number": { - // `Number("")` and `Number(" ")` are 0 — an empty bound is not the number zero. - const n = s.trim() === "" ? Number.NaN : Number(s); - if (!Number.isFinite(n)) { - throw new FilterParseError("filter.invalid_value", `Field "${field}" op "${op}" requires number, got "${s}".`, { field, op, expected: "number" }); - } - return n; + if (rule.subType === "datetime" && rule.dateValues === true) { + const d = new Date(String(v)); + // `new Date("garbage")` is an Invalid Date rather than a throw; binding one would emit + // `NaN`-shaped SQL. + if (Number.isNaN(d.getTime())) { + throw new FilterParseError("filter.invalid_value", `Field "${leaf.field}" op "${leaf.op}" requires a date, got "${String(v)}".`, { field: leaf.field, op: leaf.op, expected: "date" }); } - // Under codegen's Postgres-only `timestampMode: "date"` the Drizzle column is - // Date-typed and calls `value.toISOString()` on any bound value, so passing the - // raw qs string through threw `TypeError: value.toISOString is not a function` - // for every op except isNull. The generated allowlist now carries `dateValues` - // for exactly those columns (see FilterFieldRule), so the value is bound as a - // real Date. In the default "string" mode — and for field.date / field.time, - // which Drizzle types as strings under every dialect — the flag is absent and - // the value stays a string, unchanged. - case "datetime": { - if (dateValues !== true) return s; - const d = new Date(s); - // `new Date("garbage")` yields an Invalid Date rather than throwing; binding - // one would emit `NaN`-shaped SQL. Reject at the boundary, matching how the - // number and boolean cases report a malformed value. - if (Number.isNaN(d.getTime())) { - throw new FilterParseError("filter.invalid_value", `Field "${field}" op "${op}" requires a date, got "${s}".`, { field, op, expected: "date" }); - } - return d; - } - default: return s; - } -} - -function ensureArray(v: unknown, key: string): unknown[] { - if (Array.isArray(v)) return v; - if (v && typeof v === "object") { - // qs.parse may produce { "0": ..., "1": ... } shape for filter[or][0]... - return Object.values(v); - } - // Defensive — qs.parse normally produces an object/array; this branch is - // only reachable if a caller hand-constructs a malformed query object. - // - // `field` (not `key`) because this maps to the cross-port `invalid_filter_value` - // envelope, which REQUIRES `field` naming the offending filter key — here the - // `or`/`and` connector that was handed a non-array. - throw new FilterParseError("filter.invalid_value", `Expected array for "${key}".`, { field: key }); -} - -function parseSort(spec: string, table: AnyTable, sortAllowlist: SortAllowlist, dialect: SqlDialect | undefined): SQLWrapper[] { - const colonIdx = spec.indexOf(":"); - const field = colonIdx === -1 ? spec : spec.slice(0, colonIdx); - if (!sortAllowlist[field]) { - throw new FilterParseError( - "sort.unknown_field", - `Unknown sort field "${field}". The syntax is ${SORT_EXPECTED}.`, - { field, expected: SORT_EXPECTED, allowed: Object.keys(sortAllowlist) }, - ); - } - // `?sort=field` with no `:order` takes the field's DECLARED default order. - // - // This is the read side of `@sortableDefaultOrder`, and until now there was none. - // The attribute was authored by an adopter, carried through the loader, and emitted - // into the generated `SortAllowlist` as `{ defaultOrder: "desc" }` — and then - // nothing read it back. One door in, no door out: the adopter authored a promise the - // product never kept, and every unqualified sort came back ascending regardless. - // - // Scoped deliberately to "field named, order omitted". Applying it when `?sort` is - // ABSENT ENTIRELY would give every endpoint a default ordering it does not have - // today — a behaviour change for every consumer, to honour an attribute about how a - // FIELD sorts. The declaration says which way this column runs when you do not say; - // it does not say which column to sort by. - const orderRaw = sortOrderSpec( - sortAllowlist, - field, - colonIdx === -1 ? undefined : spec.slice(colonIdx + 1), - ); - const order = orderRaw.toLowerCase(); - if (order !== "asc" && order !== "desc") { - throw new FilterParseError( - "sort.invalid_order", - `Sort order must be asc|desc, got "${orderRaw}". The syntax is ${SORT_EXPECTED}.`, - { field, expected: SORT_EXPECTED, allowed: Object.keys(sortAllowlist) }, - ); + return d; } - const col = table[field]; - return nullsAsLargest(col as any, order, dialect); + return v; } /** diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/index.ts b/examples/showcase/codegen/runtime/drizzle-fastify/index.ts index 9eb84fd2a9..225721b86a 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/index.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/index.ts @@ -23,7 +23,7 @@ import type { FastifyInstance, RouteShorthandOptions } from "fastify"; import { classifyConstraintError, RedactedDatabaseError, logAndRedact } from "../constraint-errors.js"; import type { ZodTypeAny } from "zod"; import { eq, count, and, asc } from "drizzle-orm"; -import qs from "qs"; +import { parseListQueryString } from "./list-query.js"; import type { FilterAllowlist, SortAllowlist } from "./filter-allowlist.js"; export type { FilterAllowlist, SortAllowlist } from "./filter-allowlist.js"; import { parseFilterParams, parsePageBound, pageLimit, FilterParseError, type PageSize } from "./filter-parser.js"; @@ -35,6 +35,10 @@ import { withContractErrorHandler } from "./route-error-handler.js"; import { validationErrorBody } from "../route-errors.js"; export { isTruthyFlag, contractErrorCode, parseId, coerceIdForColumn } from "./util.js"; export { pageLimit, ERROR_CODE_LIMIT_TOO_LARGE, type PageSize } from "./list-params.js"; +export { + parseListQuery, parseListQueryString, rawQueryOf, FilterParseError, + type FilterNode, type ListQuery, type ParseListQueryOpts, +} from "./filter-parser.js"; export { ERROR_CODE_UNKNOWN_FIELDS, unknownBodyKeys } from "../wire-format.js"; export { timestampWire, canonicalTimestamp } from "../timestamp-wire.js"; export { decimalWire, withDecimals, decimalToNative, canonicalDecimal, parseDecimalInput, parseDecimalOperand } from "../decimal-wire.js"; @@ -210,7 +214,7 @@ export function mountListRoute(opts: VerbOptions): void { const rawSearch = req.raw.url?.includes("?") ? req.raw.url.slice(req.raw.url.indexOf("?") + 1) : ""; - const qsParsed = qs.parse(rawSearch) as Record; + const qsParsed = parseListQueryString(rawSearch); const withCount = isTruthyFlag(qsParsed.withCount); // FR-017 TPH: when subtype-scoped, AND the discriminator predicate into diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/list-params.ts b/examples/showcase/codegen/runtime/drizzle-fastify/list-params.ts index f8499489b1..1a1bdc3412 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/list-params.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/list-params.ts @@ -27,9 +27,9 @@ export const PAGINATION_EXPECTED = "a non-negative integer (0 or more)"; * Read `?limit=` / `?offset=` as a non-negative integer, or refuse it. Before, a value * that was not a finite number (`?limit=abc`) was dropped — every row came back — and a * negative or fractional one reached SQL. `max` is the ceiling a mount clamps to, when it - * has one: a bound above it is refused rather than silently lowered. TS-only (no corpus - * scenario sends a malformed page bound): see docs/features/api-contract.md, "TS-only - * error responses". + * has one: a bound above it is refused rather than silently lowered. Part of the REST + * contract (docs/features/api-contract.md, "Error responses for a bad request or a failed + * write"), pinned by `list-query/pagination-invalid-value` and `report/bad-page-bound`. */ export function parsePageBound( query: Record, diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/list-query.ts b/examples/showcase/codegen/runtime/drizzle-fastify/list-query.ts new file mode 100644 index 0000000000..05c4fd2c20 --- /dev/null +++ b/examples/showcase/codegen/runtime/drizzle-fastify/list-query.ts @@ -0,0 +1,385 @@ +/** + * The list query a REST list route reads, parsed into a port-neutral form BEFORE any query + * library sees it: a filter tree, a search, a sort, a page. Every refusal of the REST standard + * is raised here (`docs/features/api-contract.md`, "List handling"), so the Drizzle mounts and + * the ObjectManager mount refuse a request identically and differ only in how they run the + * tree. Deliberately free of drizzle-orm (an OPTIONAL peer), like `list-params.ts`. + * + * `fixtures/list-query-conformance/` pins this function's answers — a query string and a + * field list in, a tree or a named error out — for every port. + */ + +import qs from "qs"; +import { FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_TIMESTAMP } from "@metaobjectsdev/metadata"; +import type { FilterAllowlist, FilterFieldRule, FilterOp, SortAllowlist } from "./filter-allowlist.js"; +import { sortOrderSpec } from "./filter-allowlist.js"; +import { FilterParseError, parsePageBound, SORT_EXPECTED } from "./list-params.js"; +import { + ANY_TEMPORAL_EXPECTED, FORMAT_EXPECTED, PLUS_OFFSET_HINT, + looksLikeUnencodedPlusOffset, matchesAnyTemporal, matchesFormat, utcIsoIfZoned, utcIsoInstant, +} from "./filter-value-format.js"; +import { canonicalDecimal } from "../decimal-wire.js"; +import { DURATION_MICROS_MAX, DURATION_MICROS_MIN, parseDurationLiteral } from "../duration-wire.js"; + +/** A scalar operand after its checks: a number or boolean as that type, everything else text. */ +export type FilterScalar = string | number | boolean; + +/** One comparison. `in` carries a list; `isNull` a boolean; every other op one scalar. */ +export interface FilterLeaf { + readonly field: string; + readonly op: FilterOp; + readonly value: FilterScalar | readonly FilterScalar[]; +} + +/** A filter tree: a comparison, or an AND / OR of subtrees (never empty). */ +export type FilterNode = FilterLeaf | { readonly and: readonly FilterNode[] } | { readonly or: readonly FilterNode[] }; + +export interface ListSearch { + /** The term as sent; matched case-insensitively as a substring. */ + readonly term: string; + /** The `@filterable` text fields it is matched against (OR), in allowlist order. */ + readonly fields: readonly string[]; +} + +export interface ListSort { + readonly field: string; + readonly order: "asc" | "desc"; +} + +export interface ListQuery { + readonly filter?: FilterNode; + readonly search?: ListSearch; + readonly sort?: ListSort; + readonly limit?: number; + readonly offset?: number; +} + +export interface ParseListQueryOpts { + /** The bracketed query, as `parseListQueryString` returns it. */ + readonly query: Record; + readonly allowlist: FilterAllowlist; + readonly sortAllowlist: SortAllowlist; + /** + * Is `name` a field of the entity (a column of the table or view the list reads)? A bare + * `?name=` naming one that is not filterable is refused as `filter.bare_field`; absent, only + * a bare FILTERABLE field is refused. + */ + readonly isField?: (name: string) => boolean; + /** A field on the allowlist the read source has no column for (an allowlist out of step + * with its table) is `invalid_filter_field`. Absent, every allowlisted field has one. */ + readonly hasColumn?: (name: string) => boolean; + /** The enum members of a field whose rule carries none (an allowlist generated before + * `enumValues` existed: the Drizzle column's own members). */ + readonly enumValuesOf?: (name: string) => readonly string[] | undefined; + readonly maxNesting?: number; + readonly maxInListSize?: number; +} + +/** The deepest `or` / `and` nesting a filter may use; one level deeper is `filter.nesting_too_deep`. */ +export const DEFAULT_MAX_NESTING = 5; +/** The most elements an `in` list may carry; one more is `filter.in_too_large`. */ +export const DEFAULT_MAX_IN_LIST = 100; + +/** + * Parse a raw query string (no leading `?`) into the bracketed tree the list routes read. + * + * qs's defaults would cut the tree short: past 5 brackets it keeps the rest of a key as one + * literal string (`filter[or][0][or][0][or][0][a][eq]` became a field named `[0][a][eq]`, an + * `invalid_filter_field` naming a field nobody sent), so the nesting cap could never be reached + * and a three-level filter was refused for the wrong reason. The depth here admits one level + * past the cap — two brackets per level plus the field and the op — so a too-deep filter is + * answered as one, and an index above 20 stays an index rather than becoming an object key. + */ +export function parseListQueryString(raw: string, maxNesting: number = DEFAULT_MAX_NESTING): Record { + return qs.parse(raw, { depth: 2 * (maxNesting + 1) + 3, arrayLimit: DEFAULT_MAX_IN_LIST }) as Record; +} + +/** The query string of a request URL (`/x?a=1` → `a=1`; no `?` → ""). */ +export function rawQueryOf(url: string | undefined): string { + if (url === undefined) return ""; + const i = url.indexOf("?"); + return i === -1 ? "" : url.slice(i + 1); +} + +/** Top-level list-query parameters this parser (or the mount around it) reads. A + * filterable field that happens to share one of these names is addressed only through + * `filter[]`, so the bare-field check below never claims them. */ +const RESERVED_LIST_PARAMS: ReadonlySet = new Set([ + "filter", "sort", "limit", "offset", "search", "withCount", +]); + +/** + * Parse and check a list query. The checks run in a fixed order, which is part of the + * contract when a request carries more than one fault: bare field parameters, `limit`, + * `offset`, the filter (depth-first, in the order its keys were sent), `sort`, `search`. + */ +export function parseListQuery(opts: ParseListQueryOpts): ListQuery { + rejectBareFieldParams(opts.query, opts.allowlist, opts.isField); + const out: { -readonly [K in keyof ListQuery]: ListQuery[K] } = {}; + + const limit = parsePageBound(opts.query, "limit"); + if (limit !== undefined) out.limit = limit; + const offset = parsePageBound(opts.query, "offset"); + if (offset !== undefined) out.offset = offset; + + if (opts.query.filter && typeof opts.query.filter === "object") { + const filter = parseNode(opts.query.filter as Record, opts, 0); + if (filter) out.filter = filter; + } + + if (typeof opts.query.sort === "string") out.sort = parseSort(opts.query.sort, opts.sortAllowlist); + + if (typeof opts.query.search === "string" && opts.query.search !== "") { + const fields = searchFields(opts.allowlist); + if (fields.length > 0) out.search = { term: opts.query.search, fields }; + } + return out; +} + +/** + * The fields `?search` matches: `@filterable` text fields. A rule with a `format` (uuid, …) + * is a typed column that is a string on the wire, not text — a case-insensitive LIKE on a + * Postgres uuid column is "operator does not exist" (a 500). + */ +export function searchFields(allowlist: FilterAllowlist): string[] { + return Object.entries(allowlist) + // A search term is a `like` pattern, so only a field whose band has `like` takes part: a + // typed column spelled as a string (uuid, a `format`) and an int-backed enum (an integer + // column, no `like` in its band) would make Postgres answer "operator does not exist". + .filter(([, rule]) => rule.subType === "string" && rule.format === undefined && rule.ops.includes("like")) + .map(([field]) => field); +} + +/** + * `?priority=low` on a list whose allowlist has `priority` is almost always a caller who + * meant `?filter[priority][eq]=low` — and silently ignoring it returns EVERY row, which + * reads as "the filter matched everything". Refuse it, naming the syntax that works. + * + * A bare name that is a field of the entity but NOT on the filter allowlist is refused + * too — the caller plainly meant that field — saying it is not filterable and listing + * the fields that are. Any other unknown parameter — a cache-buster, a tracking tag, a + * param some proxy appends — is left alone. + */ +function rejectBareFieldParams( + query: Record, + allowlist: FilterAllowlist, + isField: ((name: string) => boolean) | undefined, +): void { + for (const [key, value] of Object.entries(query)) { + if (RESERVED_LIST_PARAMS.has(key)) continue; + if (Object.hasOwn(allowlist, key)) { + const shown = typeof value === "string" ? value : ""; + throw new FilterParseError( + "filter.bare_field", + `"${key}" is a filterable field, but a bare ?${key}= parameter is not a filter. Use filter[${key}][eq]=${shown}.`, + { field: key, expected: `filter[${key}][eq]=${shown}` }, + ); + } + if (isField?.(key) === true) { + const allowed = Object.keys(allowlist); + throw new FilterParseError( + "filter.bare_field", + `"${key}" is a field of this entity, but it is not @filterable, so it cannot be filtered on` + + (allowed.length > 0 ? ` (filterable: ${allowed.join(", ")}).` : " (no field is filterable)."), + { field: key, filterable: false, expected: `a filterable field — "${key}" is not @filterable`, allowed }, + ); + } + } +} + +function parseNode(node: Record, opts: ParseListQueryOpts, depth: number): FilterNode | undefined { + const maxNesting = opts.maxNesting ?? DEFAULT_MAX_NESTING; + if (depth > maxNesting) { + throw new FilterParseError("filter.nesting_too_deep", `Filter nesting depth exceeds limit (${maxNesting}).`, { limit: maxNesting }); + } + const parts: FilterNode[] = []; + for (const [key, value] of Object.entries(node)) { + if (key === "or" || key === "and") { + const subs = ensureArray(value, key) + .map((sub) => parseNode(asNode(sub, key), opts, depth + 1)) + .filter((s): s is FilterNode => s !== undefined); + if (subs.length === 0) continue; + // One branch is that branch: `or` of one condition is the condition. + parts.push(subs.length === 1 ? (subs[0] as FilterNode) : key === "or" ? { or: subs } : { and: subs }); + continue; + } + const rule = Object.hasOwn(opts.allowlist, key) ? opts.allowlist[key] : undefined; + if (!rule) { + throw new FilterParseError("filter.unknown_field", `Unknown filter field "${key}".`, { field: key, allowed: Object.keys(opts.allowlist) }); + } + if (opts.hasColumn !== undefined && !opts.hasColumn(key)) { + throw new FilterParseError("filter.unknown_field", `Table has no column for field "${key}".`, { field: key }); + } + if (typeof value === "object" && value !== null && !Array.isArray(value)) { + for (const [op, operand] of Object.entries(value)) parts.push(leaf(key, rule, op, operand, opts)); + } else { + // A bare value is `eq` sugar. + parts.push(leaf(key, rule, "eq", value, opts)); + } + } + if (parts.length === 0) return undefined; + return parts.length === 1 ? parts[0] : { and: parts }; +} + +/** A combinator's branch must itself be a filter object; a scalar there (`filter[or][0]=x`) + * names no field. */ +function asNode(sub: unknown, key: string): Record { + if (sub !== null && typeof sub === "object" && !Array.isArray(sub)) return sub as Record; + throw new FilterParseError("filter.invalid_value", `Each "${key}" branch must be a filter object.`, { field: key }); +} + +function ensureArray(v: unknown, key: string): unknown[] { + if (Array.isArray(v)) return v; + // qs gives `{ "0": …, "1": … }` for sparse or very large indexes; integer keys iterate + // in ascending order, so the branches keep their numeric order. + if (v && typeof v === "object") return Object.values(v); + // `field` (not `key`) because this is the cross-port `invalid_filter_value` envelope, + // which REQUIRES `field` naming the offending filter key — here the connector. + throw new FilterParseError("filter.invalid_value", `Expected array for "${key}".`, { field: key }); +} + +function leaf(field: string, rule: FilterFieldRule, op: string, operand: unknown, opts: ParseListQueryOpts): FilterLeaf { + if (!rule.ops.includes(op as FilterOp)) { + throw new FilterParseError("filter.unsupported_op", `Op "${op}" not supported for field "${field}".`, { field, op, allowed: rule.ops }); + } + const filterOp = op as FilterOp; + switch (filterOp) { + case "in": { + const maxInList = opts.maxInListSize ?? DEFAULT_MAX_IN_LIST; + const list = String(operand).split(",").map((v) => operandOf(v.trim(), rule, field, op, opts)); + if (list.length > maxInList) { + throw new FilterParseError("filter.in_too_large", `In-list size ${list.length} exceeds limit ${maxInList}.`, { field, limit: maxInList }); + } + return { field, op: filterOp, value: list }; + } + case "like": { + const s = String(operand); + if (s.startsWith("%") && !rule.leadingWildcard) { + throw new FilterParseError("filter.leading_wildcard_disallowed", `Leading wildcard not allowed for field "${field}".`, { field }); + } + // `like` is case-SENSITIVE SQL LIKE (ADR-0049): the pattern is kept verbatim. + return { field, op: filterOp, value: s }; + } + case "isNull": + // The operand is "is the value null?" — a boolean whatever the field's type. + return { field, op: filterOp, value: asBoolean(operand, field, op) }; + default: + return { field, op: filterOp, value: operandOf(operand, rule, field, op, opts) }; + } +} + +/** `expected` for a non-whole bound on an integer-valued field (`integer: true`). */ +const INTEGER_EXPECTED = "integer (a whole number)"; +const DURATION_IN_RANGE = "duration within the 64-bit microsecond range"; + +function invalidValue(field: string, op: string, s: string, expected: string, extra: Record = {}): FilterParseError { + const hint = typeof extra["hint"] === "string" ? ` Hint: ${extra["hint"]}.` : ""; + return new FilterParseError( + "filter.invalid_value", + `Field "${field}" op "${op}" requires ${expected}, got "${s}".${hint}`, + { field, op, expected, ...extra }, + ); +} + +/** + * Check a comparison operand against the field's rule and give it its neutral form: a + * number or boolean as that type; a decimal as its canonical text (never through a double, + * ADR-0019 Amendment 1); an instant timestamp in the stored UTC spelling (a zoneless or + * date-only bound read as UTC), any other timestamp with only a zoned bound rewritten to + * UTC; everything else as sent. Refusing a malformed operand here is what keeps SQLite from + * comparing it as text (a silent `[]`) and Postgres from failing the cast (a 500). + */ +function operandOf(value: unknown, rule: FilterFieldRule, field: string, op: string, opts: ParseListQueryOpts): FilterScalar { + const s = typeof value === "string" ? value : String(value); + const members = rule.enumValues ?? opts.enumValuesOf?.(field); + if (members !== undefined && !members.includes(s)) { + throw invalidValue(field, op, s, `one of: ${members.join(", ")}`, { allowed: [...members] }); + } + if (rule.format !== undefined) { + if (!matchesFormat(rule.format, s)) { + // `filter[dueAt][lt]=2026-10-06T00:00:00+00:00` sent unencoded arrives with a space + // where the `+` was; the answer names the fix. + const hint = rule.format === FIELD_SUBTYPE_TIMESTAMP && looksLikeUnencodedPlusOffset(s) ? { hint: PLUS_OFFSET_HINT } : {}; + throw invalidValue(field, op, s, FORMAT_EXPECTED[rule.format], hint); + } + } else if (rule.subType === "datetime" && !matchesAnyTemporal(s)) { + throw invalidValue(field, op, s, ANY_TEMPORAL_EXPECTED); + } + if (rule.format === FIELD_SUBTYPE_DECIMAL) return canonicalDecimal(s) as string; + if (rule.format === FIELD_SUBTYPE_DURATION) { + // A well-formed span past 64 bits of microseconds is no stored value on any database. + const micros = parseDurationLiteral(s) as bigint; + if (micros > DURATION_MICROS_MAX || micros < DURATION_MICROS_MIN) throw invalidValue(field, op, s, DURATION_IN_RANGE); + return s; + } + if (rule.format === FIELD_SUBTYPE_TIMESTAMP) return rule.instant === true ? utcIsoInstant(s) : utcIsoIfZoned(s); + switch (rule.subType) { + case "boolean": + return asBoolean(s, field, op); + case "number": { + // `Number("")` and `Number(" ")` are 0 — an empty bound is not the number zero. + const n = s.trim() === "" ? Number.NaN : Number(s); + if (!Number.isFinite(n)) { + throw new FilterParseError("filter.invalid_value", `Field "${field}" op "${op}" requires number, got "${s}".`, { field, op, expected: "number" }); + } + // field.int / field.long / field.currency: a fractional bound is not a value of the field. + if (rule.integer === true && !Number.isInteger(n)) throw invalidValue(field, op, s, INTEGER_EXPECTED); + return n; + } + default: + return s; + } +} + +function asBoolean(value: unknown, field: string, op: string): boolean { + const s = typeof value === "string" ? value : String(value); + if (s === "true" || s === "1") return true; + if (s === "false" || s === "0") return false; + throw new FilterParseError("filter.invalid_value", `Field "${field}" op "${op}" requires boolean, got "${s}".`, { field, op, expected: "boolean" }); +} + +function parseSort(spec: string, sortAllowlist: SortAllowlist): ListSort { + const colonIdx = spec.indexOf(":"); + const field = colonIdx === -1 ? spec : spec.slice(0, colonIdx); + if (!Object.hasOwn(sortAllowlist, field)) { + throw new FilterParseError( + "sort.unknown_field", + `Unknown sort field "${field}". The syntax is ${SORT_EXPECTED}.`, + { field, expected: SORT_EXPECTED, allowed: Object.keys(sortAllowlist) }, + ); + } + // `?sort=field` with no `:order` takes the field's DECLARED `@sortableDefaultOrder`. + // Applying it when `?sort` is absent entirely would give every endpoint an ordering it + // does not have: the declaration says which way a column runs, not which column to sort by. + const orderRaw = sortOrderSpec(sortAllowlist, field, colonIdx === -1 ? undefined : spec.slice(colonIdx + 1)); + const order = orderRaw.toLowerCase(); + if (order !== "asc" && order !== "desc") { + throw new FilterParseError( + "sort.invalid_order", + `Sort order must be asc|desc, got "${orderRaw}". The syntax is ${SORT_EXPECTED}.`, + { field, expected: SORT_EXPECTED, allowed: Object.keys(sortAllowlist) }, + ); + } + return { field, order }; +} + +/** + * Translate a SQL LIKE pattern into an equivalent SQLite GLOB pattern: + * `%` → `*`, `_` → `?`, and GLOB's own metacharacters (`*`, `?`, `[`) are + * wrapped in single-character classes so they match literally. `]` is only + * special inside a class, so it passes through. GLOB is case-sensitive, + * which is why the sqlite `like` branch uses it (ADR-0049) — SQLite's + * native LIKE folds ASCII case by default. + */ +export function likePatternToGlob(pattern: string): string { + let out = ""; + for (const ch of pattern) { + if (ch === "%") out += "*"; + else if (ch === "_") out += "?"; + else if (ch === "*") out += "[*]"; + else if (ch === "?") out += "[?]"; + else if (ch === "[") out += "[[]"; + else out += ch; + } + return out; +} diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts b/examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts index 93e97cffde..c06f5fdaec 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts @@ -1,7 +1,7 @@ import type { FastifyInstance, RouteShorthandOptions } from "fastify"; import { quoteIdent, type SqlDialect } from "../sql-dialect.js"; import { sql, eq, and, count } from "drizzle-orm"; -import qs from "qs"; +import { parseListQueryString } from "./list-query.js"; import { parseFilterParams, parsePageBound, pageLimit, parseReportPage, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, FilterParseError, type PageSize } from "./filter-parser.js"; import { ReportExportError, assertExportWithinCap, exportContentDisposition, exportWithCountError, isExportCountFlag, @@ -194,7 +194,7 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const url = req.raw.url ?? ""; const qIdx = url.indexOf("?"); const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = qs.parse(queryString) as Record; + const parsed = parseListQueryString(queryString); // A bound that is not an integer in range is a 400, not silently clamped. const reportPage = isReport ? parseReportPage(parsed, reportMaxRows) : undefined; const limitVal = reportPage?.limit ?? parsePageBound(parsed, "limit", RAW_VIEW_MAX_LIMIT) ?? RAW_VIEW_MAX_LIMIT; @@ -214,7 +214,7 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const url = req.raw.url ?? ""; const qIdx = url.indexOf("?"); const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = qs.parse(queryString) as Record; + const parsed = parseListQueryString(queryString); const withCount = isTruthyFlag(parsed["withCount"]); // Export mode: the selector is validated before any query runs, and the export cap governs. const format = exportSpec ? readExportFormat(parsed, exportSpec) : undefined; diff --git a/examples/showcase/codegen/runtime/route-errors.ts b/examples/showcase/codegen/runtime/route-errors.ts index 0a1a0e187c..b01d7a9f45 100644 --- a/examples/showcase/codegen/runtime/route-errors.ts +++ b/examples/showcase/codegen/runtime/route-errors.ts @@ -18,9 +18,9 @@ * mount folded it into a Zod `validation` error. Both now answer * `400 { "error": "invalid_json" }`. * - * The api-contract corpus pins neither response (5xx is implementation-defined there, and - * no scenario sends a malformed body), so both are TS-helper extensions — documented in - * docs/features/api-contract.md, "TS-only error responses". + * Both are in the REST contract (docs/features/api-contract.md, "Error responses for a bad + * request or a failed write"); `api-contract-conformance/list-query/invalid-json` sends a + * malformed body. A 5xx body is otherwise implementation-defined there. */ import { RedactedDatabaseError, logAndRedact } from "./constraint-errors.js"; diff --git a/examples/showcase/codegen/templates/drizzle-schema.ts b/examples/showcase/codegen/templates/drizzle-schema.ts index 026d00f5be..b5a79e86e0 100644 --- a/examples/showcase/codegen/templates/drizzle-schema.ts +++ b/examples/showcase/codegen/templates/drizzle-schema.ts @@ -590,16 +590,16 @@ function buildCompositeKeyCallback( return code`${primaryKeySym}({ columns: [${columnRefs}] })`; } -/** Build a JS-style object literal string (not JSON.stringify which uses quoted keys). - * Array values get `as const` appended so Drizzle's text(...,{ enum: [...] }) - * narrows the inferred column type to a literal union instead of bare `string`. */ -function inlineObjectLiteral(obj: Record): string { +/** Build a JS-style object literal string (not JSON.stringify, which quotes every key): + * `{ length: 200 }`, not `{ "length": 200 }`. A key that is not a bare identifier keeps + * its quotes. Array values get `as const` appended so Drizzle's text(...,{ enum: [...] }) + * narrows the inferred column type to a literal union instead of bare `string`. Shared by + * the table template and the existing-view declaration (`view-decl.ts`). */ +export function inlineObjectLiteral(obj: Record): string { const entries = Object.entries(obj).map(([k, v]) => { + const name = /^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k); const lit = JSON.stringify(v); - if (Array.isArray(v)) { - return `${k}: ${lit} as const`; - } - return `${k}: ${lit}`; + return Array.isArray(v) ? `${name}: ${lit} as const` : `${name}: ${lit}`; }); return `{ ${entries.join(", ")} }`; } diff --git a/examples/showcase/codegen/templates/filter-allowlist.ts b/examples/showcase/codegen/templates/filter-allowlist.ts index 5d1527373a..b8ef1b2bcd 100644 --- a/examples/showcase/codegen/templates/filter-allowlist.ts +++ b/examples/showcase/codegen/templates/filter-allowlist.ts @@ -93,24 +93,45 @@ const INTEGER_SUBTYPES = new Set([ * as UTC, the same rule the generated write schema stores it by. Scalar fields only: an * array field's filter value is not one element of the declared type. */ -function valueShape(f: MetaField): string { - if (f.resolvedIsArray()) return ""; - if (INTEGER_SUBTYPES.has(f.subType)) return ", integer: true as const"; +function valueShape(f: MetaField): FilterRuleValueShape { + if (f.resolvedIsArray()) return {}; + if (INTEGER_SUBTYPES.has(f.subType)) return { integer: true }; if (VALUE_FORMAT_SUBTYPES.has(f.subType)) { - const instant = f.subType === FIELD_SUBTYPE_TIMESTAMP && f.attr(FIELD_ATTR_LOCAL_TIME) !== true - ? ", instant: true as const" - : ""; - return `, format: ${JSON.stringify(f.subType)} as const${instant}`; + const instant = f.subType === FIELD_SUBTYPE_TIMESTAMP && f.attr(FIELD_ATTR_LOCAL_TIME) !== true; + return instant ? { format: f.subType, instant: true } : { format: f.subType }; } if (f.subType === FIELD_SUBTYPE_ENUM) { // Member SYMBOLS for string- and int-backed enums alike: an int-backed column's codec // maps the symbol to its integer when the value is bound. const members = enumValues(f); - if (members !== undefined && members.length > 0) { - return `, enumValues: [${members.map((m) => JSON.stringify(m)).join(", ")}] as const`; - } + if (members !== undefined && members.length > 0) return { enumValues: members }; } - return ""; + return {}; +} + +/** The optional members of a rule beyond `ops` / `subType` / `leadingWildcard`. */ +interface FilterRuleValueShape { + readonly dateValues?: true; + readonly format?: string; + readonly instant?: true; + readonly integer?: true; + readonly enumValues?: readonly string[]; +} + +/** + * One field's filter rule, as data: what `FilterAllowlist` carries for it. The + * runtime-ts `FilterFieldRule` shape, kept structural here so codegen does not depend on + * the runtime package. + */ +export interface FilterAllowlistRule extends FilterRuleValueShape { + readonly ops: readonly string[]; + readonly subType: "string" | "number" | "boolean" | "datetime"; + readonly leadingWildcard: false; +} + +/** One sortable field's rule, as data: what `SortAllowlist` carries for it. */ +export interface SortAllowlistRule { + readonly defaultOrder?: "asc" | "desc"; } function filterableFields(entity: MetaObject, exclude: string | undefined, ctx: RenderContext | undefined): MetaField[] { @@ -134,29 +155,49 @@ function filterableFields(entity: MetaObject, exclude: string | undefined, ctx: * normalized to `"string"` for sqlite/D1 at both config choke points, so no dialect * branching is needed here. Absent `ctx`, or in the default mode, output is unchanged. */ +export function filterAllowlistRules( + entity: MetaObject, + exclude?: string, + ctx?: RenderContext, +): ReadonlyArray { + return filterableFields(entity, exclude, ctx).map((f) => { + // opsForField, not opsForSubType — an int-backed field.enum (@intValueMap) + // stores as an integer, so `like` (a substring match) is not in its band. + const rule: FilterAllowlistRule = { + ops: opsForField(f), + subType: filterSubTypeFor(f.subType), + leadingWildcard: false, + // Only field.timestamp is governed by timestampMode — Drizzle types + // field.date / field.time as strings under every dialect. + ...(ctx?.timestampMode === "date" && f.subType === FIELD_SUBTYPE_TIMESTAMP ? { dateValues: true as const } : {}), + ...valueShape(f), + }; + return [f.name, rule] as const; + }); +} + +/** One rule as the generated allowlist spells it (members in a fixed order, `as const` on each). */ +function filterRuleLiteral(rule: FilterAllowlistRule): string { + const ops = rule.ops.map((o) => JSON.stringify(o)).join(", "); + let out = `{ ops: [${ops}] as const, subType: ${JSON.stringify(rule.subType)} as const, leadingWildcard: false`; + if (rule.dateValues) out += ", dateValues: true as const"; + if (rule.integer) out += ", integer: true as const"; + if (rule.format !== undefined) out += `, format: ${JSON.stringify(rule.format)} as const`; + if (rule.instant) out += ", instant: true as const"; + if (rule.enumValues !== undefined) out += `, enumValues: [${rule.enumValues.map((m) => JSON.stringify(m)).join(", ")}] as const`; + return `${out} }`; +} + export function renderFilterAllowlist(entity: MetaObject, exclude?: string, ctx?: RenderContext): Code { - const fields = filterableFields(entity, exclude, ctx); - if (fields.length === 0) { + const rules = filterAllowlistRules(entity, exclude, ctx); + if (rules.length === 0) { return code` import type { FilterAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; export const ${entity.name}FilterAllowlist = {} as const satisfies FilterAllowlist; `; } - const rows = fields - .map((f) => { - // opsForField, not opsForSubType — an int-backed field.enum (@intValueMap) - // stores as an integer, so `like` (a substring match) is not in its band. - const ops = opsForField(f).map((o) => JSON.stringify(o)).join(", "); - const sub = filterSubTypeFor(f.subType); - // Only field.timestamp is governed by timestampMode — Drizzle types - // field.date / field.time as strings under every dialect. - const dateValues = ctx?.timestampMode === "date" && f.subType === FIELD_SUBTYPE_TIMESTAMP - ? ", dateValues: true as const" - : ""; - return ` ${f.name}: { ops: [${ops}] as const, subType: ${JSON.stringify(sub)} as const, leadingWildcard: false${dateValues}${valueShape(f)} }`; - }) - .join(",\n"); + const rows = rules.map(([name, rule]) => ` ${name}: ${filterRuleLiteral(rule)}`).join(",\n"); return code` import type { FilterAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; @@ -166,34 +207,39 @@ ${rows} `; } -export function renderSortAllowlist(entity: MetaObject, exclude?: string, ctx?: RenderContext): Code { +/** The sortable fields and their rules, as data (what `SortAllowlist` carries). */ +export function sortAllowlistRules( + entity: MetaObject, + exclude?: string, + ctx?: RenderContext, +): ReadonlyArray { // Sortable = explicit @sortable === true, OR (no @sortable AND @filterable === true). - // @sortable: false explicitly opts out. - // Uses shared isSortableField predicate — must stay in sync with renderFilterType. - // `exclude` (FR-017): per-subtype TPH allowlists omit the discriminator. - // A credential is never sortable (isSortableField), nor a column a sibling subtype marks as one. + // @sortable: false explicitly opts out. A credential is never sortable, nor a column a + // sibling subtype marks as one. `exclude` (FR-017): per-subtype TPH allowlists omit the + // discriminator. const credentials = credentialFieldNames(entity, ctx?.loadedRoot); - const sortable = flatSurfaceFields(entity).filter((f) => isSortableField(f) && !credentials.has(f.name) && f.name !== exclude); - if (sortable.length === 0) { + return flatSurfaceFields(entity) + .filter((f) => isSortableField(f) && !credentials.has(f.name) && f.name !== exclude) + .map((f) => { + // The DECLARED order only — an undeclared field stays `{}` so the runtime's own + // `?? "asc"` remains the single place the fallback is spelled. + const defaultOrder = declaredSortDefaultOrder(f); + return [f.name, defaultOrder === undefined ? {} : { defaultOrder }] as const; + }); +} + +export function renderSortAllowlist(entity: MetaObject, exclude?: string, ctx?: RenderContext): Code { + const rules = sortAllowlistRules(entity, exclude, ctx); + if (rules.length === 0) { return code` import type { SortAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; export const ${entity.name}SortAllowlist = {} as const satisfies SortAllowlist; `; } - const rows = sortable - .map((f) => { - // The DECLARED order only — an undeclared field stays `{}` so the runtime's own - // `?? "asc"` remains the single place the fallback is spelled. Read through the - // shared resolver, never off the attr here, so this allowlist and the grid tier - // cannot answer one declaration two ways. - const defaultOrder = declaredSortDefaultOrder(f); - const rule = - defaultOrder === undefined - ? `{}` - : `{ defaultOrder: ${JSON.stringify(defaultOrder)} as const }`; - return ` ${f.name}: ${rule}`; - }) + const rows = rules + .map(([name, rule]) => + ` ${name}: ${rule.defaultOrder === undefined ? "{}" : `{ defaultOrder: ${JSON.stringify(rule.defaultOrder)} as const }`}`) .join(",\n"); return code` import type { SortAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; diff --git a/examples/showcase/codegen/templates/view-decl.ts b/examples/showcase/codegen/templates/view-decl.ts index 3dd02b2329..6f30828276 100644 --- a/examples/showcase/codegen/templates/view-decl.ts +++ b/examples/showcase/codegen/templates/view-decl.ts @@ -18,6 +18,7 @@ import { mapColumnType, DURATION_COLUMN_FN, type EnumIntCustomType } from "@meta import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; import { zodTypeFor } from "./field-meta.js"; +import { inlineObjectLiteral } from "./drizzle-schema.js"; import { columnExpr, type ObjectNames } from "@metaobjectsdev/codegen-ts/engine"; export interface ViewDeclOpts { @@ -111,7 +112,7 @@ function viewColumnLine( : imp(`${spec.fnName}@${spec.importModule}`); const optsArg = spec.fnOptions && Object.keys(spec.fnOptions).length > 0 - ? `, ${optionsLiteral(spec.fnOptions)}` + ? `, ${inlineObjectLiteral(spec.fnOptions)}` : ""; // #204 — of the table modifiers, only `.array()` (postgres native array element // typing) and `.notNull()` (shapes the SELECT type) carry to an existing view; @@ -252,12 +253,3 @@ export function renderViewReadZodObject(fields: readonly MetaField[], opts: View ${joinCode(lines, { on: ",\n" })} })`; } - -/** A column's options as a JS object literal: `{ length: 200 }`, not JSON's `{ "length": 200 }`. */ -function optionsLiteral(options: Record): string { - const entries = Object.entries(options).map(([key, value]) => { - const name = /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key); - return `${name}: ${JSON.stringify(value)}`; - }); - return `{ ${entries.join(", ")} }`; -} diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 1ba85b43c7..ad7b2811ca 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -8,7 +8,7 @@ }, "counts": { "fixtures": 578, - "corpora": 43, + "corpora": 45, "baseTypes": 21 }, "snippets": { diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/calibration.md index 8642c4e397..70ab55926b 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -20,9 +20,11 @@ `invalid-op` / `in`-over-cap 400s) is **generated in every port** (Java `SpringControllerGenerator`, C# `RoutesGenerator`, Python `router_generator`, Kotlin `KotlinSpringControllerGenerator`, TS) — gated by the api-contract corpus in BOTH lanes. **Flag hand-rolled filter parsing anywhere.** - Only the *richer* surface is genuinely **TS-only**: free-text `?search=`, the explicit - `filter[or][N]` / `filter[and][N]` nested boolean combinators (+ their nesting-depth cap), and - leading-wildcard gating — do NOT flag the absence of those in a non-TS port. + The *richer* list surface — free-text `?search=`, the explicit `filter[or][N]` / + `filter[and][N]` nested boolean combinators (+ their nesting-depth cap), and leading-wildcard + gating (ADR-0068) — passes in TypeScript and is **pending** in each other port until that port's + 1.3.0 REST-standard work lands. Do NOT flag the absence of those in a port that has not landed + them yet. - **Output-parser codegen** ships in **all five ports** — Java's `SpringOutputParserGenerator` *generates* the `Parser` (the Jackson `readValue` lives inside that generated file). A hand-rolled parser in a **non-generated** file where a **responding `template.prompt`** diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index 0a892f296c..bc71a99054 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -348,8 +348,10 @@ to nothing, and does not check that each claimed node complies). - **CALIBRATION — per-port codegen gaps:** the core `?filter[field][op]` filter grammar (all 9 operators + the generated allowlist + `invalid-field` / `invalid-op` / `in`-over-cap 400s) is **generated in all five ports** (api-contract corpus, both lanes) — **flag hand-rolled - filter parsing anywhere.** Only the richer surface (`?search=`, explicit - `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating) is TS-only. + filter parsing anywhere.** The richer list surface (`?search=`, explicit + `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating; ADR-0068) passes in + TypeScript and is pending in each other port until its 1.3.0 REST-standard work lands — do not + flag its absence in a port before then. Output-parser codegen also ships in **all five ports**, keyed on a **responding `template.prompt`** (`@responseRef`), never on a `template.output` (ADR-0052) — Java's `SpringOutputParserGenerator` *generates* the parser (the Jackson `readValue` lives inside diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/csharp.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/csharp.md index b2abf45c41..0a1d6a3fd3 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/csharp.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/csharp.md @@ -158,9 +158,10 @@ version across these packages is an intra-port skew finding. generator (`Routes.cs`, Minimal API) generates the `?filter[field][op]=value` grammar (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`) via the runtime `FilterParser` + `EfCoreFilterDispatch`, validated against the generated filter allowlist (api-contract corpus, - both lanes). **Flag a hand-rolled filter parser as a finding.** Only the richer surface - (`?search=`, `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating) is - TS-only — do NOT flag its absence in C#. + both lanes). **Flag a hand-rolled filter parser as a finding.** The richer list surface + (`?search=`, `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating; ADR-0068) + passes in TypeScript and is pending in C# until the C# port's 1.3.0 REST-standard work lands — + do NOT flag its absence in C# until then. - **Output-parser codegen ships in C#.** `output-parser` / `extractor` / `render-helper` generators are available (list `OutputParserGenerator` in `codegen/Generators.cs`). Absence of wired output parsers where a **responding `template.prompt`** (`@responseRef`) exists IS a diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md index 8642c4e397..70ab55926b 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -20,9 +20,11 @@ `invalid-op` / `in`-over-cap 400s) is **generated in every port** (Java `SpringControllerGenerator`, C# `RoutesGenerator`, Python `router_generator`, Kotlin `KotlinSpringControllerGenerator`, TS) — gated by the api-contract corpus in BOTH lanes. **Flag hand-rolled filter parsing anywhere.** - Only the *richer* surface is genuinely **TS-only**: free-text `?search=`, the explicit - `filter[or][N]` / `filter[and][N]` nested boolean combinators (+ their nesting-depth cap), and - leading-wildcard gating — do NOT flag the absence of those in a non-TS port. + The *richer* list surface — free-text `?search=`, the explicit `filter[or][N]` / + `filter[and][N]` nested boolean combinators (+ their nesting-depth cap), and leading-wildcard + gating (ADR-0068) — passes in TypeScript and is **pending** in each other port until that port's + 1.3.0 REST-standard work lands. Do NOT flag the absence of those in a port that has not landed + them yet. - **Output-parser codegen** ships in **all five ports** — Java's `SpringOutputParserGenerator` *generates* the `Parser` (the Jackson `readValue` lives inside that generated file). A hand-rolled parser in a **non-generated** file where a **responding `template.prompt`** diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index 0a892f296c..bc71a99054 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -348,8 +348,10 @@ to nothing, and does not check that each claimed node complies). - **CALIBRATION — per-port codegen gaps:** the core `?filter[field][op]` filter grammar (all 9 operators + the generated allowlist + `invalid-field` / `invalid-op` / `in`-over-cap 400s) is **generated in all five ports** (api-contract corpus, both lanes) — **flag hand-rolled - filter parsing anywhere.** Only the richer surface (`?search=`, explicit - `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating) is TS-only. + filter parsing anywhere.** The richer list surface (`?search=`, explicit + `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating; ADR-0068) passes in + TypeScript and is pending in each other port until its 1.3.0 REST-standard work lands — do not + flag its absence in a port before then. Output-parser codegen also ships in **all five ports**, keyed on a **responding `template.prompt`** (`@responseRef`), never on a `template.output` (ADR-0052) — Java's `SpringOutputParserGenerator` *generates* the parser (the Jackson `readValue` lives inside diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/java.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/java.md index 84e37604d3..b39b6d6862 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/java.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/java.md @@ -157,8 +157,9 @@ versioning — **do not flag it** (only intra-port skew matters). `eq/ne/gt/gte/lt/lte/in/like/isNull`): it parses via the runtime `FilterParser`, validates against the generated `FilterAllowlist`, and 400s on unknown field / disallowed op / over-cap `in`-list (api-contract corpus, both lanes). **Flag a hand-rolled filter parser as a - finding.** Only the *richer* surface is TS-only — `?search=`, `filter[or][N]` / `filter[and][N]` - combinators, leading-wildcard gating — do NOT flag the absence of those in Java. + finding.** The *richer* list surface — `?search=`, `filter[or][N]` / `filter[and][N]` + combinators, leading-wildcard gating (ADR-0068) — passes in TypeScript and is pending in Java + until the Java port's 1.3.0 REST-standard work lands — do NOT flag its absence in Java until then. - **Repository interface is a hand-implemented stub.** `SpringRepositoryGenerator` emits `Repository.java` as a stub `interface`; the consumer hand-writes the implementation against OMDB (or any persistence layer). Hand-written repository diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/kotlin.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/kotlin.md index 8b94ba2482..f047af58ed 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/kotlin.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/kotlin.md @@ -165,7 +165,8 @@ cross-port versioning — **do not flag it** (only intra-port skew matters). `KotlinSpringControllerGenerator` generates the `?filter[field][op]=value` grammar (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`) validated against the generated filter allowlist (api-contract corpus, both lanes). **Flag a hand-rolled filter parser as a finding.** Only the - richer surface (`?search=`, `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard - gating) is TS-only — do NOT flag its absence in Kotlin. + richer list surface (`?search=`, `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard + gating; ADR-0068) passes in TypeScript and is pending in Kotlin until the Kotlin port's 1.3.0 + REST-standard work lands — do NOT flag its absence in Kotlin until then. - **No JVM migrate goal.** Schema migration is Node-`meta`-owned for every port (ADR-0015). The Maven plugin has no migrate goal; `meta migrate` is correct. diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md index 8642c4e397..70ab55926b 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -20,9 +20,11 @@ `invalid-op` / `in`-over-cap 400s) is **generated in every port** (Java `SpringControllerGenerator`, C# `RoutesGenerator`, Python `router_generator`, Kotlin `KotlinSpringControllerGenerator`, TS) — gated by the api-contract corpus in BOTH lanes. **Flag hand-rolled filter parsing anywhere.** - Only the *richer* surface is genuinely **TS-only**: free-text `?search=`, the explicit - `filter[or][N]` / `filter[and][N]` nested boolean combinators (+ their nesting-depth cap), and - leading-wildcard gating — do NOT flag the absence of those in a non-TS port. + The *richer* list surface — free-text `?search=`, the explicit `filter[or][N]` / + `filter[and][N]` nested boolean combinators (+ their nesting-depth cap), and leading-wildcard + gating (ADR-0068) — passes in TypeScript and is **pending** in each other port until that port's + 1.3.0 REST-standard work lands. Do NOT flag the absence of those in a port that has not landed + them yet. - **Output-parser codegen** ships in **all five ports** — Java's `SpringOutputParserGenerator` *generates* the `Parser` (the Jackson `readValue` lives inside that generated file). A hand-rolled parser in a **non-generated** file where a **responding `template.prompt`** diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index 0a892f296c..bc71a99054 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -348,8 +348,10 @@ to nothing, and does not check that each claimed node complies). - **CALIBRATION — per-port codegen gaps:** the core `?filter[field][op]` filter grammar (all 9 operators + the generated allowlist + `invalid-field` / `invalid-op` / `in`-over-cap 400s) is **generated in all five ports** (api-contract corpus, both lanes) — **flag hand-rolled - filter parsing anywhere.** Only the richer surface (`?search=`, explicit - `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating) is TS-only. + filter parsing anywhere.** The richer list surface (`?search=`, explicit + `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating; ADR-0068) passes in + TypeScript and is pending in each other port until its 1.3.0 REST-standard work lands — do not + flag its absence in a port before then. Output-parser codegen also ships in **all five ports**, keyed on a **responding `template.prompt`** (`@responseRef`), never on a `template.output` (ADR-0052) — Java's `SpringOutputParserGenerator` *generates* the parser (the Jackson `readValue` lives inside diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/java.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/java.md index 84e37604d3..b39b6d6862 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/java.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/java.md @@ -157,8 +157,9 @@ versioning — **do not flag it** (only intra-port skew matters). `eq/ne/gt/gte/lt/lte/in/like/isNull`): it parses via the runtime `FilterParser`, validates against the generated `FilterAllowlist`, and 400s on unknown field / disallowed op / over-cap `in`-list (api-contract corpus, both lanes). **Flag a hand-rolled filter parser as a - finding.** Only the *richer* surface is TS-only — `?search=`, `filter[or][N]` / `filter[and][N]` - combinators, leading-wildcard gating — do NOT flag the absence of those in Java. + finding.** The *richer* list surface — `?search=`, `filter[or][N]` / `filter[and][N]` + combinators, leading-wildcard gating (ADR-0068) — passes in TypeScript and is pending in Java + until the Java port's 1.3.0 REST-standard work lands — do NOT flag its absence in Java until then. - **Repository interface is a hand-implemented stub.** `SpringRepositoryGenerator` emits `Repository.java` as a stub `interface`; the consumer hand-writes the implementation against OMDB (or any persistence layer). Hand-written repository diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md index 8642c4e397..70ab55926b 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -20,9 +20,11 @@ `invalid-op` / `in`-over-cap 400s) is **generated in every port** (Java `SpringControllerGenerator`, C# `RoutesGenerator`, Python `router_generator`, Kotlin `KotlinSpringControllerGenerator`, TS) — gated by the api-contract corpus in BOTH lanes. **Flag hand-rolled filter parsing anywhere.** - Only the *richer* surface is genuinely **TS-only**: free-text `?search=`, the explicit - `filter[or][N]` / `filter[and][N]` nested boolean combinators (+ their nesting-depth cap), and - leading-wildcard gating — do NOT flag the absence of those in a non-TS port. + The *richer* list surface — free-text `?search=`, the explicit `filter[or][N]` / + `filter[and][N]` nested boolean combinators (+ their nesting-depth cap), and leading-wildcard + gating (ADR-0068) — passes in TypeScript and is **pending** in each other port until that port's + 1.3.0 REST-standard work lands. Do NOT flag the absence of those in a port that has not landed + them yet. - **Output-parser codegen** ships in **all five ports** — Java's `SpringOutputParserGenerator` *generates* the `Parser` (the Jackson `readValue` lives inside that generated file). A hand-rolled parser in a **non-generated** file where a **responding `template.prompt`** diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index 0a892f296c..bc71a99054 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -348,8 +348,10 @@ to nothing, and does not check that each claimed node complies). - **CALIBRATION — per-port codegen gaps:** the core `?filter[field][op]` filter grammar (all 9 operators + the generated allowlist + `invalid-field` / `invalid-op` / `in`-over-cap 400s) is **generated in all five ports** (api-contract corpus, both lanes) — **flag hand-rolled - filter parsing anywhere.** Only the richer surface (`?search=`, explicit - `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating) is TS-only. + filter parsing anywhere.** The richer list surface (`?search=`, explicit + `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating; ADR-0068) passes in + TypeScript and is pending in each other port until its 1.3.0 REST-standard work lands — do not + flag its absence in a port before then. Output-parser codegen also ships in **all five ports**, keyed on a **responding `template.prompt`** (`@responseRef`), never on a `template.output` (ADR-0052) — Java's `SpringOutputParserGenerator` *generates* the parser (the Jackson `readValue` lives inside diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/python.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/python.md index d8f9baf9e9..1968fb15f3 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/python.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/python.md @@ -159,9 +159,10 @@ another) matters. generator emits an `APIRouter` whose list route parses the `?filter[field][op]=value` grammar (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`) via the generated `filter_parser` module, validated against the generated filter allowlist (api-contract corpus, both lanes). **Flag a - hand-rolled filter parser as a finding.** Only the richer surface (`?search=`, - `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating) is TS-only — do NOT - flag its absence in Python. + hand-rolled filter parser as a finding.** The richer list surface (`?search=`, + `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating; ADR-0068) passes in + TypeScript and is pending in Python until the Python port's 1.3.0 REST-standard work lands — do + NOT flag its absence in Python until then. - **Partial relationship + flattened-object codegen.** Relationship navigation, non-`table` source kinds, and `field.object @storage: flattened` codegen are partially implemented in the Python port. Do NOT flag these gaps as adopter defects. diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md index 8642c4e397..70ab55926b 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -20,9 +20,11 @@ `invalid-op` / `in`-over-cap 400s) is **generated in every port** (Java `SpringControllerGenerator`, C# `RoutesGenerator`, Python `router_generator`, Kotlin `KotlinSpringControllerGenerator`, TS) — gated by the api-contract corpus in BOTH lanes. **Flag hand-rolled filter parsing anywhere.** - Only the *richer* surface is genuinely **TS-only**: free-text `?search=`, the explicit - `filter[or][N]` / `filter[and][N]` nested boolean combinators (+ their nesting-depth cap), and - leading-wildcard gating — do NOT flag the absence of those in a non-TS port. + The *richer* list surface — free-text `?search=`, the explicit `filter[or][N]` / + `filter[and][N]` nested boolean combinators (+ their nesting-depth cap), and leading-wildcard + gating (ADR-0068) — passes in TypeScript and is **pending** in each other port until that port's + 1.3.0 REST-standard work lands. Do NOT flag the absence of those in a port that has not landed + them yet. - **Output-parser codegen** ships in **all five ports** — Java's `SpringOutputParserGenerator` *generates* the `Parser` (the Jackson `readValue` lives inside that generated file). A hand-rolled parser in a **non-generated** file where a **responding `template.prompt`** diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index 0a892f296c..bc71a99054 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -348,8 +348,10 @@ to nothing, and does not check that each claimed node complies). - **CALIBRATION — per-port codegen gaps:** the core `?filter[field][op]` filter grammar (all 9 operators + the generated allowlist + `invalid-field` / `invalid-op` / `in`-over-cap 400s) is **generated in all five ports** (api-contract corpus, both lanes) — **flag hand-rolled - filter parsing anywhere.** Only the richer surface (`?search=`, explicit - `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating) is TS-only. + filter parsing anywhere.** The richer list surface (`?search=`, explicit + `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating; ADR-0068) passes in + TypeScript and is pending in each other port until its 1.3.0 REST-standard work lands — do not + flag its absence in a port before then. Output-parser codegen also ships in **all five ports**, keyed on a **responding `template.prompt`** (`@responseRef`), never on a `template.output` (ADR-0052) — Java's `SpringOutputParserGenerator` *generates* the parser (the Jackson `readValue` lives inside diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/typescript.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/typescript.md index ce4485c972..12990f46cb 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/typescript.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/typescript.md @@ -211,7 +211,7 @@ via `metamodelVersion` (see the Phase 0 cross-language consistency item). TypeScript is the reference implementation — it ships the full feature set: -- Filter-operator codegen: **complete** — the core `?filter[field][op]` grammar (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`, `FilterAllowlist`) generates in every port; TS additionally ships the richer surface (`?search=`, `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating). +- Filter-operator codegen: **complete** — the core `?filter[field][op]` grammar (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`, `FilterAllowlist`) generates in every port; the richer list surface (`?search=`, `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating; ADR-0068) passes in TypeScript; each other port is pending until its 1.3.0 REST-standard work lands. - Output-parser codegen: **complete** (`outputParser()` generator; `parse*`/`safeParse*`/`extract*` emitted as `.response.ts` per **responding `template.prompt`** — one carrying `@responseRef`; ADR-0052). - ObjectManager: **complete** (`@metaobjectsdev/runtime-ts`; `kyselyDriver` / `inMemoryDriver`). - Schema migrate / `meta verify --db`: **complete** (TS owns the shared migrate engine — ADR-0015). diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript-mysql.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript-mysql.md index 3e40002a0b..ec7c7b3762 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript-mysql.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript-mysql.md @@ -123,7 +123,8 @@ emitted too, and a measure with `@default` is a `COALESCE` whose column MySQL re - The generated `deleteById` checks that the row exists before deleting it. - **`like` is case-sensitive**, as the API contract requires (ADR-0049). MySQL's default collation is case-insensitive, so the generated routes compare with - `COLLATE utf8mb4_bin`. The TypeScript-only `?search` stays case-insensitive. + `COLLATE utf8mb4_bin`. `?search` stays case-insensitive, as the list contract states + ([api-contract.md](../features/api-contract.md)). - **Timestamps use Drizzle's `date` mode.** A `DATETIME` rejects the ISO wire form (`2026-05-28T20:26:40.002Z` is `ERROR 1292`). The generated Zod schema coerces the ISO string to a `Date`, Drizzle stores the UTC wall clock, and the JSON response carries ISO with `Z`. diff --git a/fixtures/api-contract-conformance/README.md b/fixtures/api-contract-conformance/README.md index 7f1e5ce8af..c3feaea637 100644 --- a/fixtures/api-contract-conformance/README.md +++ b/fixtures/api-contract-conformance/README.md @@ -56,8 +56,8 @@ fixtures/api-contract-conformance/ └── filter-invalid-value.yaml # uncoercible value → 400; the fourth envelope, previously ungated ``` -Beside the 34 core scenarios above sit eleven **sub-corpora**, each a directory with its -own `meta.json`, `seed.json`, `scenarios/` and `README.md` (107 scenarios in all, 141 with the +Beside the 34 core scenarios above sit twelve **sub-corpora**, each a directory with its +own `meta.json`, `seed.json`, `scenarios/` and `README.md` (127 scenarios in all, 161 with the core): | Directory | Scenarios | Gates | Lanes | @@ -72,6 +72,7 @@ core): | `report/` | 37 | a view-backed `object.report` (FR-044): list, filter, sort and paging on derived fields, `POST` is `405`, no `/{id}` route; a `@spine` report keeps a row with no facts, and a measure with `@default` filters and sorts as its default; a dimension over an array or a map is neither filterable nor sortable. Also carries `schema.postgres.sql`, the TypeScript-produced table and views the C# lane executes | generated only | | `decimal/` | 11 | `field.decimal` is an exact canonical string on the wire (ADR-0019 Amendment 1): read, filter, sort, write and a report over decimals. A scenario's `engines:` key is exact; the `-15` twins run on SQLite and D1 as well. Also carries `schema.postgres.sql` / `schema.sqlite.sql` / `schema.mysql.sql` | generated only | | `api-settings/` | 8 | the `api` block in the sub-corpus's own `.metaobjects/config.json`: `api.pagination` (default 2, max 4) — a list with no `limit` answers the default page, `offset` and `withCount=1` page past it, `limit` at the cap is served, one above it is `400 {"error": "limit_too_large", "maxLimit": 4}` and a negative one is `400 pagination.invalid_value`, while `limit=0` is an empty page — and `api.unknownFields: drop`, under which an undeclared body key is ignored rather than refused | generated only | +| `list-query/` | 20 | the REST standard's list handling against a real store, over a 60-row seed: `?search` ignores case and `like` does not, `filter[or]` / `filter[and]`, the nesting cap, a bare field refused, a leading `%` refused, value formats refused, paging past 50, and the `invalid_json`, `invalid_id`, `pagination.invalid_value` and `constraint_violation` refusals. The parse itself is pinned with no server by `fixtures/list-query-conformance/`. TypeScript only until each port's 1.3.0 REST-standard work | generated only | | `duration/` | 2 | `field.duration` is a canonical ISO-8601 span on the wire under `"wire": { "durations": "iso" }`: write, read, refuse, and filter and sort as a span on every engine. Also carries `schema.postgres.sql` / `schema.sqlite.sql` / `schema.mysql.sql` | generated only | `meta.json` declares a single canonical `Author` entity in the `acme::blog` diff --git a/fixtures/api-contract-conformance/list-query/README.md b/fixtures/api-contract-conformance/list-query/README.md new file mode 100644 index 0000000000..a2546ea4ef --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/README.md @@ -0,0 +1,50 @@ +# `api-contract-conformance/list-query/` — the REST standard's list handling, against a store + +What a list query matches in a real store, and how a generated route refuses a bad request. +The parse itself (query string in, filter tree or named 400 out) is pinned with no server and +no database by [`fixtures/list-query-conformance/`](../../list-query-conformance/). This +sub-corpus checks that what was parsed reaches the store with the intended meaning. + +The model is one `Part` (`id`, `name`, `sku` with a unique key, `category` enum, `stock`, and a +`notes` field that is not filterable). The seed holds 60 rows, more than 50, so that a page +boundary sits inside the table. Four names differ only in case and position, so search and +`like` can be told apart: `Pump Housing` (7), `pump seal` (8), `Bilge PUMP` (9) and +`Sump Pump` (10). + +## The contract + +- **`?search=` ignores case; `like` does not** (ADR-0049). `search=pump` finds 7, 8, 9 and 10. + `filter[name][like]=Pump%` finds only 7, and `pump%` only 8. Search covers every filterable + text field, so `sku-05` finds rows 50 to 59 by their sku. Search and filter are both applied, + and `withCount=1` counts what they match. +- **`filter[or]` / `filter[and]`** combine, and an `or` beside a plain condition is ANDed with + it. Five levels of nesting are served, and the sixth is `filter.nesting_too_deep`. +- **Refusals name what was wrong:** + - a bare `?name=` is `filter.bare_field`, and so is `?notes=` on a field that is not + filterable; + - a leading `%` is `filter.leading_wildcard_disallowed`; + - a value of the wrong type is `invalid_filter_value`; + - a page bound that is not a non-negative integer is `pagination.invalid_value`. + + An unknown parameter such as a cache-buster is ignored. +- **Paging past 50:** + - `limit=51` answers 51 rows; + - `limit=5&offset=51` answers rows 52 to 56; + - `limit=0&withCount=1` answers no rows with `total: 60`. +- **Bad bodies, bad ids and failed writes:** + - a body that is not JSON is `400 {"error": "invalid_json"}`; + - a path id the key cannot hold is `400 {"error": "invalid_id"}` on GET, PATCH and DELETE; + - a create that breaks the unique `sku` is `409 {"error": "constraint_violation", "constraint": "unique"}`. + +`rawBody` on a request is sent byte-for-byte as `application/json`, which is how a scenario +sends a body that is not JSON. + +## Lanes + +Generated lane only, like `write-through/` and `report/`. What is under test is whether a +port's generated list route honours the REST standard; a hand-rolled reference server would +answer every scenario by construction. + +Runners: TypeScript `server/typescript/packages/integration-tests/test/api-contract-list-query.test.ts` +(one Postgres container for the file, reseeded before every scenario). The other ports' +runners arrive with their 1.3.0 REST-standard work. diff --git a/fixtures/api-contract-conformance/list-query/meta.json b/fixtures/api-contract-conformance/list-query/meta.json new file mode 100644 index 0000000000..806ca90242 --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/meta.json @@ -0,0 +1,21 @@ +{ + "metadata.root": { + "package": "acme::stockroom", + "children": [ + { "object.entity": { + "name": "Part", + "children": [ + { "source.rdb": { "@table": "parts" } }, + { "field.long": { "name": "id", "@filterable": true, "@sortable": true } }, + { "field.string": { "name": "name", "@required": true, "@maxLength": 100, "@filterable": true, "@sortable": true } }, + { "field.string": { "name": "sku", "@required": true, "@maxLength": 20, "@filterable": true } }, + { "field.enum": { "name": "category", "@values": ["tool", "part", "kit"], "@required": true, "@filterable": true } }, + { "field.int": { "name": "stock", "@required": true, "@filterable": true } }, + { "field.string": { "name": "notes", "@maxLength": 200 } }, + { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, + { "identity.secondary": { "name": "skuKey", "@fields": "sku" } } + ] + }} + ] + } +} diff --git a/fixtures/api-contract-conformance/list-query/scenarios/and-inside-or.yaml b/fixtures/api-contract-conformance/list-query/scenarios/and-inside-or.yaml new file mode 100644 index 0000000000..55add75059 --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/and-inside-or.yaml @@ -0,0 +1,11 @@ +name: and-inside-or +description: > + An `and` nested inside an `or` branch: (tool and stock 0) or id 1. +requests: + - id: r1 + method: GET + path: "/api/parts?filter[or][0][and][0][category][eq]=tool&filter[or][0][and][1][stock][eq]=0&filter[or][1][id][eq]=1&sort=id:asc" + expect: + status: 200 + body: + ids: [1, 30, 60] diff --git a/fixtures/api-contract-conformance/list-query/scenarios/bare-field-not-filterable-refused.yaml b/fixtures/api-contract-conformance/list-query/scenarios/bare-field-not-filterable-refused.yaml new file mode 100644 index 0000000000..d6ade515dd --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/bare-field-not-filterable-refused.yaml @@ -0,0 +1,12 @@ +name: bare-field-not-filterable-refused +description: > + A bare parameter naming a field of the entity that is not `@filterable` is refused too. +requests: + - id: r1 + method: GET + path: "/api/parts?notes=bin%201" + expect: + status: 400 + body: + error: "filter.bare_field" + field: "notes" diff --git a/fixtures/api-contract-conformance/list-query/scenarios/bare-field-refused.yaml b/fixtures/api-contract-conformance/list-query/scenarios/bare-field-refused.yaml new file mode 100644 index 0000000000..39e19a0143 --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/bare-field-refused.yaml @@ -0,0 +1,13 @@ +name: bare-field-refused +description: > + `?name=x` names a filterable field outside `filter[...]`. Ignoring it would answer every row, so + it is refused with `filter.bare_field`. +requests: + - id: r1 + method: GET + path: "/api/parts?name=Anvil%2001" + expect: + status: 400 + body: + error: "filter.bare_field" + field: "name" diff --git a/fixtures/api-contract-conformance/list-query/scenarios/bare-unknown-parameter-ignored.yaml b/fixtures/api-contract-conformance/list-query/scenarios/bare-unknown-parameter-ignored.yaml new file mode 100644 index 0000000000..ad815989a3 --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/bare-unknown-parameter-ignored.yaml @@ -0,0 +1,11 @@ +name: bare-unknown-parameter-ignored +description: > + A parameter that names no field (a cache-buster) is ignored. +requests: + - id: r1 + method: GET + path: "/api/parts?cb=12345&filter[id][in]=3,5,60&sort=id:asc" + expect: + status: 200 + body: + ids: [3, 5, 60] diff --git a/fixtures/api-contract-conformance/list-query/scenarios/constraint-violation.yaml b/fixtures/api-contract-conformance/list-query/scenarios/constraint-violation.yaml new file mode 100644 index 0000000000..46723973aa --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/constraint-violation.yaml @@ -0,0 +1,20 @@ +name: constraint-violation +description: > + A create that breaks the unique `sku` key is refused with + `409 {"error": "constraint_violation", "constraint": "unique"}`, and nothing about the SQL. +requests: + - id: r1 + method: POST + path: "/api/parts" + body: {"name": "Vise", "sku": "SKU-001", "category": "tool", "stock": 1} + expect: + status: 409 + body: + equals: {"error": "constraint_violation", "constraint": "unique"} + - id: r2 + method: GET + path: "/api/parts?filter[sku][eq]=SKU-001" + expect: + status: 200 + body: + ids: [1] diff --git a/fixtures/api-contract-conformance/list-query/scenarios/count-matches-the-filter.yaml b/fixtures/api-contract-conformance/list-query/scenarios/count-matches-the-filter.yaml new file mode 100644 index 0000000000..98b00f0180 --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/count-matches-the-filter.yaml @@ -0,0 +1,13 @@ +name: count-matches-the-filter +description: > + `withCount=1` counts the rows the filter and search match, not the table. +requests: + - id: r1 + method: GET + path: "/api/parts?search=pump&filter[category][eq]=part&withCount=1&limit=1" + expect: + status: 200 + body: + envelope: true + rowsLength: 1 + total: 2 diff --git a/fixtures/api-contract-conformance/list-query/scenarios/invalid-id.yaml b/fixtures/api-contract-conformance/list-query/scenarios/invalid-id.yaml new file mode 100644 index 0000000000..bbab38f414 --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/invalid-id.yaml @@ -0,0 +1,27 @@ +name: invalid-id +description: > + A path id that cannot be the key's type is refused with `400 {"error": "invalid_id"}` on every + verb that takes one, not a 404 and not a 500. +requests: + - id: r1 + method: GET + path: "/api/parts/abc" + expect: + status: 400 + body: + equals: {"error": "invalid_id"} + - id: r2 + method: PATCH + path: "/api/parts/abc" + body: {"stock": 1} + expect: + status: 400 + body: + equals: {"error": "invalid_id"} + - id: r3 + method: DELETE + path: "/api/parts/abc" + expect: + status: 400 + body: + equals: {"error": "invalid_id"} diff --git a/fixtures/api-contract-conformance/list-query/scenarios/invalid-json.yaml b/fixtures/api-contract-conformance/list-query/scenarios/invalid-json.yaml new file mode 100644 index 0000000000..da8cfa413f --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/invalid-json.yaml @@ -0,0 +1,20 @@ +name: invalid-json +description: > + A create whose body is not JSON is refused with `400 {"error": "invalid_json"}`, not a 500. +requests: + - id: r1 + method: POST + path: "/api/parts" + rawBody: "{\"name\": \"Vise\"," + expect: + status: 400 + body: + equals: {"error": "invalid_json"} + - id: r2 + method: PATCH + path: "/api/parts/1" + rawBody: "not json" + expect: + status: 400 + body: + equals: {"error": "invalid_json"} diff --git a/fixtures/api-contract-conformance/list-query/scenarios/leading-wildcard-refused.yaml b/fixtures/api-contract-conformance/list-query/scenarios/leading-wildcard-refused.yaml new file mode 100644 index 0000000000..d358d1a91f --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/leading-wildcard-refused.yaml @@ -0,0 +1,13 @@ +name: leading-wildcard-refused +description: > + A `like` pattern starting with `%` is refused with `filter.leading_wildcard_disallowed`: an + unanchored match cannot use an index. +requests: + - id: r1 + method: GET + path: "/api/parts?filter[name][like]=%25Pump" + expect: + status: 400 + body: + error: "filter.leading_wildcard_disallowed" + field: "name" diff --git a/fixtures/api-contract-conformance/list-query/scenarios/like-is-case-sensitive.yaml b/fixtures/api-contract-conformance/list-query/scenarios/like-is-case-sensitive.yaml new file mode 100644 index 0000000000..66792c506a --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/like-is-case-sensitive.yaml @@ -0,0 +1,19 @@ +name: like-is-case-sensitive +description: > + `like` is case-sensitive on every engine (ADR-0049), unlike search: `Pump%` matches "Pump Housing" + but not "pump seal", and `pump%` the other way round. +requests: + - id: r1 + method: GET + path: "/api/parts?filter[name][like]=Pump%25&sort=id:asc" + expect: + status: 200 + body: + ids: [7] + - id: r2 + method: GET + path: "/api/parts?filter[name][like]=pump%25&sort=id:asc" + expect: + status: 200 + body: + ids: [8] diff --git a/fixtures/api-contract-conformance/list-query/scenarios/nesting-at-the-cap.yaml b/fixtures/api-contract-conformance/list-query/scenarios/nesting-at-the-cap.yaml new file mode 100644 index 0000000000..202d4c9f21 --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/nesting-at-the-cap.yaml @@ -0,0 +1,11 @@ +name: nesting-at-the-cap +description: > + Five levels of or/and nesting is the cap and is served. +requests: + - id: r1 + method: GET + path: "/api/parts?filter[or][0][or][0][or][0][or][0][or][0][id][eq]=4" + expect: + status: 200 + body: + ids: [4] diff --git a/fixtures/api-contract-conformance/list-query/scenarios/nesting-too-deep.yaml b/fixtures/api-contract-conformance/list-query/scenarios/nesting-too-deep.yaml new file mode 100644 index 0000000000..acbc8fc27e --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/nesting-too-deep.yaml @@ -0,0 +1,11 @@ +name: nesting-too-deep +description: > + A sixth level of or/and nesting is refused with `filter.nesting_too_deep`. +requests: + - id: r1 + method: GET + path: "/api/parts?filter[or][0][or][0][or][0][or][0][or][0][or][0][id][eq]=4" + expect: + status: 400 + body: + equals: {"error": "filter.nesting_too_deep", "limit": 5} diff --git a/fixtures/api-contract-conformance/list-query/scenarios/or-beside-a-field.yaml b/fixtures/api-contract-conformance/list-query/scenarios/or-beside-a-field.yaml new file mode 100644 index 0000000000..034096ae91 --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/or-beside-a-field.yaml @@ -0,0 +1,11 @@ +name: or-beside-a-field +description: > + An `or` beside a plain condition is ANDed with it. +requests: + - id: r1 + method: GET + path: "/api/parts?filter[category][eq]=kit&filter[or][0][stock][eq]=2&filter[or][1][stock][eq]=5&sort=id:asc" + expect: + status: 200 + body: + ids: [2, 5, 32, 35] diff --git a/fixtures/api-contract-conformance/list-query/scenarios/or-two-branches.yaml b/fixtures/api-contract-conformance/list-query/scenarios/or-two-branches.yaml new file mode 100644 index 0000000000..acdfb94656 --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/or-two-branches.yaml @@ -0,0 +1,11 @@ +name: or-two-branches +description: > + `filter[or][i]` matches a row that satisfies any branch. +requests: + - id: r1 + method: GET + path: "/api/parts?filter[or][0][id][eq]=3&filter[or][1][stock][eq]=9&sort=id:asc" + expect: + status: 200 + body: + ids: [3, 9, 19, 29, 39, 49, 59] diff --git a/fixtures/api-contract-conformance/list-query/scenarios/page-past-fifty.yaml b/fixtures/api-contract-conformance/list-query/scenarios/page-past-fifty.yaml new file mode 100644 index 0000000000..548dfcbf37 --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/page-past-fifty.yaml @@ -0,0 +1,28 @@ +name: page-past-fifty +description: > + A page of 51 rows is served whole, and the next page starts at row 52. The seed has 60 rows, so + this is a real page boundary and not the end of the table. +requests: + - id: r1 + method: GET + path: "/api/parts?limit=51&sort=id:asc" + expect: + status: 200 + body: + length: 51 + - id: r2 + method: GET + path: "/api/parts?limit=5&offset=51&sort=id:asc" + expect: + status: 200 + body: + ids: [52, 53, 54, 55, 56] + - id: r3 + method: GET + path: "/api/parts?limit=0&withCount=1" + expect: + status: 200 + body: + envelope: true + rowsLength: 0 + total: 60 diff --git a/fixtures/api-contract-conformance/list-query/scenarios/pagination-invalid-value.yaml b/fixtures/api-contract-conformance/list-query/scenarios/pagination-invalid-value.yaml new file mode 100644 index 0000000000..92bc8a8942 --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/pagination-invalid-value.yaml @@ -0,0 +1,18 @@ +name: pagination-invalid-value +description: > + A limit or offset that is not a non-negative integer is refused with `pagination.invalid_value`. +requests: + - id: r1 + method: GET + path: "/api/parts?limit=abc" + expect: + status: 400 + body: + equals: {"error": "pagination.invalid_value", "param": "limit", "value": "abc", "expected": "a non-negative integer (0 or more)"} + - id: r2 + method: GET + path: "/api/parts?offset=-1" + expect: + status: 400 + body: + equals: {"error": "pagination.invalid_value", "param": "offset", "value": "-1", "expected": "a non-negative integer (0 or more)"} diff --git a/fixtures/api-contract-conformance/list-query/scenarios/search-is-case-insensitive.yaml b/fixtures/api-contract-conformance/list-query/scenarios/search-is-case-insensitive.yaml new file mode 100644 index 0000000000..7ec04bcae1 --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/search-is-case-insensitive.yaml @@ -0,0 +1,12 @@ +name: search-is-case-insensitive +description: > + `?search=` matches its term anywhere in a filterable text field, ignoring case: "pump" finds + "Pump Housing", "pump seal", "Bilge PUMP" and "Sump Pump". +requests: + - id: r1 + method: GET + path: "/api/parts?search=pump&sort=id:asc" + expect: + status: 200 + body: + ids: [7, 8, 9, 10] diff --git a/fixtures/api-contract-conformance/list-query/scenarios/search-matches-every-text-field.yaml b/fixtures/api-contract-conformance/list-query/scenarios/search-matches-every-text-field.yaml new file mode 100644 index 0000000000..045afc083a --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/search-matches-every-text-field.yaml @@ -0,0 +1,12 @@ +name: search-matches-every-text-field +description: > + Search covers every filterable text field, not only the first: "sku-05" matches the sku of + rows 50 to 59. +requests: + - id: r1 + method: GET + path: "/api/parts?search=sku-05&sort=id:asc" + expect: + status: 200 + body: + ids: [50, 51, 52, 53, 54, 55, 56, 57, 58, 59] diff --git a/fixtures/api-contract-conformance/list-query/scenarios/search-with-filter.yaml b/fixtures/api-contract-conformance/list-query/scenarios/search-with-filter.yaml new file mode 100644 index 0000000000..ab1c1763f1 --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/search-with-filter.yaml @@ -0,0 +1,11 @@ +name: search-with-filter +description: > + A search and a filter are both applied: the search narrows the rows the filter leaves. +requests: + - id: r1 + method: GET + path: "/api/parts?search=PUMP&filter[category][eq]=part&sort=id:asc" + expect: + status: 200 + body: + ids: [7, 10] diff --git a/fixtures/api-contract-conformance/list-query/scenarios/value-format-refused.yaml b/fixtures/api-contract-conformance/list-query/scenarios/value-format-refused.yaml new file mode 100644 index 0000000000..a3bd50cbf4 --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/scenarios/value-format-refused.yaml @@ -0,0 +1,29 @@ +name: value-format-refused +description: > + An operand that is not of the field's type is refused with `invalid_filter_value`, naming + the field, rather than reaching the store. +requests: + - id: r1 + method: GET + path: "/api/parts?filter[stock][gt]=abc" + expect: + status: 400 + body: + error: "invalid_filter_value" + field: "stock" + - id: r2 + method: GET + path: "/api/parts?filter[stock][gte]=2.5" + expect: + status: 400 + body: + error: "invalid_filter_value" + field: "stock" + - id: r3 + method: GET + path: "/api/parts?filter[category][eq]=gadget" + expect: + status: 400 + body: + error: "invalid_filter_value" + field: "category" diff --git a/fixtures/api-contract-conformance/list-query/seed.json b/fixtures/api-contract-conformance/list-query/seed.json new file mode 100644 index 0000000000..c259c3bec9 --- /dev/null +++ b/fixtures/api-contract-conformance/list-query/seed.json @@ -0,0 +1,484 @@ +{ + "rows": [ + { + "id": 1, + "name": "Anvil 01", + "sku": "SKU-001", + "category": "part", + "stock": 1, + "notes": "bin 1" + }, + { + "id": 2, + "name": "Bracket 02", + "sku": "SKU-002", + "category": "kit", + "stock": 2, + "notes": "bin 2" + }, + { + "id": 3, + "name": "Clamp 03", + "sku": "SKU-003", + "category": "tool", + "stock": 3, + "notes": "bin 3" + }, + { + "id": 4, + "name": "Drill 04", + "sku": "SKU-004", + "category": "part", + "stock": 4, + "notes": "bin 4" + }, + { + "id": 5, + "name": "Elbow 05", + "sku": "SKU-005", + "category": "kit", + "stock": 5, + "notes": "bin 5" + }, + { + "id": 6, + "name": "Flange 06", + "sku": "SKU-006", + "category": "tool", + "stock": 6, + "notes": "bin 6" + }, + { + "id": 7, + "name": "Pump Housing", + "sku": "SKU-007", + "category": "part", + "stock": 7, + "notes": "bin 0" + }, + { + "id": 8, + "name": "pump seal", + "sku": "SKU-008", + "category": "kit", + "stock": 8, + "notes": "bin 1" + }, + { + "id": 9, + "name": "Bilge PUMP", + "sku": "SKU-009", + "category": "tool", + "stock": 9, + "notes": "bin 2" + }, + { + "id": 10, + "name": "Sump Pump", + "sku": "SKU-010", + "category": "part", + "stock": 0, + "notes": "bin 3" + }, + { + "id": 11, + "name": "Knob 11", + "sku": "SKU-011", + "category": "kit", + "stock": 1, + "notes": "bin 4" + }, + { + "id": 12, + "name": "Lever 12", + "sku": "SKU-012", + "category": "tool", + "stock": 2, + "notes": "bin 5" + }, + { + "id": 13, + "name": "Anvil 13", + "sku": "SKU-013", + "category": "part", + "stock": 3, + "notes": "bin 6" + }, + { + "id": 14, + "name": "Bracket 14", + "sku": "SKU-014", + "category": "kit", + "stock": 4, + "notes": "bin 0" + }, + { + "id": 15, + "name": "Clamp 15", + "sku": "SKU-015", + "category": "tool", + "stock": 5, + "notes": "bin 1" + }, + { + "id": 16, + "name": "Drill 16", + "sku": "SKU-016", + "category": "part", + "stock": 6, + "notes": "bin 2" + }, + { + "id": 17, + "name": "Elbow 17", + "sku": "SKU-017", + "category": "kit", + "stock": 7, + "notes": "bin 3" + }, + { + "id": 18, + "name": "Flange 18", + "sku": "SKU-018", + "category": "tool", + "stock": 8, + "notes": "bin 4" + }, + { + "id": 19, + "name": "Gasket 19", + "sku": "SKU-019", + "category": "part", + "stock": 9, + "notes": "bin 5" + }, + { + "id": 20, + "name": "Hinge 20", + "sku": "SKU-020", + "category": "kit", + "stock": 0, + "notes": "bin 6" + }, + { + "id": 21, + "name": "Inlet 21", + "sku": "SKU-021", + "category": "tool", + "stock": 1, + "notes": "bin 0" + }, + { + "id": 22, + "name": "Jack 22", + "sku": "SKU-022", + "category": "part", + "stock": 2, + "notes": "bin 1" + }, + { + "id": 23, + "name": "Knob 23", + "sku": "SKU-023", + "category": "kit", + "stock": 3, + "notes": "bin 2" + }, + { + "id": 24, + "name": "Lever 24", + "sku": "SKU-024", + "category": "tool", + "stock": 4, + "notes": "bin 3" + }, + { + "id": 25, + "name": "Anvil 25", + "sku": "SKU-025", + "category": "part", + "stock": 5, + "notes": "bin 4" + }, + { + "id": 26, + "name": "Bracket 26", + "sku": "SKU-026", + "category": "kit", + "stock": 6, + "notes": "bin 5" + }, + { + "id": 27, + "name": "Clamp 27", + "sku": "SKU-027", + "category": "tool", + "stock": 7, + "notes": "bin 6" + }, + { + "id": 28, + "name": "Drill 28", + "sku": "SKU-028", + "category": "part", + "stock": 8, + "notes": "bin 0" + }, + { + "id": 29, + "name": "Elbow 29", + "sku": "SKU-029", + "category": "kit", + "stock": 9, + "notes": "bin 1" + }, + { + "id": 30, + "name": "Flange 30", + "sku": "SKU-030", + "category": "tool", + "stock": 0, + "notes": "bin 2" + }, + { + "id": 31, + "name": "Gasket 31", + "sku": "SKU-031", + "category": "part", + "stock": 1, + "notes": "bin 3" + }, + { + "id": 32, + "name": "Hinge 32", + "sku": "SKU-032", + "category": "kit", + "stock": 2, + "notes": "bin 4" + }, + { + "id": 33, + "name": "Inlet 33", + "sku": "SKU-033", + "category": "tool", + "stock": 3, + "notes": "bin 5" + }, + { + "id": 34, + "name": "Jack 34", + "sku": "SKU-034", + "category": "part", + "stock": 4, + "notes": "bin 6" + }, + { + "id": 35, + "name": "Knob 35", + "sku": "SKU-035", + "category": "kit", + "stock": 5, + "notes": "bin 0" + }, + { + "id": 36, + "name": "Lever 36", + "sku": "SKU-036", + "category": "tool", + "stock": 6, + "notes": "bin 1" + }, + { + "id": 37, + "name": "Anvil 37", + "sku": "SKU-037", + "category": "part", + "stock": 7, + "notes": "bin 2" + }, + { + "id": 38, + "name": "Bracket 38", + "sku": "SKU-038", + "category": "kit", + "stock": 8, + "notes": "bin 3" + }, + { + "id": 39, + "name": "Clamp 39", + "sku": "SKU-039", + "category": "tool", + "stock": 9, + "notes": "bin 4" + }, + { + "id": 40, + "name": "Drill 40", + "sku": "SKU-040", + "category": "part", + "stock": 0, + "notes": "bin 5" + }, + { + "id": 41, + "name": "Elbow 41", + "sku": "SKU-041", + "category": "kit", + "stock": 1, + "notes": "bin 6" + }, + { + "id": 42, + "name": "Flange 42", + "sku": "SKU-042", + "category": "tool", + "stock": 2, + "notes": "bin 0" + }, + { + "id": 43, + "name": "Gasket 43", + "sku": "SKU-043", + "category": "part", + "stock": 3, + "notes": "bin 1" + }, + { + "id": 44, + "name": "Hinge 44", + "sku": "SKU-044", + "category": "kit", + "stock": 4, + "notes": "bin 2" + }, + { + "id": 45, + "name": "Inlet 45", + "sku": "SKU-045", + "category": "tool", + "stock": 5, + "notes": "bin 3" + }, + { + "id": 46, + "name": "Jack 46", + "sku": "SKU-046", + "category": "part", + "stock": 6, + "notes": "bin 4" + }, + { + "id": 47, + "name": "Knob 47", + "sku": "SKU-047", + "category": "kit", + "stock": 7, + "notes": "bin 5" + }, + { + "id": 48, + "name": "Lever 48", + "sku": "SKU-048", + "category": "tool", + "stock": 8, + "notes": "bin 6" + }, + { + "id": 49, + "name": "Anvil 49", + "sku": "SKU-049", + "category": "part", + "stock": 9, + "notes": "bin 0" + }, + { + "id": 50, + "name": "Bracket 50", + "sku": "SKU-050", + "category": "kit", + "stock": 0, + "notes": "bin 1" + }, + { + "id": 51, + "name": "Clamp 51", + "sku": "SKU-051", + "category": "tool", + "stock": 1, + "notes": "bin 2" + }, + { + "id": 52, + "name": "Drill 52", + "sku": "SKU-052", + "category": "part", + "stock": 2, + "notes": "bin 3" + }, + { + "id": 53, + "name": "Elbow 53", + "sku": "SKU-053", + "category": "kit", + "stock": 3, + "notes": "bin 4" + }, + { + "id": 54, + "name": "Flange 54", + "sku": "SKU-054", + "category": "tool", + "stock": 4, + "notes": "bin 5" + }, + { + "id": 55, + "name": "Gasket 55", + "sku": "SKU-055", + "category": "part", + "stock": 5, + "notes": "bin 6" + }, + { + "id": 56, + "name": "Hinge 56", + "sku": "SKU-056", + "category": "kit", + "stock": 6, + "notes": "bin 0" + }, + { + "id": 57, + "name": "Inlet 57", + "sku": "SKU-057", + "category": "tool", + "stock": 7, + "notes": "bin 1" + }, + { + "id": 58, + "name": "Jack 58", + "sku": "SKU-058", + "category": "part", + "stock": 8, + "notes": "bin 2" + }, + { + "id": 59, + "name": "Knob 59", + "sku": "SKU-059", + "category": "kit", + "stock": 9, + "notes": "bin 3" + }, + { + "id": 60, + "name": "Lever 60", + "sku": "SKU-060", + "category": "tool", + "stock": 0, + "notes": "bin 4" + } + ] +} diff --git a/fixtures/codegen-skip-conformance/cases.json b/fixtures/codegen-skip-conformance/cases.json index 3d337503ca..483e2b8a8a 100644 --- a/fixtures/codegen-skip-conformance/cases.json +++ b/fixtures/codegen-skip-conformance/cases.json @@ -157,6 +157,12 @@ "change": "A run that started after an input change failed; the input is then restored to what the last successful run saw.", "gen": "regenerate", "verify": "must-render" + }, + { + "id": "template-and-docs-rerun", + "change": "The project also configures a `template` generator (a project template under the declared template root, rendered once per entity) and a docs page generator. Nothing changes between the two runs. Besides the two answers, the runner then forces a full render (`--force`, or the port's equivalent) and asserts it wrote zero files: no generated file, template output, docs page or hash manifest changed its bytes or its modification time. A port with no `template` generator names the case with its reason.", + "gen": "skip", + "verify": "may-answer-no-drift" } ] } diff --git a/fixtures/docs-page-conformance/README.md b/fixtures/docs-page-conformance/README.md new file mode 100644 index 0000000000..d4912f0cbb --- /dev/null +++ b/fixtures/docs-page-conformance/README.md @@ -0,0 +1,82 @@ +# docs-page-conformance + +The shared corpus for the documentation pages every port writes from the requirement +ledger and the model: `requirements.md`, `requirements.toon`, `agent/requirements.md` and +the **model-only** `agent/schema.md`. + +**The TypeScript generators are the source of the expected bytes.** A port that disagrees +with a case is wrong, not the case. + +## How a page is made + +Every page is a shared Mustache template fed the data a builder computes: + +| Page | Template (canonical copy) | Data | +|---|---|---| +| `requirements.md` | `templates/requirements/requirements.md.mustache` | `data/requirements.md.json` | +| `requirements.toon` | `templates/requirements/requirements.toon.mustache` | `data/requirements.toon.json` | +| `agent/requirements.md` | `templates/agent/requirements.md.mustache` | `data/agent-requirements.md.json` | +| `agent/schema.md` | `templates/agent/schema.md.mustache` | `data/agent-schema.md.json` | + +The builder makes every decision: heading depth, which title survives, the fact bar, the +heading demotion of the embedded ledger, every table cell, TOON quoting. The template only +lays the lines out. So a port renders the SAME template file from the same data, and a case +has two checks: + +1. **Builder.** The port's builder, run on `input/`, produces `expected/data/.json` + (compare as JSON values). +2. **Page.** Rendering the template with that data produces `expected/` byte for byte. + +A page the case does not list is a page the port must NOT write: a model with no +`requirement.*` node gets neither requirements page, and a model with no table and no view +gets no schema page. + +Two rules a port must keep. `agent/requirements.md` carries the ledger as its `ledger` +value: the `requirements.md` template rendered in its `embedded` form (no `# Requirements` +title, every heading one level down, capped at h6), with its trailing line breaks removed. +The TOON page ends without a line break; the other pages end with exactly one. + +## What a non-TypeScript schema page contains (design call 17) + +A port without the expected schema builds the schema page from the model with its own +naming helpers. TypeScript writes the same page with `physical: false`: it builds its input +from the expected schema and then leaves out every fact only that schema knows. The page +contains: + +- **Tables**: one per object whose primary source is a table in the schema (abstract bases + and sourceless values have none; a TPH subtype shares its base's table and adds its own + columns after the base's), sorted by physical name. Each has the declaring object's FQN, + its `description`, and a column table of column name, declaring field (first writer wins + on a shared table), declared type (`field.`), nullability (`no` for a primary-key + column or a required field) and key (`PK`, `PK (composite)`, `FK → `). Column + descriptions follow the table, then the foreign keys as columns → target table (target + key columns). +- **Views**: one per view source, sorted by name, with the declaring object and the + `origin.*` lineage of each column. The intro names a report's dimensions and measures when + a view-backed `object.report` owns one of them. +- **Relationships**: every relationship as written in the model, with its cardinality read + from the declaring side and the authored `@onDelete`. +- **Enums**: every enum field of a table-backed object, its members and its storage + (string-backed, or int-backed with the member map). + +It leaves out the dialect facts: the SQL type and default columns, indexes (and the +`unique` / `indexed` key roles they give), checks (and the Enums sentence that points at +them), foreign-key constraint names and referential actions. Only the TypeScript page, +written from the expected schema, carries those; `agent/ui.md` stays a TypeScript page. + +## Cases + +| Case | Pins | +|---|---| +| `ledger-and-claims` | A nested functional tree (L1 to L5, heading depth to h6 when embedded), a title that is kept, a description holding a `#` line, a statement with a line break and one with a `\|`, an architectural entry with no level, a retired entry (in the ledger, in no index), the node index with its statements, TOON quoting of commas, colons and line breaks. | +| `ledger-unclaimed` | One requirement (the singular count), no claim (the "No requirement resolves" paragraph), a disposition, a statement TOON must quote because it reads as a literal (`true`). | +| `schema-model` | Tables with descriptions, an increment key, a TPH subtype's column on its base table, a foreign key, a view with passthrough and aggregate lineage, relationships both ways, string- and int-backed enums, a sourceless value's enum left out. | +| `schema-report-view` | A report's view (the Views intro that names reports), the description nudge, a `@default` left off the page. | + +## Runners + +- TypeScript: `server/typescript/packages/cli/test/docs-page-conformance.test.ts`. + Regenerate with `UPDATE_DOCS_PAGE_FIXTURES=1 bun test test/docs-page-conformance.test.ts` + from that package, and review the diff: it is the cross-port contract. +- C#, Java (Kotlin through Java), Python and Rust: their page generators are planned and + will run every case. diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/agent/requirements.md b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/agent/requirements.md new file mode 100644 index 0000000000..4ede596108 --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/agent/requirements.md @@ -0,0 +1,97 @@ + + +# Requirements + +Read this before adding a capability, and before extending anything that looks like it already does what you were asked for. + +- A requirement is **prescriptive**: it states what should be true, never what happened. `status: retired` means the capability was BUILT and deliberately REMOVED — that entry is a prohibition, not history, and the right response to it is to stop, not to rebuild. +- The **node index** below answers *"does anything claim the thing I am about to change?"*. Match the literal FQN. +- **The ledger under it is not the same list.** A retired capability carries no `@implementedBy` — there is nothing left to point at — so it appears there and in no index. Read it before you conclude a capability does not exist yet. + +## Node index + +| Node | Kind | Claimed by | +|---|---|---| +| `acme::shop::Invoice` | `object.entity` | `MoneyIsExactMinorUnits` (live) | +| `acme::shop::Order` | `object.entity` | `Storefront.OrderService.OrderRecord` L4 (live) | +| `acme::shop::Order.placedAt` | `field.timestamp` | `Storefront.OrderService.OrderRecord` L4 (live) | +| `acme::shop::Order.reference` | `field.string` | `Storefront.OrderService.OrderRecord.TranscribableReference` L5 (live) | + +### What those requirements say + +- `MoneyIsExactMinorUnits` (`architectural`) — Monetary amounts are stored as exact integer minor units, never as floating point +- `Storefront.OrderService.OrderRecord` (`functional`) — An order records what was bought, for how much, and when: placed \| paid +- `Storefront.OrderService.OrderRecord.TranscribableReference` (`functional`) — An order carries a reference a customer can read down a phone line + +## The ledger + +7 declared requirements, in declaration order. + +### Storefront + +`functional` · **L1** · status: `live` + +The storefront solution + +**Counterexample:** Nothing can be sold + +#### Storefront.OrderService + +`functional` · **L3** · status: `live` + +Every placed order is recorded before payment is attempted + +**Counterexample:** A payment attempted against an order that was never stored + +Recording first is what lets a failed payment be retried. + +## Why first + +A payment with no order is a refund nobody can trace. + +##### Storefront.OrderService.OrderRecord — What an order must hold + +`functional` · **L4** · status: `live` + +An order records what was bought, for how much, and when: placed | paid + +**Counterexample:** An order row that cannot say who placed it + +**Implemented by:** `acme::shop::Order`, `acme::shop::Order.placedAt` + +###### Storefront.OrderService.OrderRecord.TranscribableReference + +`functional` · **L5** · status: `live` + +An order carries a reference a customer can read +down a phone line + +**Counterexample:** A reference that is a raw uuid + +**Implemented by:** `acme::shop::Order.reference` + +###### Storefront.OrderService.OrderRecord.OrderExpiry + +`functional` · **L5** · status: `planned` · tracked: acme/shop#412 + +An unpaid order carries the instant it stops being reservable + +**Counterexample:** Stock held indefinitely against an order nobody paid for + +### MoneyIsExactMinorUnits + +`architectural` · status: `live` + +Monetary amounts are stored as exact integer minor units, never as floating point + +**Counterexample:** A cent that disappears when a total is split three ways + +**Implemented by:** `acme::shop::Invoice` + +### GuestCheckout + +`functional` · **L4** · status: `retired` + +A visitor can check out without an account + +**Counterexample:** An order with no way to reach the person who placed it diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/agent/schema.md b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/agent/schema.md new file mode 100644 index 0000000000..d93ba79792 --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/agent/schema.md @@ -0,0 +1,34 @@ + + +# Schema + +The tables, columns and keys this model declares. Read it before writing a query, a migration, or anything that names a table or a column. SQL types, defaults, indexes, checks, constraint names and referential actions are not on this page: the migration files carry them. + +- The **DDL is not repeated here.** The migration files are the DDL, they are generated, and they are what runs — this page describes the schema they produce. +- Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. +- `Field` and `Declared` are the METADATA names. Edit those; the column name follows. + +## Tables + +### `invoices` + +Declared by `acme::shop::Invoice`. + +| Column | Field | Declared | Null | Key | +|---|---|---|---|---| +| `id` | `id` | `field.long` | no | PK | +| `total_cents` | `totalCents` | `field.currency` | no | | + +### `orders` + +Declared by `acme::shop::Order`. + +> A customer's order, from cart to fulfilment. + +| Column | Field | Declared | Null | Key | +|---|---|---|---|---| +| `id` | `id` | `field.uuid` | no | PK | +| `reference` | `reference` | `field.string` | no | | +| `placed_at` | `placedAt` | `field.timestamp` | no | | + +- `reference` — The code a customer reads down a phone line. diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/agent-requirements.md.json b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/agent-requirements.md.json new file mode 100644 index 0000000000..3cfe8be3c3 --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/agent-requirements.md.json @@ -0,0 +1,45 @@ +{ + "generatedMarker": "", + "hasNodeIndex": true, + "nodeIndex": [ + { + "address": "acme::shop::Invoice", + "concern": "object.entity", + "claims": "`MoneyIsExactMinorUnits` (live)" + }, + { + "address": "acme::shop::Order", + "concern": "object.entity", + "claims": "`Storefront.OrderService.OrderRecord` L4 (live)" + }, + { + "address": "acme::shop::Order.placedAt", + "concern": "field.timestamp", + "claims": "`Storefront.OrderService.OrderRecord` L4 (live)" + }, + { + "address": "acme::shop::Order.reference", + "concern": "field.string", + "claims": "`Storefront.OrderService.OrderRecord.TranscribableReference` L5 (live)" + } + ], + "hasStatements": true, + "statements": [ + { + "path": "MoneyIsExactMinorUnits", + "subType": "architectural", + "statement": "Monetary amounts are stored as exact integer minor units, never as floating point" + }, + { + "path": "Storefront.OrderService.OrderRecord", + "subType": "functional", + "statement": "An order records what was bought, for how much, and when: placed \\| paid" + }, + { + "path": "Storefront.OrderService.OrderRecord.TranscribableReference", + "subType": "functional", + "statement": "An order carries a reference a customer can read down a phone line" + } + ], + "ledger": "7 declared requirements, in declaration order.\n\n### Storefront\n\n`functional` · **L1** · status: `live`\n\nThe storefront solution\n\n**Counterexample:** Nothing can be sold\n\n#### Storefront.OrderService\n\n`functional` · **L3** · status: `live`\n\nEvery placed order is recorded before payment is attempted\n\n**Counterexample:** A payment attempted against an order that was never stored\n\nRecording first is what lets a failed payment be retried.\n\n## Why first\n\nA payment with no order is a refund nobody can trace.\n\n##### Storefront.OrderService.OrderRecord — What an order must hold\n\n`functional` · **L4** · status: `live`\n\nAn order records what was bought, for how much, and when: placed | paid\n\n**Counterexample:** An order row that cannot say who placed it\n\n**Implemented by:** `acme::shop::Order`, `acme::shop::Order.placedAt`\n\n###### Storefront.OrderService.OrderRecord.TranscribableReference\n\n`functional` · **L5** · status: `live`\n\nAn order carries a reference a customer can read\ndown a phone line\n\n**Counterexample:** A reference that is a raw uuid\n\n**Implemented by:** `acme::shop::Order.reference`\n\n###### Storefront.OrderService.OrderRecord.OrderExpiry\n\n`functional` · **L5** · status: `planned` · tracked: acme/shop#412\n\nAn unpaid order carries the instant it stops being reservable\n\n**Counterexample:** Stock held indefinitely against an order nobody paid for\n\n### MoneyIsExactMinorUnits\n\n`architectural` · status: `live`\n\nMonetary amounts are stored as exact integer minor units, never as floating point\n\n**Counterexample:** A cent that disappears when a total is split three ways\n\n**Implemented by:** `acme::shop::Invoice`\n\n### GuestCheckout\n\n`functional` · **L4** · status: `retired`\n\nA visitor can check out without an account\n\n**Counterexample:** An order with no way to reach the person who placed it" +} diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/agent-schema.md.json b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/agent-schema.md.json new file mode 100644 index 0000000000..2d8391a6ab --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/agent-schema.md.json @@ -0,0 +1,95 @@ +{ + "generatedMarker": "", + "physical": false, + "dialect": "", + "descriptionNudge": false, + "hasTables": true, + "tables": [ + { + "heading": "`invoices`", + "tableDeclaredBy": "acme::shop::Invoice", + "columns": [ + { + "name": "id", + "fieldCell": "`id`", + "declaredCell": "`field.long`", + "sqlTypeCell": "", + "nullCell": "no", + "defaultCell": "", + "keyCell": "PK" + }, + { + "name": "total_cents", + "fieldCell": "`totalCents`", + "declaredCell": "`field.currency`", + "sqlTypeCell": "", + "nullCell": "no", + "defaultCell": "", + "keyCell": "" + } + ], + "hasDescribed": false, + "described": [], + "hasIndexes": false, + "indexes": [], + "hasForeignKeys": false, + "foreignKeys": [], + "hasChecks": false, + "checks": [] + }, + { + "heading": "`orders`", + "tableDeclaredBy": "acme::shop::Order", + "tableDescription": "A customer's order, from cart to fulfilment.", + "columns": [ + { + "name": "id", + "fieldCell": "`id`", + "declaredCell": "`field.uuid`", + "sqlTypeCell": "", + "nullCell": "no", + "defaultCell": "", + "keyCell": "PK" + }, + { + "name": "reference", + "fieldCell": "`reference`", + "declaredCell": "`field.string`", + "sqlTypeCell": "", + "nullCell": "no", + "defaultCell": "", + "keyCell": "" + }, + { + "name": "placed_at", + "fieldCell": "`placedAt`", + "declaredCell": "`field.timestamp`", + "sqlTypeCell": "", + "nullCell": "no", + "defaultCell": "", + "keyCell": "" + } + ], + "hasDescribed": true, + "described": [ + { + "name": "reference", + "text": "The code a customer reads down a phone line." + } + ], + "hasIndexes": false, + "indexes": [], + "hasForeignKeys": false, + "foreignKeys": [], + "hasChecks": false, + "checks": [] + } + ], + "hasViews": false, + "hasReportView": false, + "views": [], + "hasRelationships": false, + "relationships": [], + "hasEnums": false, + "enums": [] +} diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/requirements.md.json b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/requirements.md.json new file mode 100644 index 0000000000..2e53f21d77 --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/requirements.md.json @@ -0,0 +1,53 @@ +{ + "embedded": false, + "count": 7, + "plural": "s", + "entries": [ + { + "heading": "## Storefront", + "facts": "`functional` · **L1** · status: `live`", + "statement": "The storefront solution", + "counterexample": "**Counterexample:** Nothing can be sold" + }, + { + "heading": "### Storefront.OrderService", + "facts": "`functional` · **L3** · status: `live`", + "statement": "Every placed order is recorded before payment is attempted", + "counterexample": "**Counterexample:** A payment attempted against an order that was never stored", + "description": "Recording first is what lets a failed payment be retried.\n\n# Why first\n\nA payment with no order is a refund nobody can trace." + }, + { + "heading": "#### Storefront.OrderService.OrderRecord — What an order must hold", + "facts": "`functional` · **L4** · status: `live`", + "statement": "An order records what was bought, for how much, and when: placed | paid", + "counterexample": "**Counterexample:** An order row that cannot say who placed it", + "implementedBy": "**Implemented by:** `acme::shop::Order`, `acme::shop::Order.placedAt`" + }, + { + "heading": "##### Storefront.OrderService.OrderRecord.TranscribableReference", + "facts": "`functional` · **L5** · status: `live`", + "statement": "An order carries a reference a customer can read\ndown a phone line", + "counterexample": "**Counterexample:** A reference that is a raw uuid", + "implementedBy": "**Implemented by:** `acme::shop::Order.reference`" + }, + { + "heading": "##### Storefront.OrderService.OrderRecord.OrderExpiry", + "facts": "`functional` · **L5** · status: `planned` · tracked: acme/shop#412", + "statement": "An unpaid order carries the instant it stops being reservable", + "counterexample": "**Counterexample:** Stock held indefinitely against an order nobody paid for" + }, + { + "heading": "## MoneyIsExactMinorUnits", + "facts": "`architectural` · status: `live`", + "statement": "Monetary amounts are stored as exact integer minor units, never as floating point", + "counterexample": "**Counterexample:** A cent that disappears when a total is split three ways", + "implementedBy": "**Implemented by:** `acme::shop::Invoice`" + }, + { + "heading": "## GuestCheckout", + "facts": "`functional` · **L4** · status: `retired`", + "statement": "A visitor can check out without an account", + "counterexample": "**Counterexample:** An order with no way to reach the person who placed it" + } + ] +} diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/requirements.toon.json b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/requirements.toon.json new file mode 100644 index 0000000000..64b6ca0448 --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/requirements.toon.json @@ -0,0 +1,27 @@ +{ + "count": 7, + "fields": "{path,subType,level,status,disposition,claims,statement}", + "rows": [ + { + "line": "Storefront,functional,1,live,\"\",\"\",The storefront solution" + }, + { + "line": "Storefront.OrderService,functional,3,live,\"\",\"\",Every placed order is recorded before payment is attempted" + }, + { + "line": "Storefront.OrderService.OrderRecord,functional,4,live,\"\",\"acme::shop::Order acme::shop::Order.placedAt\",\"An order records what was bought, for how much, and when: placed | paid\"" + }, + { + "line": "Storefront.OrderService.OrderRecord.TranscribableReference,functional,5,live,\"\",\"acme::shop::Order.reference\",\"An order carries a reference a customer can read\\ndown a phone line\"" + }, + { + "line": "Storefront.OrderService.OrderRecord.OrderExpiry,functional,5,planned,\"\",\"\",An unpaid order carries the instant it stops being reservable" + }, + { + "line": "MoneyIsExactMinorUnits,architectural,\"\",live,\"\",\"acme::shop::Invoice\",\"Monetary amounts are stored as exact integer minor units, never as floating point\"" + }, + { + "line": "GuestCheckout,functional,4,retired,\"\",\"\",A visitor can check out without an account" + } + ] +} diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/requirements.md b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/requirements.md new file mode 100644 index 0000000000..799e1ed6b7 --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/requirements.md @@ -0,0 +1,72 @@ +# Requirements + +7 declared requirements, in declaration order. + +## Storefront + +`functional` · **L1** · status: `live` + +The storefront solution + +**Counterexample:** Nothing can be sold + +### Storefront.OrderService + +`functional` · **L3** · status: `live` + +Every placed order is recorded before payment is attempted + +**Counterexample:** A payment attempted against an order that was never stored + +Recording first is what lets a failed payment be retried. + +# Why first + +A payment with no order is a refund nobody can trace. + +#### Storefront.OrderService.OrderRecord — What an order must hold + +`functional` · **L4** · status: `live` + +An order records what was bought, for how much, and when: placed | paid + +**Counterexample:** An order row that cannot say who placed it + +**Implemented by:** `acme::shop::Order`, `acme::shop::Order.placedAt` + +##### Storefront.OrderService.OrderRecord.TranscribableReference + +`functional` · **L5** · status: `live` + +An order carries a reference a customer can read +down a phone line + +**Counterexample:** A reference that is a raw uuid + +**Implemented by:** `acme::shop::Order.reference` + +##### Storefront.OrderService.OrderRecord.OrderExpiry + +`functional` · **L5** · status: `planned` · tracked: acme/shop#412 + +An unpaid order carries the instant it stops being reservable + +**Counterexample:** Stock held indefinitely against an order nobody paid for + +## MoneyIsExactMinorUnits + +`architectural` · status: `live` + +Monetary amounts are stored as exact integer minor units, never as floating point + +**Counterexample:** A cent that disappears when a total is split three ways + +**Implemented by:** `acme::shop::Invoice` + +## GuestCheckout + +`functional` · **L4** · status: `retired` + +A visitor can check out without an account + +**Counterexample:** An order with no way to reach the person who placed it diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/requirements.toon b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/requirements.toon new file mode 100644 index 0000000000..5e8d5a6aab --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/requirements.toon @@ -0,0 +1,8 @@ +requirements[7]{path,subType,level,status,disposition,claims,statement}: + Storefront,functional,1,live,"","",The storefront solution + Storefront.OrderService,functional,3,live,"","",Every placed order is recorded before payment is attempted + Storefront.OrderService.OrderRecord,functional,4,live,"","acme::shop::Order acme::shop::Order.placedAt","An order records what was bought, for how much, and when: placed | paid" + Storefront.OrderService.OrderRecord.TranscribableReference,functional,5,live,"","acme::shop::Order.reference","An order carries a reference a customer can read\ndown a phone line" + Storefront.OrderService.OrderRecord.OrderExpiry,functional,5,planned,"","",An unpaid order carries the instant it stops being reservable + MoneyIsExactMinorUnits,architectural,"",live,"","acme::shop::Invoice","Monetary amounts are stored as exact integer minor units, never as floating point" + GuestCheckout,functional,4,retired,"","",A visitor can check out without an account \ No newline at end of file diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/input/meta.requirements.json b/fixtures/docs-page-conformance/cases/ledger-and-claims/input/meta.requirements.json new file mode 100644 index 0000000000..e9cc045b50 --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-and-claims/input/meta.requirements.json @@ -0,0 +1,91 @@ +{ + "metadata.root": { + "package": "acme::caps", + "children": [ + { + "requirement.functional": { + "name": "Storefront", + "@level": 1, + "@status": "live", + "@statement": "The storefront solution", + "@counterexample": "Nothing can be sold", + "children": [ + { + "requirement.functional": { + "name": "OrderService", + "@title": "Order service", + "@level": 3, + "@status": "live", + "@statement": "Every placed order is recorded before payment is attempted", + "@counterexample": "A payment attempted against an order that was never stored", + "@description": "Recording first is what lets a failed payment be retried.\n\n# Why first\n\nA payment with no order is a refund nobody can trace.", + "children": [ + { + "requirement.functional": { + "name": "OrderRecord", + "@title": "What an order must hold", + "@level": 4, + "@status": "live", + "@statement": "An order records what was bought, for how much, and when: placed | paid", + "@counterexample": "An order row that cannot say who placed it", + "@implementedBy": [ + "acme::shop::Order", + "acme::shop::Order.placedAt" + ], + "children": [ + { + "requirement.functional": { + "name": "TranscribableReference", + "@level": 5, + "@status": "live", + "@statement": "An order carries a reference a customer can read\ndown a phone line", + "@counterexample": "A reference that is a raw uuid", + "@implementedBy": [ + "acme::shop::Order.reference" + ] + } + }, + { + "requirement.functional": { + "name": "OrderExpiry", + "@level": 5, + "@status": "planned", + "@statement": "An unpaid order carries the instant it stops being reservable", + "@counterexample": "Stock held indefinitely against an order nobody paid for", + "@trackedBy": [ + "acme/shop#412" + ] + } + } + ] + } + } + ] + } + } + ] + } + }, + { + "requirement.architectural": { + "name": "MoneyIsExactMinorUnits", + "@status": "live", + "@statement": "Monetary amounts are stored as exact integer minor units, never as floating point", + "@counterexample": "A cent that disappears when a total is split three ways", + "@implementedBy": [ + "acme::shop::Invoice" + ] + } + }, + { + "requirement.functional": { + "name": "GuestCheckout", + "@level": 4, + "@status": "retired", + "@statement": "A visitor can check out without an account", + "@counterexample": "An order with no way to reach the person who placed it" + } + } + ] + } +} diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/input/meta.shop.json b/fixtures/docs-page-conformance/cases/ledger-and-claims/input/meta.shop.json new file mode 100644 index 0000000000..0f40f953e9 --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-and-claims/input/meta.shop.json @@ -0,0 +1,78 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "object.entity": { + "name": "Order", + "@description": "A customer's order, from cart to fulfilment.", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.uuid": { + "name": "id" + } + }, + { + "field.string": { + "name": "reference", + "@required": true, + "@description": "The code a customer reads down a phone line." + } + }, + { + "field.timestamp": { + "name": "placedAt", + "@required": true + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "Invoice", + "children": [ + { + "source.rdb": { + "@table": "invoices" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.currency": { + "name": "totalCents", + "@required": true + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ], + "@generation": "increment" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/agent/requirements.md b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/agent/requirements.md new file mode 100644 index 0000000000..9fa4c3d7ed --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/agent/requirements.md @@ -0,0 +1,25 @@ + + +# Requirements + +Read this before adding a capability, and before extending anything that looks like it already does what you were asked for. + +- A requirement is **prescriptive**: it states what should be true, never what happened. `status: retired` means the capability was BUILT and deliberately REMOVED — that entry is a prohibition, not history, and the right response to it is to stop, not to rebuild. +- The **node index** below answers *"does anything claim the thing I am about to change?"*. Match the literal FQN. +- **The ledger under it is not the same list.** A retired capability carries no `@implementedBy` — there is nothing left to point at — so it appears there and in no index. Read it before you conclude a capability does not exist yet. + +## Node index + +No requirement resolves to a model node. The common reason is the ordinary one: an entry at L4 or L5 that simply declares no `@implementedBy` yet, which is legal and is what a `planned` entry looks like. The others are an entry sitting ABOVE the L4 link floor (where a claim is not permitted), a `retired` entry (where it is forbidden outright), and a claim that names a node nothing resolves — `meta verify` is what says which. + +## The ledger + +1 declared requirement, in declaration order. + +### ExportsAreResumable + +`functional` · **L4** · status: `planned` · disposition: `deferred` + +true + +**Counterexample:** A 2 GB export that restarts from zero after a dropped connection diff --git a/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/agent-requirements.md.json b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/agent-requirements.md.json new file mode 100644 index 0000000000..1d03ae17ba --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/agent-requirements.md.json @@ -0,0 +1,8 @@ +{ + "generatedMarker": "", + "hasNodeIndex": false, + "nodeIndex": [], + "hasStatements": false, + "statements": [], + "ledger": "1 declared requirement, in declaration order.\n\n### ExportsAreResumable\n\n`functional` · **L4** · status: `planned` · disposition: `deferred`\n\ntrue\n\n**Counterexample:** A 2 GB export that restarts from zero after a dropped connection" +} diff --git a/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/requirements.md.json b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/requirements.md.json new file mode 100644 index 0000000000..9764aa2e2e --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/requirements.md.json @@ -0,0 +1,13 @@ +{ + "embedded": false, + "count": 1, + "plural": "", + "entries": [ + { + "heading": "## ExportsAreResumable", + "facts": "`functional` · **L4** · status: `planned` · disposition: `deferred`", + "statement": "true", + "counterexample": "**Counterexample:** A 2 GB export that restarts from zero after a dropped connection" + } + ] +} diff --git a/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/requirements.toon.json b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/requirements.toon.json new file mode 100644 index 0000000000..40cc78b29e --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/requirements.toon.json @@ -0,0 +1,9 @@ +{ + "count": 1, + "fields": "{path,subType,level,status,disposition,claims,statement}", + "rows": [ + { + "line": "ExportsAreResumable,functional,4,planned,deferred,\"\",\"true\"" + } + ] +} diff --git a/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/requirements.md b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/requirements.md new file mode 100644 index 0000000000..eec567a3ae --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/requirements.md @@ -0,0 +1,11 @@ +# Requirements + +1 declared requirement, in declaration order. + +## ExportsAreResumable + +`functional` · **L4** · status: `planned` · disposition: `deferred` + +true + +**Counterexample:** A 2 GB export that restarts from zero after a dropped connection diff --git a/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/requirements.toon b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/requirements.toon new file mode 100644 index 0000000000..6df1f1e80a --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/requirements.toon @@ -0,0 +1,2 @@ +requirements[1]{path,subType,level,status,disposition,claims,statement}: + ExportsAreResumable,functional,4,planned,deferred,"","true" \ No newline at end of file diff --git a/fixtures/docs-page-conformance/cases/ledger-unclaimed/input/meta.requirements.json b/fixtures/docs-page-conformance/cases/ledger-unclaimed/input/meta.requirements.json new file mode 100644 index 0000000000..348477de5c --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-unclaimed/input/meta.requirements.json @@ -0,0 +1,17 @@ +{ + "metadata.root": { + "package": "acme::caps", + "children": [ + { + "requirement.functional": { + "name": "ExportsAreResumable", + "@level": 4, + "@status": "planned", + "@statement": "true", + "@counterexample": "A 2 GB export that restarts from zero after a dropped connection", + "@disposition": "deferred" + } + } + ] + } +} diff --git a/fixtures/docs-page-conformance/cases/schema-model/expected/agent/schema.md b/fixtures/docs-page-conformance/cases/schema-model/expected/agent/schema.md new file mode 100644 index 0000000000..9ab77ccb05 --- /dev/null +++ b/fixtures/docs-page-conformance/cases/schema-model/expected/agent/schema.md @@ -0,0 +1,69 @@ + + +# Schema + +The tables, columns and keys this model declares. Read it before writing a query, a migration, or anything that names a table or a column. SQL types, defaults, indexes, checks, constraint names and referential actions are not on this page: the migration files carry them. + +- The **DDL is not repeated here.** The migration files are the DDL, they are generated, and they are what runs — this page describes the schema they produce. +- Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. +- `Field` and `Declared` are the METADATA names. Edit those; the column name follows. + +## Tables + +### `owners` + +Declared by `acme::fleet::Owner`. + +> A person or company that owns vehicles. + +| Column | Field | Declared | Null | Key | +|---|---|---|---|---| +| `id` | `id` | `field.long` | no | PK | +| `name` | `name` | `field.string` | no | | +| `tier` | `tier` | `field.enum` | yes | | +| `rating` | `rating` | `field.enum` | yes | | + +- `name` — The legal name, as registered. + +### `vehicles` + +Declared by `acme::fleet::Vehicle`. + +| Column | Field | Declared | Null | Key | +|---|---|---|---|---| +| `id` | `id` | `field.long` | no | PK | +| `kind` | `kind` | `field.string` | no | | +| `owner_id` | `ownerId` | `field.long` | yes | FK → `owners` | +| `doors` | `doors` | `field.int` | yes | | + +**Foreign keys** + +- `owner_id` → `owners`(`id`) + +## Views + +A view is generated from its projection's `origin.*` children — it is derived, never hand-written. Editing the view SQL directly is drift the tool cannot see. + +### `v_owner_summary` + +Declared by `acme::fleet::OwnerSummary`. + +| Column | Lineage | +|---|---| +| `name` | passthrough from `Owner.name` | +| `vehicle_count` | `count` of `Vehicle.id` via `Owner.vehicles` | + +## Relationships + +- `acme::fleet::Owner.vehicles` · `aggregation` · one-to-many → `Vehicle` +- `acme::fleet::Vehicle.owner` · `association` · many-to-one → `Owner` · on delete `cascade` +- `acme::fleet::Car.owner` · `association` · many-to-one → `Owner` · on delete `cascade` + +## Enums + +Members are the values the wire and the generated types use. + +| Field | Members | Storage | +|---|---|---| +| `acme::fleet::Owner.tier` | `standard`, `fleet` | string-backed | +| `acme::fleet::Owner.rating` | `LOW`, `HIGH` | int-backed (LOW=1, HIGH=2) | diff --git a/fixtures/docs-page-conformance/cases/schema-model/expected/data/agent-schema.md.json b/fixtures/docs-page-conformance/cases/schema-model/expected/data/agent-schema.md.json new file mode 100644 index 0000000000..e22d8bf393 --- /dev/null +++ b/fixtures/docs-page-conformance/cases/schema-model/expected/data/agent-schema.md.json @@ -0,0 +1,155 @@ +{ + "generatedMarker": "", + "physical": false, + "dialect": "", + "descriptionNudge": false, + "hasTables": true, + "tables": [ + { + "heading": "`owners`", + "tableDeclaredBy": "acme::fleet::Owner", + "tableDescription": "A person or company that owns vehicles.", + "columns": [ + { + "name": "id", + "fieldCell": "`id`", + "declaredCell": "`field.long`", + "sqlTypeCell": "", + "nullCell": "no", + "defaultCell": "", + "keyCell": "PK" + }, + { + "name": "name", + "fieldCell": "`name`", + "declaredCell": "`field.string`", + "sqlTypeCell": "", + "nullCell": "no", + "defaultCell": "", + "keyCell": "" + }, + { + "name": "tier", + "fieldCell": "`tier`", + "declaredCell": "`field.enum`", + "sqlTypeCell": "", + "nullCell": "yes", + "defaultCell": "", + "keyCell": "" + }, + { + "name": "rating", + "fieldCell": "`rating`", + "declaredCell": "`field.enum`", + "sqlTypeCell": "", + "nullCell": "yes", + "defaultCell": "", + "keyCell": "" + } + ], + "hasDescribed": true, + "described": [ + { + "name": "name", + "text": "The legal name, as registered." + } + ], + "hasIndexes": false, + "indexes": [], + "hasForeignKeys": false, + "foreignKeys": [], + "hasChecks": false, + "checks": [] + }, + { + "heading": "`vehicles`", + "tableDeclaredBy": "acme::fleet::Vehicle", + "columns": [ + { + "name": "id", + "fieldCell": "`id`", + "declaredCell": "`field.long`", + "sqlTypeCell": "", + "nullCell": "no", + "defaultCell": "", + "keyCell": "PK" + }, + { + "name": "kind", + "fieldCell": "`kind`", + "declaredCell": "`field.string`", + "sqlTypeCell": "", + "nullCell": "no", + "defaultCell": "", + "keyCell": "" + }, + { + "name": "owner_id", + "fieldCell": "`ownerId`", + "declaredCell": "`field.long`", + "sqlTypeCell": "", + "nullCell": "yes", + "defaultCell": "", + "keyCell": "FK → `owners`" + }, + { + "name": "doors", + "fieldCell": "`doors`", + "declaredCell": "`field.int`", + "sqlTypeCell": "", + "nullCell": "yes", + "defaultCell": "", + "keyCell": "" + } + ], + "hasDescribed": false, + "described": [], + "hasIndexes": false, + "indexes": [], + "hasForeignKeys": true, + "foreignKeys": [ + "`owner_id` → `owners`(`id`)" + ], + "hasChecks": false, + "checks": [] + } + ], + "hasViews": true, + "hasReportView": false, + "views": [ + { + "heading": "`v_owner_summary`", + "viewDeclaredBy": "acme::fleet::OwnerSummary", + "hasLineage": true, + "lineage": [ + { + "column": "name", + "text": "passthrough from `Owner.name`" + }, + { + "column": "vehicle_count", + "text": "`count` of `Vehicle.id` via `Owner.vehicles`" + } + ] + } + ], + "hasRelationships": true, + "relationships": [ + "`acme::fleet::Owner.vehicles` · `aggregation` · one-to-many → `Vehicle`", + "`acme::fleet::Vehicle.owner` · `association` · many-to-one → `Owner` · on delete `cascade`", + "`acme::fleet::Car.owner` · `association` · many-to-one → `Owner` · on delete `cascade`" + ], + "hasEnums": true, + "enums": [ + { + "field": "acme::fleet::Owner.tier", + "members": "`standard`, `fleet`", + "storage": "string-backed" + }, + { + "field": "acme::fleet::Owner.rating", + "members": "`LOW`, `HIGH`", + "storage": "int-backed (LOW=1, HIGH=2)" + } + ] +} diff --git a/fixtures/docs-page-conformance/cases/schema-model/input/meta.fleet.json b/fixtures/docs-page-conformance/cases/schema-model/input/meta.fleet.json new file mode 100644 index 0000000000..fc32e4b8bc --- /dev/null +++ b/fixtures/docs-page-conformance/cases/schema-model/input/meta.fleet.json @@ -0,0 +1,207 @@ +{ + "metadata.root": { + "package": "acme::fleet", + "children": [ + { + "object.entity": { + "name": "Owner", + "@description": "A person or company that owns vehicles.", + "children": [ + { + "source.rdb": { + "@table": "owners" + } + }, + { + "field.long": { + "name": "id", + "@required": true + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": "id", + "@generation": "increment" + } + }, + { + "field.string": { + "name": "name", + "@required": true, + "@description": "The legal name, as registered." + } + }, + { + "field.enum": { + "name": "tier", + "@values": [ + "standard", + "fleet" + ] + } + }, + { + "field.enum": { + "name": "rating", + "@values": [ + "LOW", + "HIGH" + ], + "@intValueMap": { + "LOW": 1, + "HIGH": 2 + } + } + }, + { + "relationship.aggregation": { + "name": "vehicles", + "@cardinality": "many", + "@objectRef": "Vehicle" + } + } + ] + } + }, + { + "object.entity": { + "name": "Vehicle", + "@discriminator": "kind", + "children": [ + { + "source.rdb": { + "@table": "vehicles" + } + }, + { + "field.long": { + "name": "id", + "@required": true + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": "id", + "@generation": "increment" + } + }, + { + "field.string": { + "name": "kind", + "@required": true + } + }, + { + "field.long": { + "name": "ownerId" + } + }, + { + "identity.reference": { + "name": "ownerRef", + "@fields": "ownerId", + "@references": "Owner" + } + }, + { + "relationship.association": { + "name": "owner", + "@cardinality": "one", + "@objectRef": "Owner", + "@onDelete": "cascade" + } + } + ] + } + }, + { + "object.entity": { + "name": "Car", + "extends": "Vehicle", + "@discriminatorValue": "Car", + "children": [ + { + "field.int": { + "name": "doors" + } + } + ] + } + }, + { + "object.value": { + "name": "Party", + "children": [ + { + "field.string": { + "name": "name" + } + }, + { + "field.enum": { + "name": "kind", + "@values": [ + "person", + "company" + ] + } + } + ] + } + }, + { + "object.projection": { + "name": "OwnerSummary", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_owner_summary" + } + }, + { + "field.long": { + "name": "id", + "extends": "Owner.id" + } + }, + { + "identity.primary": { + "name": "pk", + "extends": "Owner.pk" + } + }, + { + "field.string": { + "name": "name", + "children": [ + { + "origin.passthrough": { + "@from": "Owner.name" + } + } + ] + } + }, + { + "field.long": { + "name": "vehicleCount", + "children": [ + { + "origin.aggregate": { + "@agg": "count", + "@of": "Vehicle.id", + "@via": "Owner.vehicles" + } + } + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/docs-page-conformance/cases/schema-report-view/expected/agent/schema.md b/fixtures/docs-page-conformance/cases/schema-report-view/expected/agent/schema.md new file mode 100644 index 0000000000..3b317afedd --- /dev/null +++ b/fixtures/docs-page-conformance/cases/schema-report-view/expected/agent/schema.md @@ -0,0 +1,30 @@ + + +# Schema + +The tables, columns and keys this model declares. Read it before writing a query, a migration, or anything that names a table or a column. SQL types, defaults, indexes, checks, constraint names and referential actions are not on this page: the migration files carry them. + +- The **DDL is not repeated here.** The migration files are the DDL, they are generated, and they are what runs — this page describes the schema they produce. +- Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. +- `Field` and `Declared` are the METADATA names. Edit those; the column name follows. + +> **Nothing in this model declares a `description`.** The tables and columns below are named but not explained. Adding `description` to an entity or a field is the single highest-value change to this page: it is what tells a reader *which* of two plausible columns to use, and it is the same text `meta migrate` emits as a `COMMENT ON`, so it lands in the database too. + +## Tables + +### `invoices` + +Declared by `acme::billing::Invoice`. + +| Column | Field | Declared | Null | Key | +|---|---|---|---|---| +| `id` | `id` | `field.long` | no | PK | +| `status` | `status` | `field.string` | no | | + +## Views + +A view is generated from its projection's `origin.*` children or its report's dimensions and measures — it is derived, never hand-written. Editing the view SQL directly is drift the tool cannot see. + +### `v_status_totals` + +Declared by `acme::billing::StatusTotals`. diff --git a/fixtures/docs-page-conformance/cases/schema-report-view/expected/data/agent-schema.md.json b/fixtures/docs-page-conformance/cases/schema-report-view/expected/data/agent-schema.md.json new file mode 100644 index 0000000000..292d1eb69d --- /dev/null +++ b/fixtures/docs-page-conformance/cases/schema-report-view/expected/data/agent-schema.md.json @@ -0,0 +1,55 @@ +{ + "generatedMarker": "", + "physical": false, + "dialect": "", + "descriptionNudge": true, + "hasTables": true, + "tables": [ + { + "heading": "`invoices`", + "tableDeclaredBy": "acme::billing::Invoice", + "columns": [ + { + "name": "id", + "fieldCell": "`id`", + "declaredCell": "`field.long`", + "sqlTypeCell": "", + "nullCell": "no", + "defaultCell": "", + "keyCell": "PK" + }, + { + "name": "status", + "fieldCell": "`status`", + "declaredCell": "`field.string`", + "sqlTypeCell": "", + "nullCell": "no", + "defaultCell": "", + "keyCell": "" + } + ], + "hasDescribed": false, + "described": [], + "hasIndexes": false, + "indexes": [], + "hasForeignKeys": false, + "foreignKeys": [], + "hasChecks": false, + "checks": [] + } + ], + "hasViews": true, + "hasReportView": true, + "views": [ + { + "heading": "`v_status_totals`", + "viewDeclaredBy": "acme::billing::StatusTotals", + "hasLineage": false, + "lineage": [] + } + ], + "hasRelationships": false, + "relationships": [], + "hasEnums": false, + "enums": [] +} diff --git a/fixtures/docs-page-conformance/cases/schema-report-view/input/meta.billing.json b/fixtures/docs-page-conformance/cases/schema-report-view/input/meta.billing.json new file mode 100644 index 0000000000..179b977a3d --- /dev/null +++ b/fixtures/docs-page-conformance/cases/schema-report-view/input/meta.billing.json @@ -0,0 +1,72 @@ +{ + "metadata.root": { + "package": "acme::billing", + "children": [ + { + "object.entity": { + "name": "Invoice", + "children": [ + { + "source.rdb": { + "@table": "invoices" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "status", + "@required": true, + "@default": "open" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "dimension.attribute": { + "name": "invoiceStatus", + "@of": "Invoice.status" + } + }, + { + "measure.aggregate": { + "name": "invoiceCount", + "@agg": "count", + "@of": "Invoice.id" + } + } + ] + } + }, + { + "object.report": { + "name": "StatusTotals", + "@from": "Invoice", + "@dimensions": [ + "invoiceStatus" + ], + "@measures": [ + "invoiceCount" + ], + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_status_totals" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/list-query-conformance/README.md b/fixtures/list-query-conformance/README.md new file mode 100644 index 0000000000..136e585956 --- /dev/null +++ b/fixtures/list-query-conformance/README.md @@ -0,0 +1,76 @@ +# `list-query-conformance/` — how a list route reads its query string + +The shared parse cases of the REST standard's list handling. Each case is a query string in, and +out comes either the parsed list query (filter tree, search, sort, page) or the 400 body the route +refuses with. They run with no web server and no database: what they pin is the parse, which a +port's list route does before its query library sees anything. What a parsed query then +*matches* in a store is the api-contract corpus's job (`fixtures/api-contract-conformance/`). + +## Files + +- `meta.json` — one `Ticket` entity with a field of every filterable kind: text, string- and + int-backed enums, int, double, decimal, currency, boolean, date, time, an instant timestamp, a + `@localTime` timestamp, uuid and duration. It also has one field that is not `@filterable` + (`notes`), one with `@sortable: false` (`score`) and one with `@sortableDefaultOrder: desc` + (`priority`). +- `cases.json` — `cases[]`, each `{ group, name, query, why, expect }`. `query` is the raw query + string as it arrives, percent-encoding included. `expect` is one of: + - `{ "list": { filter?, search?, sort?, limit?, offset? } }` — the parsed query, with members + that are absent left out; + - `{ "error": { "error": "", ... } }` — the exact 400 body. + +The allowlist is not written in the fixture. A runner derives it from `meta.json` the way its +port's generator does (the generated `FilterAllowlist` / `SortAllowlist`), so a port whose +generator derives a different allowlist fails here. + +## The parsed form + +- A **leaf** is `{ field, op, value }`. Two or more conditions are `{ "and": [...] }` in the order + they were sent, and `filter[or][i]` is `{ "or": [...] }` in index order. An `or`/`and` with one + branch is that branch. +- **Values are neutral**, not a driver's: + - a number (int, long, double, currency) is a JSON number, and on an integer field a fraction + is refused; + - a boolean (`true`/`1`/`false`/`0`) is a JSON boolean, and so is `isNull`'s operand; + - a decimal is its canonical text (`10.50` → `"10.5"`, `1.5e2` → `"150"`), never a double; + - an instant timestamp is a UTC ISO string (a bare date is midnight UTC, no zone is UTC, an + offset is converted); + - a `@localTime` timestamp is kept as sent unless it carries a zone, which is converted to UTC; + - `in` is a list split on commas, each element trimmed and typed like a scalar; + - everything else (text, enum member, date, time, uuid, duration, a `like` pattern) is the + string as sent, once it passes the format check. +- `search` is `{ term, fields }`. `fields` lists the filterable fields whose band includes + `like`: plain text and string-backed enums, but not a uuid or an int-backed enum, because a + case-insensitive substring match on those columns is an error on Postgres. An empty `search` + is no search. +- `sort` is `{ field, order }`. A missing order takes the field's `@sortableDefaultOrder`, or + `asc` if it has none. + +## Refusals and their order + +The wire codes are the REST standard's ([`docs/features/api-contract.md`](../../docs/features/api-contract.md)): +`invalid_filter_field`, `invalid_filter_op`, `invalid_filter_value`, `invalid_sort`, +`filter.bare_field`, `filter.nesting_too_deep`, `filter.in_too_large`, +`filter.leading_wildcard_disallowed`, `pagination.invalid_value`. When a query has more than +one fault, the first one found is reported, and they are found in this order: + +1. bare field parameters; +2. `limit`, then `offset`; +3. the filter, depth-first, in the order its keys were sent; +4. the sort; +5. the search. + +The `fault-order` group pins that order. + +Caps: five levels of `or`/`and` nesting (the sixth is `filter.nesting_too_deep`, `limit: 5`) and +100 `in` elements (`filter.in_too_large`, `limit: 100`). A query-string parser has to be able to +reach the nesting cap: `qs`'s default depth of 5 cannot (the sixth bracket pair stays part of the +key), so the TypeScript mounts parse with a depth sized to the cap. + +## Runners + +- TypeScript (the source of the expected answers): + `server/typescript/packages/integration-tests/test/list-query-conformance.test.ts`. + To regenerate after an intended change, run + `UPDATE_LIST_QUERY_FIXTURES=1 bun test test/list-query-conformance.test.ts`, then review every + changed answer, because the answers are the cross-port contract. diff --git a/fixtures/list-query-conformance/cases.json b/fixtures/list-query-conformance/cases.json new file mode 100644 index 0000000000..d956d1af11 --- /dev/null +++ b/fixtures/list-query-conformance/cases.json @@ -0,0 +1,1764 @@ +{ + "cases": [ + { + "group": "operators", + "name": "eq-text", + "query": "filter[title][eq]=Pump", + "why": "eq on a text field keeps the value as sent", + "expect": { + "list": { + "filter": { + "field": "title", + "op": "eq", + "value": "Pump" + } + } + } + }, + { + "group": "operators", + "name": "eq-bare-value-sugar", + "query": "filter[title]=Pump", + "why": "a bare filter value is eq", + "expect": { + "list": { + "filter": { + "field": "title", + "op": "eq", + "value": "Pump" + } + } + } + }, + { + "group": "operators", + "name": "ne-text", + "query": "filter[code][ne]=T-001", + "why": "ne on a text field", + "expect": { + "list": { + "filter": { + "field": "code", + "op": "ne", + "value": "T-001" + } + } + } + }, + { + "group": "operators", + "name": "gt-integer", + "query": "filter[priority][gt]=2", + "why": "an integer operand is a JSON number", + "expect": { + "list": { + "filter": { + "field": "priority", + "op": "gt", + "value": 2 + } + } + } + }, + { + "group": "operators", + "name": "gte-double", + "query": "filter[score][gte]=1.5", + "why": "a double operand is a JSON number", + "expect": { + "list": { + "filter": { + "field": "score", + "op": "gte", + "value": 1.5 + } + } + } + }, + { + "group": "operators", + "name": "lt-date", + "query": "filter[dueOn][lt]=2026-03-01", + "why": "a date operand is kept as sent", + "expect": { + "list": { + "filter": { + "field": "dueOn", + "op": "lt", + "value": "2026-03-01" + } + } + } + }, + { + "group": "operators", + "name": "lte-time", + "query": "filter[opensAt][lte]=09:30", + "why": "a time operand is kept as sent", + "expect": { + "list": { + "filter": { + "field": "opensAt", + "op": "lte", + "value": "09:30" + } + } + } + }, + { + "group": "operators", + "name": "in-text", + "query": "filter[status][in]=open,closed", + "why": "in splits on commas", + "expect": { + "list": { + "filter": { + "field": "status", + "op": "in", + "value": [ + "open", + "closed" + ] + } + } + } + }, + { + "group": "operators", + "name": "in-integers-trimmed", + "query": "filter[priority][in]=1,%202,3", + "why": "each in element is trimmed and typed", + "expect": { + "list": { + "filter": { + "field": "priority", + "op": "in", + "value": [ + 1, + 2, + 3 + ] + } + } + } + }, + { + "group": "operators", + "name": "like-trailing-wildcard", + "query": "filter[title][like]=Pu%25", + "why": "a like pattern is kept verbatim", + "expect": { + "list": { + "filter": { + "field": "title", + "op": "like", + "value": "Pu%" + } + } + } + }, + { + "group": "operators", + "name": "like-underscore", + "query": "filter[code][like]=T-0_1", + "why": "_ is a wildcard and is kept", + "expect": { + "list": { + "filter": { + "field": "code", + "op": "like", + "value": "T-0_1" + } + } + } + }, + { + "group": "operators", + "name": "isnull-true-filterable", + "query": "filter[ownerId][isNull]=true", + "why": "isNull true", + "expect": { + "list": { + "filter": { + "field": "ownerId", + "op": "isNull", + "value": true + } + } + } + }, + { + "group": "operators", + "name": "isnull-false", + "query": "filter[ownerId][isNull]=false", + "why": "isNull false", + "expect": { + "list": { + "filter": { + "field": "ownerId", + "op": "isNull", + "value": false + } + } + } + }, + { + "group": "operators", + "name": "isnull-one", + "query": "filter[dueOn][isNull]=1", + "why": "1 is true", + "expect": { + "list": { + "filter": { + "field": "dueOn", + "op": "isNull", + "value": true + } + } + } + }, + { + "group": "operators", + "name": "boolean-true", + "query": "filter[active][eq]=true", + "why": "a boolean operand is a JSON boolean", + "expect": { + "list": { + "filter": { + "field": "active", + "op": "eq", + "value": true + } + } + } + }, + { + "group": "operators", + "name": "boolean-zero", + "query": "filter[active][eq]=0", + "why": "0 is false", + "expect": { + "list": { + "filter": { + "field": "active", + "op": "eq", + "value": false + } + } + } + }, + { + "group": "operators", + "name": "enum-member", + "query": "filter[status][eq]=pending", + "why": "an enum member", + "expect": { + "list": { + "filter": { + "field": "status", + "op": "eq", + "value": "pending" + } + } + } + }, + { + "group": "operators", + "name": "int-enum-member", + "query": "filter[severity][in]=low,high", + "why": "an int-backed enum is filtered by member symbol", + "expect": { + "list": { + "filter": { + "field": "severity", + "op": "in", + "value": [ + "low", + "high" + ] + } + } + } + }, + { + "group": "operators", + "name": "int-enum-no-like", + "query": "filter[severity][like]=lo%25", + "why": "an int-backed enum has no like", + "expect": { + "error": { + "error": "invalid_filter_op", + "field": "severity", + "op": "like", + "allowed": [ + "eq", + "ne", + "in", + "isNull" + ] + } + } + }, + { + "group": "operators", + "name": "currency-integer", + "query": "filter[feeCents][gte]=1500", + "why": "currency is integer minor units", + "expect": { + "list": { + "filter": { + "field": "feeCents", + "op": "gte", + "value": 1500 + } + } + } + }, + { + "group": "operators", + "name": "uuid", + "query": "filter[ownerId][eq]=6f1c2a9e-0b7d-4c3a-9e2f-1a2b3c4d5e6f", + "why": "a uuid operand is kept as sent", + "expect": { + "list": { + "filter": { + "field": "ownerId", + "op": "eq", + "value": "6f1c2a9e-0b7d-4c3a-9e2f-1a2b3c4d5e6f" + } + } + } + }, + { + "group": "operators", + "name": "duration", + "query": "filter[timeSpent][gte]=PT1H30M", + "why": "a duration operand is kept as sent", + "expect": { + "list": { + "filter": { + "field": "timeSpent", + "op": "gte", + "value": "PT1H30M" + } + } + } + }, + { + "group": "canonical-values", + "name": "decimal-canonical", + "query": "filter[amount][gt]=10.50", + "why": "a decimal operand is its canonical text, never a double", + "expect": { + "list": { + "filter": { + "field": "amount", + "op": "gt", + "value": "10.5" + } + } + } + }, + { + "group": "canonical-values", + "name": "decimal-leading-zero", + "query": "filter[amount][gt]=010.5", + "why": "a leading zero is not the JSON-number grammar", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "amount", + "op": "gt", + "expected": "decimal number (digits, optional fraction, optional exponent)" + } + } + }, + { + "group": "canonical-values", + "name": "decimal-exponent", + "query": "filter[amount][lte]=1.5e2", + "why": "the JSON-number grammar admits an exponent", + "expect": { + "list": { + "filter": { + "field": "amount", + "op": "lte", + "value": "150" + } + } + } + }, + { + "group": "canonical-values", + "name": "timestamp-date-only-is-utc-midnight", + "query": "filter[createdAt][gte]=2026-10-06", + "why": "an instant read from a date is midnight UTC", + "expect": { + "list": { + "filter": { + "field": "createdAt", + "op": "gte", + "value": "2026-10-06T00:00:00Z" + } + } + } + }, + { + "group": "canonical-values", + "name": "timestamp-zoneless-is-utc", + "query": "filter[createdAt][lt]=2026-10-06T08:00:00", + "why": "an instant with no zone is read as UTC", + "expect": { + "list": { + "filter": { + "field": "createdAt", + "op": "lt", + "value": "2026-10-06T08:00:00Z" + } + } + } + }, + { + "group": "canonical-values", + "name": "timestamp-offset-to-utc", + "query": "filter[createdAt][lt]=2026-10-06T08:00:00%2B02:00", + "why": "a zoned instant is rewritten to UTC", + "expect": { + "list": { + "filter": { + "field": "createdAt", + "op": "lt", + "value": "2026-10-06T06:00:00Z" + } + } + } + }, + { + "group": "canonical-values", + "name": "timestamp-local-kept", + "query": "filter[wallClock][gte]=2026-10-06T08:00:00", + "why": "a @localTime wall clock is kept as sent", + "expect": { + "list": { + "filter": { + "field": "wallClock", + "op": "gte", + "value": "2026-10-06T08:00:00" + } + } + } + }, + { + "group": "canonical-values", + "name": "timestamp-local-offset-to-utc", + "query": "filter[wallClock][gte]=2026-10-06T08:00:00-05:00", + "why": "a zoned bound on a wall clock is still rewritten to UTC", + "expect": { + "list": { + "filter": { + "field": "wallClock", + "op": "gte", + "value": "2026-10-06T13:00:00Z" + } + } + } + }, + { + "group": "combinators", + "name": "two-ops-one-field", + "query": "filter[priority][gte]=2&filter[priority][lte]=4", + "why": "two ops on one field AND together", + "expect": { + "list": { + "filter": { + "and": [ + { + "field": "priority", + "op": "gte", + "value": 2 + }, + { + "field": "priority", + "op": "lte", + "value": 4 + } + ] + } + } + } + }, + { + "group": "combinators", + "name": "two-fields", + "query": "filter[status][eq]=open&filter[active][eq]=true", + "why": "two fields AND together, in the order sent", + "expect": { + "list": { + "filter": { + "and": [ + { + "field": "status", + "op": "eq", + "value": "open" + }, + { + "field": "active", + "op": "eq", + "value": true + } + ] + } + } + } + }, + { + "group": "combinators", + "name": "or-two-branches", + "query": "filter[or][0][status][eq]=closed&filter[or][1][priority][eq]=5", + "why": "or of two branches", + "expect": { + "list": { + "filter": { + "or": [ + { + "field": "status", + "op": "eq", + "value": "closed" + }, + { + "field": "priority", + "op": "eq", + "value": 5 + } + ] + } + } + } + }, + { + "group": "combinators", + "name": "and-explicit", + "query": "filter[and][0][priority][gte]=2&filter[and][1][title][like]=P%25", + "why": "an explicit and", + "expect": { + "list": { + "filter": { + "and": [ + { + "field": "priority", + "op": "gte", + "value": 2 + }, + { + "field": "title", + "op": "like", + "value": "P%" + } + ] + } + } + } + }, + { + "group": "combinators", + "name": "or-one-branch-is-the-branch", + "query": "filter[or][0][status][eq]=closed", + "why": "an or of one branch is that branch", + "expect": { + "list": { + "filter": { + "field": "status", + "op": "eq", + "value": "closed" + } + } + } + }, + { + "group": "combinators", + "name": "or-beside-a-field", + "query": "filter[active][eq]=true&filter[or][0][status][eq]=open&filter[or][1][status][eq]=pending", + "why": "an or beside a field is ANDed with it", + "expect": { + "list": { + "filter": { + "and": [ + { + "field": "active", + "op": "eq", + "value": true + }, + { + "or": [ + { + "field": "status", + "op": "eq", + "value": "open" + }, + { + "field": "status", + "op": "eq", + "value": "pending" + } + ] + } + ] + } + } + } + }, + { + "group": "combinators", + "name": "or-branch-with-two-conditions", + "query": "filter[or][0][status][eq]=open&filter[or][0][priority][gt]=3&filter[or][1][active][eq]=false", + "why": "a branch with two conditions is their and", + "expect": { + "list": { + "filter": { + "or": [ + { + "and": [ + { + "field": "status", + "op": "eq", + "value": "open" + }, + { + "field": "priority", + "op": "gt", + "value": 3 + } + ] + }, + { + "field": "active", + "op": "eq", + "value": false + } + ] + } + } + } + }, + { + "group": "combinators", + "name": "and-inside-or", + "query": "filter[or][0][and][0][status][eq]=open&filter[or][0][and][1][active][eq]=true&filter[or][1][priority][eq]=1", + "why": "nesting an and inside an or", + "expect": { + "list": { + "filter": { + "or": [ + { + "and": [ + { + "field": "status", + "op": "eq", + "value": "open" + }, + { + "field": "active", + "op": "eq", + "value": true + } + ] + }, + { + "field": "priority", + "op": "eq", + "value": 1 + } + ] + } + } + } + }, + { + "group": "combinators", + "name": "or-index-order", + "query": "filter[or][1][status][eq]=closed&filter[or][0][status][eq]=open", + "why": "branches are taken in index order, not the order sent", + "expect": { + "list": { + "filter": { + "or": [ + { + "field": "status", + "op": "eq", + "value": "open" + }, + { + "field": "status", + "op": "eq", + "value": "closed" + } + ] + } + } + } + }, + { + "group": "combinators", + "name": "or-sparse-large-index", + "query": "filter[or][0][status][eq]=open&filter[or][25][status][eq]=closed", + "why": "an index above 20 stays a branch", + "expect": { + "list": { + "filter": { + "or": [ + { + "field": "status", + "op": "eq", + "value": "open" + }, + { + "field": "status", + "op": "eq", + "value": "closed" + } + ] + } + } + } + }, + { + "group": "combinators", + "name": "nesting-at-the-cap", + "query": "filter[or][0][or][0][or][0][or][0][or][0][priority][eq]=1", + "why": "five levels of or/and is allowed", + "expect": { + "list": { + "filter": { + "field": "priority", + "op": "eq", + "value": 1 + } + } + } + }, + { + "group": "combinators", + "name": "nesting-too-deep", + "query": "filter[or][0][or][0][or][0][or][0][or][0][or][0][priority][eq]=1", + "why": "six levels is refused", + "expect": { + "error": { + "error": "filter.nesting_too_deep", + "limit": 5 + } + } + }, + { + "group": "combinators", + "name": "or-not-a-list", + "query": "filter[or]=open", + "why": "an or that is not a list of branches", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "or" + } + } + }, + { + "group": "combinators", + "name": "or-branch-not-an-object", + "query": "filter[or][0]=open", + "why": "an or branch that names no field", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "or" + } + } + }, + { + "group": "refusals", + "name": "unknown-field", + "query": "filter[nope][eq]=1", + "why": "a field the entity does not have", + "expect": { + "error": { + "error": "invalid_filter_field", + "field": "nope", + "allowed": [ + "id", + "title", + "code", + "status", + "severity", + "priority", + "score", + "amount", + "feeCents", + "active", + "dueOn", + "opensAt", + "createdAt", + "wallClock", + "ownerId", + "timeSpent" + ] + } + } + }, + { + "group": "refusals", + "name": "field-not-filterable", + "query": "filter[notes][eq]=x", + "why": "a field of the entity that is not @filterable", + "expect": { + "error": { + "error": "invalid_filter_field", + "field": "notes", + "allowed": [ + "id", + "title", + "code", + "status", + "severity", + "priority", + "score", + "amount", + "feeCents", + "active", + "dueOn", + "opensAt", + "createdAt", + "wallClock", + "ownerId", + "timeSpent" + ] + } + } + }, + { + "group": "refusals", + "name": "op-not-in-band", + "query": "filter[priority][like]=1%25", + "why": "like is not an integer op", + "expect": { + "error": { + "error": "invalid_filter_op", + "field": "priority", + "op": "like", + "allowed": [ + "eq", + "ne", + "gt", + "gte", + "lt", + "lte", + "in", + "isNull" + ] + } + } + }, + { + "group": "refusals", + "name": "gt-on-text", + "query": "filter[title][gt]=A", + "why": "gt is not a text op", + "expect": { + "error": { + "error": "invalid_filter_op", + "field": "title", + "op": "gt", + "allowed": [ + "eq", + "ne", + "in", + "like", + "isNull" + ] + } + } + }, + { + "group": "refusals", + "name": "unknown-op", + "query": "filter[title][between]=A", + "why": "an op that is not one of the nine", + "expect": { + "error": { + "error": "invalid_filter_op", + "field": "title", + "op": "between", + "allowed": [ + "eq", + "ne", + "in", + "like", + "isNull" + ] + } + } + }, + { + "group": "refusals", + "name": "leading-wildcard", + "query": "filter[title][like]=%25pump", + "why": "a like pattern starting with % is refused", + "expect": { + "error": { + "error": "filter.leading_wildcard_disallowed", + "field": "title" + } + } + }, + { + "group": "refusals", + "name": "in-over-the-cap", + "query": "filter[priority][in]=0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100", + "why": "an in list of 101 elements", + "expect": { + "error": { + "error": "filter.in_too_large", + "field": "priority", + "limit": 100 + } + } + }, + { + "group": "refusals", + "name": "in-at-the-cap", + "query": "filter[priority][in]=0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99", + "why": "an in list of 100 elements is allowed", + "expect": { + "list": { + "filter": { + "field": "priority", + "op": "in", + "value": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99 + ] + } + } + } + }, + { + "group": "refusals", + "name": "integer-fractional", + "query": "filter[priority][gte]=2.5", + "why": "a fractional bound on an integer field", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "priority", + "op": "gte", + "expected": "integer (a whole number)" + } + } + }, + { + "group": "refusals", + "name": "currency-fractional", + "query": "filter[feeCents][eq]=10.5", + "why": "currency is whole minor units", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "feeCents", + "op": "eq", + "expected": "integer (a whole number)" + } + } + }, + { + "group": "refusals", + "name": "number-not-numeric", + "query": "filter[score][gt]=abc", + "why": "a number that is not one", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "score", + "op": "gt", + "expected": "number" + } + } + }, + { + "group": "refusals", + "name": "number-empty", + "query": "filter[score][gt]=", + "why": "an empty number is not zero", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "score", + "op": "gt", + "expected": "number" + } + } + }, + { + "group": "refusals", + "name": "boolean-not-boolean", + "query": "filter[active][eq]=yes", + "why": "a boolean that is not one", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "active", + "op": "eq", + "expected": "boolean" + } + } + }, + { + "group": "refusals", + "name": "date-malformed", + "query": "filter[dueOn][gte]=2026-3-1", + "why": "a date that is not YYYY-MM-DD", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "dueOn", + "op": "gte", + "expected": "date (YYYY-MM-DD)" + } + } + }, + { + "group": "refusals", + "name": "date-impossible", + "query": "filter[dueOn][gte]=2026-02-30", + "why": "a date that is not a calendar day", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "dueOn", + "op": "gte", + "expected": "date (YYYY-MM-DD)" + } + } + }, + { + "group": "refusals", + "name": "time-malformed", + "query": "filter[opensAt][lt]=9am", + "why": "a time that is not HH:MM", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "opensAt", + "op": "lt", + "expected": "time (HH:MM[:SS[.fff]])" + } + } + }, + { + "group": "refusals", + "name": "timestamp-malformed", + "query": "filter[createdAt][gt]=yesterday", + "why": "a timestamp that is not one", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "createdAt", + "op": "gt", + "expected": "timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])" + } + } + }, + { + "group": "refusals", + "name": "timestamp-unencoded-plus-hint", + "query": "filter[createdAt][gt]=2026-10-06T00:00:00+00:00", + "why": "a + sent unencoded arrives as a space; the answer says so", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "createdAt", + "op": "gt", + "expected": "timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + "hint": "a \"+\" in a query string decodes to a space: URL-encode the offset's \"+\" as %2B, or use Z for UTC" + } + } + }, + { + "group": "refusals", + "name": "uuid-malformed", + "query": "filter[ownerId][eq]=abc", + "why": "a uuid that is not 8-4-4-4-12 hex", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "ownerId", + "op": "eq", + "expected": "uuid (8-4-4-4-12 hex)" + } + } + }, + { + "group": "refusals", + "name": "enum-not-a-member", + "query": "filter[status][eq]=archived", + "why": "a value that is not a declared member", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "status", + "op": "eq", + "expected": "one of: open, closed, pending", + "allowed": [ + "open", + "closed", + "pending" + ] + } + } + }, + { + "group": "refusals", + "name": "enum-in-not-a-member", + "query": "filter[status][in]=open,archived", + "why": "every in element is checked", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "status", + "op": "in", + "expected": "one of: open, closed, pending", + "allowed": [ + "open", + "closed", + "pending" + ] + } + } + }, + { + "group": "refusals", + "name": "decimal-malformed", + "query": "filter[amount][eq]=1,5", + "why": "a decimal that is not a JSON number", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "amount", + "op": "eq", + "expected": "decimal number (digits, optional fraction, optional exponent)" + } + } + }, + { + "group": "refusals", + "name": "duration-malformed", + "query": "filter[timeSpent][gt]=90 minutes", + "why": "a duration that is not ISO-8601", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "timeSpent", + "op": "gt", + "expected": "duration (ISO 8601, e.g. PT1H30M; no years or months)" + } + } + }, + { + "group": "refusals", + "name": "isnull-not-boolean", + "query": "filter[ownerId][isNull]=maybe", + "why": "isNull takes a boolean", + "expect": { + "error": { + "error": "invalid_filter_value", + "field": "ownerId", + "op": "isNull", + "expected": "boolean" + } + } + }, + { + "group": "bare-parameters", + "name": "bare-filterable-field", + "query": "title=Pump", + "why": "a bare ?field= naming a filterable field", + "expect": { + "error": { + "error": "filter.bare_field", + "field": "title", + "expected": "filter[title][eq]=Pump" + } + } + }, + { + "group": "bare-parameters", + "name": "bare-field-not-filterable", + "query": "notes=x", + "why": "a bare ?field= naming a field that is not filterable", + "expect": { + "error": { + "error": "filter.bare_field", + "field": "notes", + "filterable": false, + "expected": "a filterable field — \"notes\" is not @filterable", + "allowed": [ + "id", + "title", + "code", + "status", + "severity", + "priority", + "score", + "amount", + "feeCents", + "active", + "dueOn", + "opensAt", + "createdAt", + "wallClock", + "ownerId", + "timeSpent" + ] + } + } + }, + { + "group": "bare-parameters", + "name": "bare-unknown-parameter-ignored", + "query": "cb=12345&utm_source=mail", + "why": "any other parameter is ignored", + "expect": { + "list": {} + } + }, + { + "group": "bare-parameters", + "name": "bare-repeated-parameter", + "query": "title=a&title=b", + "why": "a repeated bare field still names the field", + "expect": { + "error": { + "error": "filter.bare_field", + "field": "title", + "expected": "filter[title][eq]=" + } + } + }, + { + "group": "search", + "name": "search", + "query": "search=pump", + "why": "search is matched against the filterable fields whose band has like (not a uuid, not an int-backed enum)", + "expect": { + "list": { + "search": { + "term": "pump", + "fields": [ + "title", + "code", + "status" + ] + } + } + } + }, + { + "group": "search", + "name": "search-empty-ignored", + "query": "search=", + "why": "an empty search is no search", + "expect": { + "list": {} + } + }, + { + "group": "search", + "name": "search-with-filter", + "query": "search=pump&filter[status][eq]=open", + "why": "search and filter are both applied", + "expect": { + "list": { + "filter": { + "field": "status", + "op": "eq", + "value": "open" + }, + "search": { + "term": "pump", + "fields": [ + "title", + "code", + "status" + ] + } + } + } + }, + { + "group": "search", + "name": "search-wildcards-kept", + "query": "search=50%25_off", + "why": "the term is kept as sent", + "expect": { + "list": { + "search": { + "term": "50%_off", + "fields": [ + "title", + "code", + "status" + ] + } + } + } + }, + { + "group": "sort-and-page", + "name": "sort-asc", + "query": "sort=title:asc", + "why": "an explicit order", + "expect": { + "list": { + "sort": { + "field": "title", + "order": "asc" + } + } + } + }, + { + "group": "sort-and-page", + "name": "sort-desc-uppercase", + "query": "sort=title:DESC", + "why": "the order is case-insensitive", + "expect": { + "list": { + "sort": { + "field": "title", + "order": "desc" + } + } + } + }, + { + "group": "sort-and-page", + "name": "sort-declared-default", + "query": "sort=priority", + "why": "no order takes the field's @sortableDefaultOrder", + "expect": { + "list": { + "sort": { + "field": "priority", + "order": "desc" + } + } + } + }, + { + "group": "sort-and-page", + "name": "sort-undeclared-default", + "query": "sort=title", + "why": "no order and no declaration is asc", + "expect": { + "list": { + "sort": { + "field": "title", + "order": "asc" + } + } + } + }, + { + "group": "sort-and-page", + "name": "sort-unknown-field", + "query": "sort=nope:asc", + "why": "a field not on the sort allowlist", + "expect": { + "error": { + "error": "invalid_sort", + "field": "nope", + "expected": "sort=:asc|desc", + "allowed": [ + "id", + "title", + "code", + "status", + "severity", + "priority", + "amount", + "feeCents", + "active", + "dueOn", + "opensAt", + "createdAt", + "wallClock", + "ownerId", + "timeSpent" + ] + } + } + }, + { + "group": "sort-and-page", + "name": "sort-inherited-object-property", + "query": "sort=constructor", + "why": "a name every object inherits (constructor, toString) is not a field on the sort allowlist; it answers invalid_sort like any unknown field", + "expect": { + "error": { + "error": "invalid_sort", + "field": "constructor", + "expected": "sort=:asc|desc", + "allowed": [ + "id", + "title", + "code", + "status", + "severity", + "priority", + "amount", + "feeCents", + "active", + "dueOn", + "opensAt", + "createdAt", + "wallClock", + "ownerId", + "timeSpent" + ] + } + } + }, + { + "group": "sort-and-page", + "name": "sort-inherited-object-property-tostring", + "query": "sort=toString:desc", + "why": "a name every object inherits (constructor, toString) is not a field on the sort allowlist; it answers invalid_sort like any unknown field", + "expect": { + "error": { + "error": "invalid_sort", + "field": "toString", + "expected": "sort=:asc|desc", + "allowed": [ + "id", + "title", + "code", + "status", + "severity", + "priority", + "amount", + "feeCents", + "active", + "dueOn", + "opensAt", + "createdAt", + "wallClock", + "ownerId", + "timeSpent" + ] + } + } + }, + { + "group": "sort-and-page", + "name": "sort-not-sortable", + "query": "sort=score:asc", + "why": "a filterable field marked @sortable false", + "expect": { + "error": { + "error": "invalid_sort", + "field": "score", + "expected": "sort=:asc|desc", + "allowed": [ + "id", + "title", + "code", + "status", + "severity", + "priority", + "amount", + "feeCents", + "active", + "dueOn", + "opensAt", + "createdAt", + "wallClock", + "ownerId", + "timeSpent" + ] + } + } + }, + { + "group": "sort-and-page", + "name": "sort-bad-order", + "query": "sort=title:up", + "why": "an order that is not asc or desc", + "expect": { + "error": { + "error": "invalid_sort", + "field": "title", + "expected": "sort=:asc|desc", + "allowed": [ + "id", + "title", + "code", + "status", + "severity", + "priority", + "amount", + "feeCents", + "active", + "dueOn", + "opensAt", + "createdAt", + "wallClock", + "ownerId", + "timeSpent" + ] + } + } + }, + { + "group": "sort-and-page", + "name": "page", + "query": "limit=10&offset=20", + "why": "limit and offset", + "expect": { + "list": { + "limit": 10, + "offset": 20 + } + } + }, + { + "group": "sort-and-page", + "name": "page-zero", + "query": "limit=0", + "why": "a zero limit is a page size", + "expect": { + "list": { + "limit": 0 + } + } + }, + { + "group": "sort-and-page", + "name": "limit-not-a-number", + "query": "limit=abc", + "why": "a limit that is not a non-negative integer", + "expect": { + "error": { + "error": "pagination.invalid_value", + "param": "limit", + "value": "abc", + "expected": "a non-negative integer (0 or more)" + } + } + }, + { + "group": "sort-and-page", + "name": "limit-fractional", + "query": "limit=1.5", + "why": "a fractional limit", + "expect": { + "error": { + "error": "pagination.invalid_value", + "param": "limit", + "value": "1.5", + "expected": "a non-negative integer (0 or more)" + } + } + }, + { + "group": "sort-and-page", + "name": "offset-negative", + "query": "offset=-1", + "why": "a negative offset", + "expect": { + "error": { + "error": "pagination.invalid_value", + "param": "offset", + "value": "-1", + "expected": "a non-negative integer (0 or more)" + } + } + }, + { + "group": "sort-and-page", + "name": "limit-empty", + "query": "limit=", + "why": "an empty limit", + "expect": { + "error": { + "error": "pagination.invalid_value", + "param": "limit", + "value": "", + "expected": "a non-negative integer (0 or more)" + } + } + }, + { + "group": "fault-order", + "name": "bare-field-before-page", + "query": "title=Pump&limit=abc", + "why": "a bare field is reported before a bad page", + "expect": { + "error": { + "error": "filter.bare_field", + "field": "title", + "expected": "filter[title][eq]=Pump" + } + } + }, + { + "group": "fault-order", + "name": "page-before-filter", + "query": "limit=abc&filter[nope][eq]=1", + "why": "a bad page is reported before a bad filter", + "expect": { + "error": { + "error": "pagination.invalid_value", + "param": "limit", + "value": "abc", + "expected": "a non-negative integer (0 or more)" + } + } + }, + { + "group": "fault-order", + "name": "filter-before-sort", + "query": "sort=nope&filter[nope][eq]=1", + "why": "a bad filter is reported before a bad sort", + "expect": { + "error": { + "error": "invalid_filter_field", + "field": "nope", + "allowed": [ + "id", + "title", + "code", + "status", + "severity", + "priority", + "score", + "amount", + "feeCents", + "active", + "dueOn", + "opensAt", + "createdAt", + "wallClock", + "ownerId", + "timeSpent" + ] + } + } + }, + { + "group": "fault-order", + "name": "first-filter-fault-wins", + "query": "filter[title][like]=%25x&filter[nope][eq]=1", + "why": "filter faults are reported in the order sent", + "expect": { + "error": { + "error": "filter.leading_wildcard_disallowed", + "field": "title" + } + } + } + ] +} diff --git a/fixtures/list-query-conformance/meta.json b/fixtures/list-query-conformance/meta.json new file mode 100644 index 0000000000..fa5d007081 --- /dev/null +++ b/fixtures/list-query-conformance/meta.json @@ -0,0 +1,31 @@ +{ + "metadata.root": { + "package": "acme::desk", + "children": [ + { "object.entity": { + "name": "Ticket", + "children": [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { "name": "id", "@filterable": true } }, + { "field.string": { "name": "title", "@maxLength": 100, "@filterable": true } }, + { "field.string": { "name": "code", "@maxLength": 20, "@filterable": true } }, + { "field.string": { "name": "notes", "@maxLength": 200 } }, + { "field.enum": { "name": "status", "@values": ["open", "closed", "pending"], "@filterable": true } }, + { "field.enum": { "name": "severity", "@values": ["low", "high"], "@intValueMap": { "low": 1, "high": 2 }, "@filterable": true } }, + { "field.int": { "name": "priority", "@filterable": true, "@sortableDefaultOrder": "desc" } }, + { "field.double": { "name": "score", "@filterable": true, "@sortable": false } }, + { "field.decimal": { "name": "amount", "@precision": 12, "@scale": 2, "@filterable": true } }, + { "field.currency": { "name": "feeCents", "@currency": "USD", "@filterable": true } }, + { "field.boolean": { "name": "active", "@filterable": true } }, + { "field.date": { "name": "dueOn", "@filterable": true } }, + { "field.time": { "name": "opensAt", "@filterable": true } }, + { "field.timestamp": { "name": "createdAt", "@filterable": true } }, + { "field.timestamp": { "name": "wallClock", "@localTime": true, "@filterable": true } }, + { "field.uuid": { "name": "ownerId", "@filterable": true } }, + { "field.duration": { "name": "timeSpent", "@filterable": true } }, + { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } + ] + }} + ] + } +} diff --git a/fixtures/render-conformance/render-standalone-at-eof/expected.txt b/fixtures/render-conformance/render-standalone-at-eof/expected.txt new file mode 100644 index 0000000000..40c2b12205 --- /dev/null +++ b/fixtures/render-conformance/render-standalone-at-eof/expected.txt @@ -0,0 +1,3 @@ +before +- a +- b diff --git a/fixtures/render-conformance/render-standalone-at-eof/meta.json b/fixtures/render-conformance/render-standalone-at-eof/meta.json new file mode 100644 index 0000000000..6ba806bd06 --- /dev/null +++ b/fixtures/render-conformance/render-standalone-at-eof/meta.json @@ -0,0 +1 @@ +{ "format": "text", "note": "a standalone closing tag on the last line, with no newline after it, is still standalone: its line is removed and nothing is appended" } diff --git a/fixtures/render-conformance/render-standalone-at-eof/payload.json b/fixtures/render-conformance/render-standalone-at-eof/payload.json new file mode 100644 index 0000000000..c574d5c05f --- /dev/null +++ b/fixtures/render-conformance/render-standalone-at-eof/payload.json @@ -0,0 +1,3 @@ +{ + "items": ["a", "b"] +} diff --git a/fixtures/render-conformance/render-standalone-at-eof/template.mustache b/fixtures/render-conformance/render-standalone-at-eof/template.mustache new file mode 100644 index 0000000000..fbf100c7ed --- /dev/null +++ b/fixtures/render-conformance/render-standalone-at-eof/template.mustache @@ -0,0 +1,4 @@ +before +{{#items}} +- {{.}} +{{/items}} \ No newline at end of file diff --git a/fixtures/render-conformance/render-standalone-consecutive/expected.txt b/fixtures/render-conformance/render-standalone-consecutive/expected.txt new file mode 100644 index 0000000000..7323af238d --- /dev/null +++ b/fixtures/render-conformance/render-standalone-consecutive/expected.txt @@ -0,0 +1,9 @@ +open-open: +both +close-then-open: +- a +- b +fallback +three-in-a-row: +deep +end diff --git a/fixtures/render-conformance/render-standalone-consecutive/meta.json b/fixtures/render-conformance/render-standalone-consecutive/meta.json new file mode 100644 index 0000000000..17b41fcb00 --- /dev/null +++ b/fixtures/render-conformance/render-standalone-consecutive/meta.json @@ -0,0 +1 @@ +{ "format": "text", "note": "two or more standalone tags on consecutive lines each strip their own line: no blank line survives between them" } diff --git a/fixtures/render-conformance/render-standalone-consecutive/payload.json b/fixtures/render-conformance/render-standalone-consecutive/payload.json new file mode 100644 index 0000000000..f8d8e63135 --- /dev/null +++ b/fixtures/render-conformance/render-standalone-consecutive/payload.json @@ -0,0 +1,5 @@ +{ + "outer": true, + "inner": true, + "items": ["a", "b"] +} diff --git a/fixtures/render-conformance/render-standalone-consecutive/template.mustache b/fixtures/render-conformance/render-standalone-consecutive/template.mustache new file mode 100644 index 0000000000..cd26ced6cd --- /dev/null +++ b/fixtures/render-conformance/render-standalone-consecutive/template.mustache @@ -0,0 +1,21 @@ +open-open: +{{#outer}} +{{#inner}} +both +{{/inner}} +{{/outer}} +close-then-open: +{{#items}} +- {{.}} +{{/items}} +{{^missing}} +fallback +{{/missing}} +three-in-a-row: +{{#outer}} +{{! a comment between two section tags }} +{{#inner}} +deep +{{/inner}} +{{/outer}} +end diff --git a/fixtures/render-conformance/render-standalone-indented/expected.txt b/fixtures/render-conformance/render-standalone-indented/expected.txt new file mode 100644 index 0000000000..323e39a28d --- /dev/null +++ b/fixtures/render-conformance/render-standalone-indented/expected.txt @@ -0,0 +1,7 @@ +list: + - a + - b +flag: + shown +tab: +done diff --git a/fixtures/render-conformance/render-standalone-indented/meta.json b/fixtures/render-conformance/render-standalone-indented/meta.json new file mode 100644 index 0000000000..f21c41a43b --- /dev/null +++ b/fixtures/render-conformance/render-standalone-indented/meta.json @@ -0,0 +1 @@ +{ "format": "text", "note": "a standalone tag indented by spaces or a tab removes its whole line, indentation included; the content lines keep theirs" } diff --git a/fixtures/render-conformance/render-standalone-indented/payload.json b/fixtures/render-conformance/render-standalone-indented/payload.json new file mode 100644 index 0000000000..79ec6d7f3d --- /dev/null +++ b/fixtures/render-conformance/render-standalone-indented/payload.json @@ -0,0 +1,4 @@ +{ + "items": ["a", "b"], + "show": true +} diff --git a/fixtures/render-conformance/render-standalone-indented/template.mustache b/fixtures/render-conformance/render-standalone-indented/template.mustache new file mode 100644 index 0000000000..89fb067f78 --- /dev/null +++ b/fixtures/render-conformance/render-standalone-indented/template.mustache @@ -0,0 +1,14 @@ +list: + {{#items}} + - {{.}} + {{/items}} +flag: + {{#show}} + shown + {{/show}} + {{^show}} + hidden + {{/show}} +tab: + {{! a tab-indented comment }} +done diff --git a/scripts/sync-doc-templates.sh b/scripts/sync-doc-templates.sh index f705f18a9e..a7e4faba4c 100755 --- a/scripts/sync-doc-templates.sh +++ b/scripts/sync-doc-templates.sh @@ -26,7 +26,7 @@ REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" # (`/`) resolve identically from the bundled copy. Adding a new # group here is the ONLY edit needed — the byte-identity gate + embed generator # discover groups by globbing templates/*/, so they stay in lockstep. -TEMPLATE_GROUPS=(docs api) +TEMPLATE_GROUPS=(docs api requirements agent) # Per-consumer bundled-copy ROOT (the consumer's own templates/ dir). Each group # is copied under /. diff --git a/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs index 6d618d9a03..ffa928e955 100644 --- a/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs @@ -10,6 +10,8 @@ using System.Text.Json; using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using MetaObjects.Render; using Xunit; namespace MetaObjects.Cli.Tests; @@ -80,6 +82,7 @@ public GenSkipConformanceTests() "\n"); Directory.CreateDirectory(P("prompts")); File.WriteAllText(P("prompts/greeting.mustache"), "hello\n"); + File.WriteAllText(P("prompts/note.mustache"), "{{name}}\n"); Directory.CreateDirectory(P("extra")); File.WriteAllText(P("extra/data.txt"), "one"); File.WriteAllText(P("README.md"), "readme v1\n"); @@ -97,6 +100,23 @@ private string[] GenArgs(params string[] more) => private IReadOnlyList Declared(bool uncacheable = false) => [.. OwnedRunner.Declared(_tmp, "entity"), new Custom(!uncacheable)]; + /// The case that also configures a template generator and a docs page. + private const string DocsCase = "template-and-docs-rerun"; + + private IReadOnlyList DeclaredWithDocs() => + [.. Declared(), + TemplateGenerator.Create("note", "note", + r => r.Objects().Where(o => !o.IsAbstract).Select(e => new TemplateWalkResult(new { name = e.Name }, $"notes/{e.Name}.txt")), + new FilesystemProvider(P("prompts"))), + new ApiDocsGenerator()]; + + /// Every file under the given directories: its bytes and its modification time. + private static List<(string Path, string Text, DateTime Stamp)> Snapshot(params string[] dirs) => + [.. dirs.Where(Directory.Exists) + .SelectMany(d => Directory.GetFiles(d, "*", SearchOption.AllDirectories)) + .Order(StringComparer.Ordinal) + .Select(f => (f, File.ReadAllText(f), File.GetLastWriteTimeUtc(f)))]; + private (int Exit, string Out, string Err) RunGen(IReadOnlyList declared, params string[] more) => Wrap(OwnedRunner.Run(_tmp, declared, GenArgs(more))); @@ -147,7 +167,7 @@ public static IEnumerable Cases() [MemberData(nameof(Cases))] public void The_case_table_decides_gen_and_verify(string id, string gen, string verify) { - var declared = Declared(); + var declared = id == DocsCase ? DeclaredWithDocs() : Declared(); var first = RunGen(declared); Assert.True(first.Exit == 0, first.Out + first.Err); Assert.NotNull(GenFingerprint.Read(_tmp)); @@ -231,6 +251,7 @@ public void The_case_table_decides_gen_and_verify(string id, string gen, string Assert.NotEqual(0, bad.Exit); File.WriteAllText(P("metaobjects/meta.order.json"), good); break; + case DocsCase: break; default: Assert.Fail($"unknown case id '{id}': add it to this runner"); break; } @@ -248,6 +269,17 @@ public void The_case_table_decides_gen_and_verify(string id, string gen, string Assert.False(File.Exists(P(".metaobjects/.gen-state/.hashes.json"))); Assert.NotEmpty(Directory.GetFiles(P(".metaobjects/.gen-state/.hashes"), "*.json")); } + if (id == DocsCase) + { + // The template output and the docs page were written, and a forced render rewrites none. + Assert.Equal("Order\n", File.ReadAllText(Path.Combine(OutDir, "notes", "Order.txt"))); + Assert.Contains(Directory.GetFiles(OutDir, "*.md", SearchOption.AllDirectories), f => f.Contains("api", StringComparison.OrdinalIgnoreCase)); + var before = Snapshot(OutDir, P(".metaobjects/.gen-state/.hashes")); + Thread.Sleep(20); + var forced = RunGen(declared, "--force"); + Assert.True(forced.Exit == 0, forced.Out + forced.Err); + Assert.Equal(before, Snapshot(OutDir, P(".metaobjects/.gen-state/.hashes"))); + } } [Fact] diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GenSkipConformanceTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GenSkipConformanceTest.java index 690a7f6c95..a39ad7050d 100644 --- a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GenSkipConformanceTest.java +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GenSkipConformanceTest.java @@ -38,6 +38,9 @@ public class GenSkipConformanceTest { private static final Path CASES = Path.of("../../../fixtures/codegen-skip-conformance/cases.json"); + /** The case that also configures a {@code template} generator and a docs page. */ + private static final String DOCS_CASE = "template-and-docs-rerun"; + @Rule public TemporaryFolder tmp = new TemporaryFolder(); @@ -80,6 +83,7 @@ public void execute(MetaDataLoader loader) { private boolean lax; private String ci; private boolean verifyFull; // -Dmetaobjects.verify.full=true, the verify spelling of --force + private boolean docs; // also configure a template generator and a docs page @Before public void setUp() throws IOException { @@ -116,7 +120,15 @@ private List generators() { GeneratorParam g = new GeneratorParam(); g.setClassname(FixtureGenerator.class.getName()); g.setArgs(Map.of(GeneratorBase.ARG_OUTPUTDIR, "gen", "templatesDir", "tpl", "content", content)); - return List.of(g); + if (!docs) return List.of(g); + GeneratorParam note = new GeneratorParam(); + note.setClassname(com.metaobjects.generator.template.TemplateScopeGenerator.class.getName()); + note.setArgs(Map.of(GeneratorBase.ARG_OUTPUTDIR, "gen", "templatesDir", project.resolve("tpl").toString(), + "template", "note", "scope", "perEntity", "outputPattern", "notes/{Name}.txt")); + GeneratorParam apiDocs = new GeneratorParam(); + apiDocs.setClassname(com.metaobjects.generator.apidocs.JavaApiDocsGenerator.class.getName()); + apiDocs.setArgs(Map.of(GeneratorBase.ARG_OUTPUTDIR, "docs")); + return List.of(g, note, apiDocs); } private void gen(boolean force) throws Exception { @@ -333,7 +345,7 @@ private void applyChange(String id) throws Exception { } } } - case "force", "ci" -> { } + case "force", "ci", DOCS_CASE -> { } case "failed-run" -> { Path f = project.resolve("metaobjects/meta.shop.json"); String original = Files.readString(f); @@ -370,6 +382,7 @@ private void runCase(String id, String expectGen, String expectVerify) throws Ex tearDown(); setUp0(); if (id.equals("uncacheable-generator")) FixtureGenerator.cacheable = false; + docs = id.equals(DOCS_CASE); FixtureGenerator.extra = project.resolve("lookup.txt"); gen(false); assertTrue(id + ": the first run writes", FixtureGenerator.runs == 1); @@ -407,6 +420,36 @@ private void runCase(String id, String expectGen, String expectVerify) throws Ex assertFalse("the write run removed the legacy manifest", Files.exists(gs.resolve(".hashes.json"))); assertTrue("and left package manifests", Files.isRegularFile(gs.resolve(".hashes/.root.json"))); } + if (id.equals(DOCS_CASE)) { + // The template output and the docs page were written, and a forced render rewrites none. + assertEquals("Gizmo\n", Files.readString(project.resolve("gen/notes/Gizmo.txt"))); + assertFalse("the docs page was written", snapshot(project.resolve("docs")).isEmpty()); + List snapshotBefore = watched(); + Thread.sleep(20); + gen(true); + assertEquals(id + ": a forced run over unchanged inputs rewrote a file", snapshotBefore, watched()); + } + docs = false; + } + + private List watched() throws IOException { + List out = new ArrayList<>(); + out.addAll(snapshot(project.resolve("gen"))); + out.addAll(snapshot(project.resolve("docs"))); + out.addAll(snapshot(project.resolve(".metaobjects/.gen-state/.hashes"))); + return out; + } + + /** Every file under {@code dir}: its path, bytes and modification time, in path order. */ + private static List snapshot(Path dir) throws IOException { + if (!Files.isDirectory(dir)) return List.of(); + try (var walk = Files.walk(dir)) { + List out = new ArrayList<>(); + for (Path p : walk.filter(Files::isRegularFile).sorted().toList()) { + out.add(p + "|" + Files.readString(p) + "|" + Files.getLastModifiedTime(p).toMillis()); + } + return out; + } } private void setUp0() throws IOException { @@ -436,6 +479,7 @@ private void setUpFiles() throws IOException { """); Files.createDirectories(project.resolve("tpl")); Files.writeString(project.resolve("tpl/a.mustache"), "template a"); + Files.writeString(project.resolve("tpl/note.mustache"), "{{name}}\n"); Files.createDirectories(project.resolve("codegen")); Files.writeString(project.resolve("codegen/Gen.java"), "class Gen {}"); Files.writeString(project.resolve("lookup.txt"), "lookup"); diff --git a/server/java/render/KNOWN_DRIFT.md b/server/java/render/KNOWN_DRIFT.md index 27a837cfeb..161b087efe 100644 --- a/server/java/render/KNOWN_DRIFT.md +++ b/server/java/render/KNOWN_DRIFT.md @@ -12,7 +12,11 @@ removed. This table is the source of truth for that ledger. | Fixture | Drift type | Notes | |---|---|---| -| render-standalone-tag-stripping | trailing newline after `{{! comment }}` | Mustache.java does NOT apply the standalone-line whitespace strip rule to comments — it leaves the trailing newline. TS (`mustache.js`), C# (Stubble), and Python (purpose-built interpreter) all strip it. Symptom: one extra blank line after the comment-standalone block. Same fixture's `{{#section}}`, `{{>partial}}`, etc. standalone-strip correctly in Java. | + +No fixture drifts today. The last row, `render-standalone-tag-stripping` (mustache.java left the line +break after a standalone `{{! comment }}`), was closed by stripping standalone comment lines in +`Renderer` before mustache.java parses (`MustacheTags.withoutStandaloneComments`); the +`render-standalone-consecutive` and `render-standalone-indented` fixtures hold it. When you find a drift in `RenderCrossPortReportTest` output: 1. Decide if it's worth fixing (most aren't — see FR-004 Java spec §6.4). diff --git a/server/java/render/src/main/java/com/metaobjects/render/MustacheTags.java b/server/java/render/src/main/java/com/metaobjects/render/MustacheTags.java index 2f726ca9c4..c56618844e 100644 --- a/server/java/render/src/main/java/com/metaobjects/render/MustacheTags.java +++ b/server/java/render/src/main/java/com/metaobjects/render/MustacheTags.java @@ -125,6 +125,43 @@ static String delimiterConflict(List tags, String inlinedAs) { return tags.stream().filter(t -> t.kind() == Kind.PARTIAL).map(Tag::value).findFirst().orElse(null); } + /** + * {@code text} with the line of every STANDALONE comment removed: the indentation before + * it, the comment, and the line break after it (or nothing, at the end of the text). + * + *

The Mustache spec treats a comment alone on its line like any other standalone tag. + * mustache.java strips sections, inverted sections and partials that way but leaves a + * comment's line break behind, so a template with a comment on its own line rendered one + * blank line more in Java than in every other port. Doing the strip here, before the + * library parses, is what makes a shared template render the same bytes in Java. + */ + static String withoutStandaloneComments(String text) throws SyntaxException { + List tags = scan(text); + StringBuilder sb = new StringBuilder(text.length()); + int pos = 0; + for (Tag tag : tags) { + if (tag.kind() != Kind.COMMENT) continue; + int lineStart = tag.start(); + while (lineStart > 0 && (text.charAt(lineStart - 1) == ' ' || text.charAt(lineStart - 1) == '\t')) lineStart--; + if (lineStart > 0 && text.charAt(lineStart - 1) != '\n') continue; + int lineEnd = tag.end(); + while (lineEnd < text.length() && (text.charAt(lineEnd) == ' ' || text.charAt(lineEnd) == '\t')) lineEnd++; + if (lineEnd < text.length()) { + if (text.charAt(lineEnd) == '\n') { + lineEnd++; + } else if (text.charAt(lineEnd) == '\r' && lineEnd + 1 < text.length() && text.charAt(lineEnd + 1) == '\n') { + lineEnd += 2; + } else { + continue; + } + } + if (lineStart < pos) continue; + sb.append(text, pos, lineStart); + pos = lineEnd; + } + return sb.append(text, pos, text.length()).toString(); + } + /** {@code text} with every comment cut out: what a tag-presence check may scan. */ static String withoutComments(String text, List tags) { StringBuilder sb = new StringBuilder(text.length()); diff --git a/server/java/render/src/main/java/com/metaobjects/render/Renderer.java b/server/java/render/src/main/java/com/metaobjects/render/Renderer.java index 6376f5bc8d..8941f9319f 100644 --- a/server/java/render/src/main/java/com/metaobjects/render/Renderer.java +++ b/server/java/render/src/main/java/com/metaobjects/render/Renderer.java @@ -59,6 +59,11 @@ public String render(RenderRequest req) { } String expanded = preExpandPartials(body, req.provider(), new ArrayDeque<>()); + try { + expanded = MustacheTags.withoutStandaloneComments(expanded); + } catch (MustacheTags.SyntaxException e) { + throw new RenderException("template syntax error: " + e.getMessage()); + } // Per-variable escaping via the Mustache encode() hook — equivalent to // C# Stubble's SetEncodingFunction. {{var}} runs through the escaper, diff --git a/server/java/render/src/test/java/com/metaobjects/render/RenderCrossPortReportTest.java b/server/java/render/src/test/java/com/metaobjects/render/RenderCrossPortReportTest.java index 87bfc38152..9171911c6d 100644 --- a/server/java/render/src/test/java/com/metaobjects/render/RenderCrossPortReportTest.java +++ b/server/java/render/src/test/java/com/metaobjects/render/RenderCrossPortReportTest.java @@ -46,11 +46,7 @@ public class RenderCrossPortReportTest { * differ; if Java comes into agreement, remove the entry (the test will fail * to remind you). */ - private static final Set KNOWN_DRIFT = Set.of( - // Mustache.java leaves the trailing newline after a standalone {{! comment }}; - // TS / C# / Python all strip it. - "render-standalone-tag-stripping" - ); + private static final Set KNOWN_DRIFT = Set.of(); static { Path p = Paths.get(System.getProperty("user.dir")).toAbsolutePath(); diff --git a/server/java/render/src/test/resources/snapshots/render-standalone-at-eof.txt b/server/java/render/src/test/resources/snapshots/render-standalone-at-eof.txt new file mode 100644 index 0000000000..40c2b12205 --- /dev/null +++ b/server/java/render/src/test/resources/snapshots/render-standalone-at-eof.txt @@ -0,0 +1,3 @@ +before +- a +- b diff --git a/server/java/render/src/test/resources/snapshots/render-standalone-consecutive.txt b/server/java/render/src/test/resources/snapshots/render-standalone-consecutive.txt new file mode 100644 index 0000000000..7323af238d --- /dev/null +++ b/server/java/render/src/test/resources/snapshots/render-standalone-consecutive.txt @@ -0,0 +1,9 @@ +open-open: +both +close-then-open: +- a +- b +fallback +three-in-a-row: +deep +end diff --git a/server/java/render/src/test/resources/snapshots/render-standalone-indented.txt b/server/java/render/src/test/resources/snapshots/render-standalone-indented.txt new file mode 100644 index 0000000000..323e39a28d --- /dev/null +++ b/server/java/render/src/test/resources/snapshots/render-standalone-indented.txt @@ -0,0 +1,7 @@ +list: + - a + - b +flag: + shown +tab: +done diff --git a/server/java/render/src/test/resources/snapshots/render-standalone-tag-stripping.txt b/server/java/render/src/test/resources/snapshots/render-standalone-tag-stripping.txt index 39eff3452a..953057ca58 100644 --- a/server/java/render/src/test/resources/snapshots/render-standalone-tag-stripping.txt +++ b/server/java/render/src/test/resources/snapshots/render-standalone-tag-stripping.txt @@ -12,7 +12,6 @@ end-list list-inline: [a,b,] comment-standalone: - after-comment partial-standalone: diff --git a/server/python/tests/test_gen_skip_conformance.py b/server/python/tests/test_gen_skip_conformance.py index 618527dee6..75b5e0dd01 100644 --- a/server/python/tests/test_gen_skip_conformance.py +++ b/server/python/tests/test_gen_skip_conformance.py @@ -70,6 +70,24 @@ def make(): ''' +_TEMPLATE = '''\ +from pathlib import Path + +from metaobjects.codegen.generators.template_generator import template_generator +from metaobjects.render.filesystem_provider import FilesystemProvider + + +def make(): + return template_generator( + name="note", template="note", provider=FilesystemProvider(Path("prompts")), + scope="perEntity", output_pattern="notes/{name}.txt", + ) +''' + +#: The case that also configures a `template` generator and a docs page. +DOCS_CASE = "template-and-docs-rerun" + + def _book_json(base_extra: bool = False, with_book: bool = True) -> str: """meta.b.json: an abstract parent (Base) and, optionally, a child that extends it.""" base_fields = [{"field.long": {"name": "id"}}] @@ -95,6 +113,7 @@ def _entity_json(name: str, extra_attr: str | None = None) -> str: class Project: root: Path uncacheable: bool = False + docs: bool = False @property def config(self) -> Path: @@ -108,6 +127,8 @@ def write_config(self, generators: str = "[entity, owned:make]") -> None: gens = generators if self.uncacheable: gens = "[entity, owned:make, volatile:make]" + elif self.docs: + gens = "[entity, owned:make, tmpl:make, api-docs]" self.config.write_text( "metadata: metaobjects\ntemplates: prompts\n" f"targets:\n app:\n outDir: generated\n generators: {gens}\n", @@ -115,8 +136,8 @@ def write_config(self, generators: str = "[entity, owned:make]") -> None: ) -def _project(tmp_path: Path, uncacheable: bool = False) -> Project: - p = Project(tmp_path, uncacheable) +def _project(tmp_path: Path, uncacheable: bool = False, docs: bool = False) -> Project: + p = Project(tmp_path, uncacheable, docs) (tmp_path / "metaobjects").mkdir() (tmp_path / "metaobjects" / "meta.a.json").write_text(_entity_json("Author")) (tmp_path / "metaobjects" / "meta.b.json").write_text(_book_json()) @@ -127,6 +148,8 @@ def _project(tmp_path: Path, uncacheable: bool = False) -> Project: (tmp_path / "README.md").write_text("readme\n") (tmp_path / "owned.py").write_text(_OWNED) (tmp_path / "volatile.py").write_text(_UNCACHEABLE) + (tmp_path / "tmpl.py").write_text(_TEMPLATE) + (tmp_path / "prompts" / "note.mustache").write_text("{{name}}\n") (tmp_path / ".metaobjects").mkdir() (tmp_path / ".metaobjects" / "config.json").write_text('{"schema_version": 1, "sources": [{"path": "metaobjects"}]}\n') p.write_config() @@ -292,6 +315,7 @@ def _engine_changed(p: Project, h: Harness) -> None: "ci": (_NOOP, ()), "failed-run": (_failed_run, ()), "legacy-manifest": (_legacy_manifest, ()), + DOCS_CASE: (_NOOP, ()), } @@ -309,7 +333,7 @@ def test_every_shared_case_has_a_handler() -> None: def test_case(case: dict[str, str], tmp_path: Path, monkeypatch, capsys) -> None: assert case["id"] in HANDLERS, f"unknown case id {case['id']!r}" setup, flags = HANDLERS[case["id"]] - project = _project(tmp_path, uncacheable=case["id"] == "uncacheable-generator") + project = _project(tmp_path, uncacheable=case["id"] == "uncacheable-generator", docs=case["id"] == DOCS_CASE) h = Harness(project, monkeypatch, capsys) rc, skipped = h.gen() @@ -341,6 +365,27 @@ def test_case(case: dict[str, str], tmp_path: Path, monkeypatch, capsys) -> None if case["id"] == "legacy-manifest": assert not (project.state / ".hashes.json").exists(), "the write run removes the legacy file" assert list((project.state / ".hashes").glob("*.json")), "and leaves per-package files" + if case["id"] == DOCS_CASE: + _assert_forced_rerun_writes_nothing(project, h) + + +def _snapshot(*dirs: Path) -> list[tuple[str, bytes, int]]: + return sorted( + (str(f), f.read_bytes(), f.stat().st_mtime_ns) + for d in dirs if d.exists() for f in d.rglob("*") if f.is_file() + ) + + +def _assert_forced_rerun_writes_nothing(project: Project, h: Harness) -> None: + """The template output and the docs page were written, and a forced render rewrites none.""" + generated = project.root / "generated" + assert (generated / "notes" / "Book.txt").read_text() == "Book\n" + assert any("api" in str(f).lower() for f in generated.rglob("*.md")), "the docs page was written" + watched = (generated, project.state / ".hashes") + before = _snapshot(*watched) + rc, skipped = h.gen("--force") + assert rc == 0 and not skipped, h.out + h.err + assert _snapshot(*watched) == before, "a forced run over unchanged inputs rewrote a file" def test_unchanged_files_keep_their_timestamp_and_report_unchanged( diff --git a/server/rust/metaobjects-codegen/tests/skip_conformance.rs b/server/rust/metaobjects-codegen/tests/skip_conformance.rs index 6c9ab29813..854df1cf72 100644 --- a/server/rust/metaobjects-codegen/tests/skip_conformance.rs +++ b/server/rust/metaobjects-codegen/tests/skip_conformance.rs @@ -37,6 +37,9 @@ fn fit(id: &str) -> Fit { "template-edited" | "template-added" => Fit::NotApplicable( "the Rust port has no templates (the prompt pillar is a later phase)", ), + "template-and-docs-rerun" => Fit::NotApplicable( + "the Rust port has no `template` generator and no docs page generator yet", + ), "hand-edit-kept" => Fit::NotApplicable( "a hand edit is never kept: with no merge engine, the run refuses the file instead", ), diff --git a/server/typescript/packages/cli/src/commands/eject.ts b/server/typescript/packages/cli/src/commands/eject.ts index 98eab51682..654cff09c0 100644 --- a/server/typescript/packages/cli/src/commands/eject.ts +++ b/server/typescript/packages/cli/src/commands/eject.ts @@ -321,7 +321,8 @@ export async function ejectGenerator(opts: EjectOptions): Promise { ? await ejectTemplates(opts.cwd, [closure], opts.force === true) : undefined; - if (!opts.force && existing !== undefined) { + // Kept unless --force; and --force over identical bytes writes nothing either. + if (existing !== undefined && (!opts.force || existing === templateSource)) { return { ...common, status: "preserved", comparison, runtime, templates }; } @@ -865,9 +866,12 @@ interface EjectPayload { /** The text report for `meta eject docs-site`. */ function reportDocsSite(files: readonly DocsSiteFileResult[]): void { const written = files.filter((f) => f.status !== "preserved").length; + const identical = files.filter((f) => f.identical === true).length; + const kept = files.length - written - identical; log.info( - `Ejected the docs-site theme -> codegen/docs-site/: ${written} file(s) written, ` + - `${files.length - written} already there and kept (--force replaces them).`, + `Ejected the docs-site theme -> codegen/docs-site/: ${written} file(s) written` + + (identical > 0 ? `, ${identical} already identical to the shipped copy` : "") + + (kept > 0 ? `, ${kept} already there and kept (--force replaces them)` : "") + ".", ); log.info( " docsSiteFile() reads these in place of the bundled templates and assets; edit them to own " + @@ -890,7 +894,9 @@ function reportLibrary(result: LibraryEjectResult): void { // Never clobber without consent — the same contract the generator path keeps, and // the stakes are higher here: these files are the adopter's MODEL. for (const f of kept) { - log.info(` ${f.path} already exists — left untouched (--force replaces it).`); + log.info(f.identical === true + ? ` ${f.path} already matches the shipped copy — nothing to do.` + : ` ${f.path} already exists — left untouched (--force replaces it).`); } } log.info( diff --git a/server/typescript/packages/cli/src/commands/init.ts b/server/typescript/packages/cli/src/commands/init.ts index 29e51fe13a..e8142a2820 100644 --- a/server/typescript/packages/cli/src/commands/init.ts +++ b/server/typescript/packages/cli/src/commands/init.ts @@ -341,6 +341,8 @@ async function stackForAgentContext(opts: InitOptions, prior: Manifest | undefin async function writeUnlessDryRun(cwd: string, dryRun: boolean, path: string, contents: string): Promise { if (dryRun) return; const abs = join(cwd, path); + // Identical bytes are left alone: a rewrite would only move the timestamp. + if (existsSyncWrap(abs) && readFileSyncWrap(abs, "utf8") === contents) return; await mkdir(dirname(abs), { recursive: true }); await writeFile(abs, contents, "utf8"); } @@ -442,11 +444,14 @@ async function writeAgentContext(opts: InitOptions, result: InitResult): Promise `${c.path} appears hand-edited; refreshed version ${verbed(dryRun, "written")} to ${c.newPath}`, ); } - await writeUnlessDryRun( - opts.cwd, dryRun, AGENT_CONTEXT_MANIFEST_PATH, - JSON.stringify(decision.manifest, null, 2) + "\n", - ); - result.created.push(AGENT_CONTEXT_MANIFEST_PATH); + // The manifest is rewritten only when its text changed, so a refresh that changed + // nothing leaves every file, the manifest included, exactly as it was. + const manifestText = JSON.stringify(decision.manifest, null, 2) + "\n"; + const manifestAbs = join(opts.cwd, AGENT_CONTEXT_MANIFEST_PATH); + if (!existsSyncWrap(manifestAbs) || readFileSyncWrap(manifestAbs, "utf8") !== manifestText) { + await writeUnlessDryRun(opts.cwd, dryRun, AGENT_CONTEXT_MANIFEST_PATH, manifestText); + result.created.push(AGENT_CONTEXT_MANIFEST_PATH); + } // A fragment this stack no longer assembles. `prunes` are ones we wrote that nobody has // touched — deleting is exactly as safe as the overwrite the same hash predicate already @@ -1116,7 +1121,10 @@ export async function initCommand(args: string[], cwd: string): Promise // Report the refresh, not a scaffold. `result.refreshedDocsOnly` (not `flags.refreshDocs`) // because --refresh-docs on an uninitialized repo falls through to a full init, which // genuinely DID scaffold and must still say so. - log.info(`Refreshed the MetaObjects agent context in place (${result.created.length} files): .metaobjects/AGENTS.md + the metaobjects-* skills.`); + // `created` lists only what was written: an unchanged file is never rewritten. + log.info(result.created.length === 0 + ? "The MetaObjects agent context is already current: no file changed." + : `Refreshed the MetaObjects agent context in place (${result.created.length} files): .metaobjects/AGENTS.md + the metaobjects-* skills.`); log.info("Your metadata, .metaobjects/config.json, codegen/generators/ and metaobjects.config.ts were left untouched."); for (const w of result.warnings) log.warn(w); } else if (flags.configOnly) { diff --git a/server/typescript/packages/cli/src/lib/docs-site-eject.ts b/server/typescript/packages/cli/src/lib/docs-site-eject.ts index 035a669987..85db333013 100644 --- a/server/typescript/packages/cli/src/lib/docs-site-eject.ts +++ b/server/typescript/packages/cli/src/lib/docs-site-eject.ts @@ -6,7 +6,7 @@ // the same place. import { existsSync } from "node:fs"; -import { mkdir, writeFile } from "node:fs/promises"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { OWNED_DOCS_SITE_DIR } from "@metaobjectsdev/codegen-ts"; import { readSiteFile, SITE_ASSET_NAMES, SITE_TEMPLATE_NAMES } from "@metaobjectsdev/docs-site"; @@ -18,6 +18,8 @@ export interface DocsSiteFileResult { /** Project-relative path. */ path: string; status: "created" | "preserved" | "replaced"; + /** Set when a kept file already holds exactly the shipped bytes. */ + identical?: true; } /** @@ -36,11 +38,14 @@ export async function ejectDocsSite(projectRoot: string, force: boolean): Promis const path = `${dir}/${name}`; const abs = join(projectRoot, path); const existed = existsSync(abs); - if (existed && !force) { - out.push({ path, status: "preserved" }); + const text = readSiteFile(kind, name); + // Kept unless --force; and --force over identical bytes writes nothing either. + const identical = existed && (await readFile(abs, "utf8")) === text; + if (existed && (!force || identical)) { + out.push({ path, status: "preserved", ...(identical && { identical: true as const }) }); continue; } - await writeFile(abs, readSiteFile(kind, name), "utf8"); + await writeFile(abs, text, "utf8"); out.push({ path, status: existed ? "replaced" : "created" }); } } diff --git a/server/typescript/packages/cli/src/lib/library-eject.ts b/server/typescript/packages/cli/src/lib/library-eject.ts index 1829e909a3..45d51c9cc8 100644 --- a/server/typescript/packages/cli/src/lib/library-eject.ts +++ b/server/typescript/packages/cli/src/lib/library-eject.ts @@ -74,6 +74,8 @@ export interface EjectedLibraryFile { /** Path relative to the project root. */ path: string; status: "created" | "preserved" | "replaced"; + /** Set when a kept file already holds exactly the shipped bytes. */ + identical?: true; } export interface LibraryEjectResult { @@ -120,8 +122,10 @@ export async function ejectLibrary(opts: { const name = ejectedFileName(opts.name, ref); const abs = join(root, name); const existed = await fileExists(abs); - if (existed && opts.force !== true) { - files.push({ ref, path: name, status: "preserved" }); + // Kept unless --force; and --force over identical bytes writes nothing either. + const identical = existed && (await readFile(abs, "utf8")) === text; + if (existed && (opts.force !== true || identical)) { + files.push({ ref, path: name, status: "preserved", ...(identical && { identical: true as const }) }); continue; } await writeFile(abs, text, "utf8"); diff --git a/server/typescript/packages/cli/src/lib/runtime-eject.ts b/server/typescript/packages/cli/src/lib/runtime-eject.ts index 500be335de..688c23c6c2 100644 --- a/server/typescript/packages/cli/src/lib/runtime-eject.ts +++ b/server/typescript/packages/cli/src/lib/runtime-eject.ts @@ -175,7 +175,8 @@ export async function ejectRuntime(cwd: string, names: readonly string[], force: const abs = join(cwd, path); const existing = existsSync(abs) ? await readFile(abs, "utf8") : undefined; const comparison = existing === undefined ? undefined : await compareOwnedCopy(existing, source); - if (existing !== undefined && !force) { + // Kept unless --force; and --force over identical bytes writes nothing either. + if (existing !== undefined && (!force || existing === source)) { files.push({ path, status: "preserved", comparison }); continue; } diff --git a/server/typescript/packages/cli/src/lib/template-eject.ts b/server/typescript/packages/cli/src/lib/template-eject.ts index 088e532f25..d49012d9a6 100644 --- a/server/typescript/packages/cli/src/lib/template-eject.ts +++ b/server/typescript/packages/cli/src/lib/template-eject.ts @@ -385,7 +385,8 @@ export async function ejectTemplates( const abs = join(cwd, file.path); const existing = existsSync(abs) ? await readFile(abs, "utf8") : undefined; const comparison = existing === undefined ? undefined : await compareOwnedCopy(existing, file.content); - if (existing !== undefined && !force) { + // Kept unless --force; and --force over identical bytes writes nothing either. + if (existing !== undefined && (!force || existing === file.content)) { files.push({ path: file.path, status: "preserved", comparison }); continue; } diff --git a/server/typescript/packages/cli/test/docs-page-conformance.test.ts b/server/typescript/packages/cli/test/docs-page-conformance.test.ts new file mode 100644 index 0000000000..a8130a1599 --- /dev/null +++ b/server/typescript/packages/cli/test/docs-page-conformance.test.ts @@ -0,0 +1,124 @@ +// The TypeScript runner of `fixtures/docs-page-conformance/` — the shared corpus that pins the +// requirements pages and the model-only schema page for every port (plan G0, design call 17). +// +// TypeScript is the SOURCE of the expected bytes: each case's `expected/` is what the +// TypeScript builders and the shared templates produce from the case's `input/`, and this +// runner fails the moment they disagree. Every other port runs the same cases against its +// own builders and the same templates. `expected/data/` pins what each template is FED, so a +// port can tell a builder defect (wrong data) from a render defect (right data, wrong bytes). +// +// The schema page pinned here is the MODEL-ONLY one (`physical: false`): the page a port +// without the expected schema writes. TypeScript builds its input from the expected schema +// and then leaves out every fact only that schema knows, so the bytes are exactly what a port +// computes from the model with its own naming helpers. The README lists what is left out. +// +// Regenerate after an intended change: `UPDATE_DOCS_PAGE_FIXTURES=1 bun test +// test/docs-page-conformance.test.ts`, then review the diff — it is the cross-port contract. + +import { describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { InMemoryStringSource, MetaDataLoader, physicalNamingOf } from "@metaobjectsdev/metadata"; +import type { MetaRoot } from "@metaobjectsdev/metadata"; +import { resolveSchemaConventions } from "@metaobjectsdev/migrate-ts"; +import { + agentRequirementsPageData, + agentSchemaPageData, + renderAgentRequirementsPage, + renderAgentSchemaPage, + renderRequirementsMarkdown, + renderRequirementsToon, + requirementRows, + requirementsLedgerData, + requirementsToonData, +} from "@metaobjectsdev/codegen-ts"; +import { buildAgentSchemaInput } from "../src/lib/agent-schema.js"; + +const CORPUS = resolve(import.meta.dir, "../../../../../fixtures/docs-page-conformance/cases"); +const UPDATE = process.env.UPDATE_DOCS_PAGE_FIXTURES === "1"; + +async function load(dir: string): Promise { + const files = readdirSync(dir).filter((f) => /^meta\..*\.json$/.test(f)).sort(); + const res = await new MetaDataLoader().load( + files.map((f) => new InMemoryStringSource(readFileSync(join(dir, f), "utf8"), { id: f, format: "json" })), + ); + expect(res.errors).toEqual([]); + return res.root; +} + +/** Every pinned output of one case, by path under `expected/`. An absent page is no entry. */ +async function outputsOf(root: MetaRoot): Promise> { + const out = new Map(); + const json = (v: unknown): string => `${JSON.stringify(v, null, 2)}\n`; + + const rows = requirementRows(root); + if (rows.length > 0) { + out.set("requirements.md", renderRequirementsMarkdown(rows)); + out.set("requirements.toon", renderRequirementsToon(rows)); + out.set("data/requirements.md.json", json(requirementsLedgerData(rows))); + out.set("data/requirements.toon.json", json(requirementsToonData(rows))); + } + const agentRequirements = agentRequirementsPageData(root); + if (agentRequirements !== undefined) { + out.set("agent/requirements.md", renderAgentRequirementsPage(root)); + out.set("data/agent-requirements.md.json", json(agentRequirements)); + } + + // The schema the TypeScript toolchain builds; the dialect only feeds what the model-only + // page leaves out, so the page does not depend on it. + const schema = buildAgentSchemaInput(root, "postgres", () => {}, { + conventions: resolveSchemaConventions(undefined), + skipRedundantChecks: false, + foreignKeyIndexes: false, + foreignKeyTargets: "refuse", + }); + if (schema !== undefined) { + const naming = physicalNamingOf(root).columns; + const data = agentSchemaPageData(root, schema, naming, { physical: false }); + if (data !== undefined) { + out.set("agent/schema.md", renderAgentSchemaPage(root, schema, naming, { physical: false })); + out.set("data/agent-schema.md.json", json(data)); + } + } + return out; +} + +function expectedOf(dir: string): Map { + const out = new Map(); + if (!existsSync(dir)) return out; + const walk = (d: string, prefix: string): void => { + for (const e of readdirSync(d, { withFileTypes: true })) { + if (e.isDirectory()) walk(join(d, e.name), `${prefix}${e.name}/`); + else out.set(`${prefix}${e.name}`, readFileSync(join(d, e.name), "utf8")); + } + }; + walk(dir, ""); + return out; +} + +const cases = readdirSync(CORPUS, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort(); + +describe("docs-page-conformance", () => { + test("the corpus is not empty", () => { + expect(cases.length).toBeGreaterThan(0); + }); + + for (const name of cases) { + test(name, async () => { + const caseDir = join(CORPUS, name); + const actual = await outputsOf(await load(join(caseDir, "input"))); + const expectedDir = join(caseDir, "expected"); + if (UPDATE) { + rmSync(expectedDir, { recursive: true, force: true }); + for (const [path, content] of actual) { + mkdirSync(dirname(join(expectedDir, path)), { recursive: true }); + writeFileSync(join(expectedDir, path), content); + } + } + const expected = expectedOf(expectedDir); + // The SET of pages is pinned too: a page one port writes and another does not is drift. + expect([...actual.keys()].sort()).toEqual([...expected.keys()].sort()); + for (const [path, content] of expected) expect({ path, content: actual.get(path) }).toEqual({ path, content }); + }); + } +}); diff --git a/server/typescript/packages/cli/test/eject-library.test.ts b/server/typescript/packages/cli/test/eject-library.test.ts index 9037bc53f3..87c92821db 100644 --- a/server/typescript/packages/cli/test/eject-library.test.ts +++ b/server/typescript/packages/cli/test/eject-library.test.ts @@ -7,7 +7,7 @@ // their origin legible later, and they tell the adopter the one step that finishes the // job — which the loader then enforces. import { describe, test, expect } from "bun:test"; -import { mkdtempSync, mkdirSync, rmSync, readFileSync, writeFileSync, existsSync, readdirSync } from "node:fs"; +import { mkdtempSync, mkdirSync, rmSync, readFileSync, statSync, writeFileSync, existsSync, readdirSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { ejectCommand } from "../src/commands/eject.js"; @@ -82,6 +82,13 @@ describe("meta eject ", () => { const forced = await ejectLibrary({ cwd: root, name: "iam", force: true }); expect(forced.files.find((f) => f.ref === "iam/model")!.status).toBe("replaced"); + + // --force over files that already hold the shipped bytes writes nothing. + const model = join(root, "model", "meta.iam.model.yaml"); + const before = statSync(model).mtimeMs; + const again2 = await ejectLibrary({ cwd: root, name: "iam", force: true }); + expect(again2.files.every((f) => f.status === "preserved" && f.identical === true)).toBe(true); + expect(statSync(model).mtimeMs).toBe(before); } finally { rmSync(root, { recursive: true, force: true }); } diff --git a/server/typescript/packages/cli/test/eject.test.ts b/server/typescript/packages/cli/test/eject.test.ts index b7ffd879b1..011fb907b9 100644 --- a/server/typescript/packages/cli/test/eject.test.ts +++ b/server/typescript/packages/cli/test/eject.test.ts @@ -1,13 +1,22 @@ // FR-040 §4.2(a) — eject copies a reference template into the consumer's repo so they // own it, for any generator in any package, at any time after init. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtemp, rm, readFile, mkdir, writeFile } from "node:fs/promises"; +import { mkdtemp, rm, readFile, readdir, mkdir, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { ejectGenerator, ejectableNames } from "../src/commands/eject.js"; import { Biome, Distribution } from "@biomejs/js-api"; let cwd: string; +/** Every file under `dir`, recursively. */ +async function allFiles(dir: string): Promise { + const out: string[] = []; + for (const e of await readdir(dir, { withFileTypes: true })) { + const p = join(dir, e.name); + if (e.isDirectory()) out.push(...(await allFiles(p))); else out.push(p); + } + return out.sort(); +} beforeEach(async () => { cwd = await mkdtemp(join(tmpdir(), "mo-eject-")); }); afterEach(async () => { await rm(cwd, { recursive: true, force: true }); }); @@ -260,11 +269,17 @@ describe("meta eject reports how the owned copy compares to the reference", () = .not.toContain("deliberate: trimmed"); }); - test("--force over an IDENTICAL copy is a replace with nothing lost", async () => { - await own("queries"); - const r = await ejectGenerator({ cwd, name: "queries", force: true }); - expect(r.status).toBe("replaced"); + test("--force over an IDENTICAL copy writes nothing: the file, its templates and runtime stay as they were", async () => { + await own("entity"); + const written = await allFiles(cwd); + const before = await Promise.all(written.map(async (f) => (await stat(f)).mtimeMs)); + await new Promise((r) => setTimeout(r, 20)); + const r = await ejectGenerator({ cwd, name: "entity", force: true }); + expect(r.status).toBe("preserved"); expect(r.comparison?.verdict).toBe("identical"); + expect(r.templates?.files.every((f) => f.status === "preserved")).toBe(true); + expect(r.runtime?.files.every((f) => f.status === "preserved")).toBe(true); + expect(await Promise.all(written.map(async (f) => (await stat(f)).mtimeMs))).toEqual(before); }); test("a first eject reports no comparison at all", async () => { diff --git a/server/typescript/packages/cli/test/gen-skip-conformance.test.ts b/server/typescript/packages/cli/test/gen-skip-conformance.test.ts index b978e9db6d..29b4c34de6 100644 --- a/server/typescript/packages/cli/test/gen-skip-conformance.test.ts +++ b/server/typescript/packages/cli/test/gen-skip-conformance.test.ts @@ -76,20 +76,22 @@ export function mine(opts: { cache?: boolean } = {}) { } `; -const config = (mineArgs = "") => `import { defineConfig } from "@metaobjectsdev/codegen-ts"; -import { mine } from "./codegen/generators/mine"; +const config = (mineArgs = "", docs = false) => `import { defineConfig } from "@metaobjectsdev/codegen-ts"; +${docs ? 'import { docsFile, templateGenerator } from "@metaobjectsdev/codegen-ts/generators";\n' : ""}import { mine } from "./codegen/generators/mine"; export default defineConfig({ outDir: "generated", dialect: "sqlite", dbImport: "~/db", extStyle: "none", - generators: ["entity", mine(${mineArgs})], +${docs ? ' targets: { docs: { outDir: "./docs/generated" } },\n' : ""} generators: ["entity", mine(${mineArgs})${docs + ? ', templateGenerator({ name: "note", template: "note", scope: "perEntity", outputPattern: "notes/{name}.txt" }), docsFile()' + : ""}], }); `; interface Project { root: string; } -function makeProject(opts: { uncacheable?: boolean } = {}): Project { +function makeProject(opts: { uncacheable?: boolean; docs?: boolean } = {}): Project { mkdirSync(WORKSPACE_TMP, { recursive: true }); const root = mkdtempSync(join(WORKSPACE_TMP, "gen-skip-")); made.push(root); @@ -106,7 +108,7 @@ function makeProject(opts: { uncacheable?: boolean } = {}): Project { writeFileSync(join(root, "codegen", "generators", "mine.ts"), OWNED); writeFileSync(join(root, "extra.txt"), "extra\n"); writeFileSync(join(root, "README.md"), "a project\n"); - writeFileSync(join(root, "metaobjects.config.ts"), config(opts.uncacheable === true ? "{ cache: false }" : "")); + writeFileSync(join(root, "metaobjects.config.ts"), config(opts.uncacheable === true ? "{ cache: false }" : "", opts.docs === true)); return { root }; } @@ -150,6 +152,8 @@ async function verifyMayAnswer(p: Project, r: Runner): Promise { /** One case: what to change, and how to ask afterwards. */ interface Runner { uncacheable?: boolean; + /** Also configure a `template` generator and a docs page generator. */ + docs?: boolean; change?: (p: Project) => void | Promise; args?: string[]; env?: NodeJS.ProcessEnv; @@ -157,9 +161,19 @@ interface Runner { /** `verify --codegen --full`. */ full?: boolean; /** Checked after both answers: what the read-only questions must have left alone. */ - after?: (p: Project) => void; + after?: (p: Project) => void | Promise; } +/** Every file under `dir`, recursively, with its bytes and modification time. */ +const snapshotTree = (dir: string): [string, string, number][] => + !existsSync(dir) ? [] : readdirSync(dir, { recursive: true, withFileTypes: true }) + .filter((e) => e.isFile()) + .map((e): [string, string, number] => { + const f = join(e.parentPath, e.name); + return [f, readFileSync(f, "utf-8"), statSync(f).mtimeMs]; + }) + .sort((a, b) => a[0].localeCompare(b[0])); + const append = (path: string, text: string) => writeFileSync(path, readFileSync(path, "utf-8") + text); const RUNNERS: Record = { @@ -239,6 +253,24 @@ const RUNNERS: Record = { }, }, "force": { args: ["--force"], full: true }, + "template-and-docs-rerun": { + docs: true, + after: async (p) => { + // The first run really wrote the template output and the docs page. + expect(existsSync(join(p.root, "generated", "notes", "Order.txt"))).toBe(true); + expect(snapshotTree(join(p.root, "docs", "generated")).length).toBeGreaterThan(0); + const watched = () => [ + ...snapshotTree(join(p.root, "generated")), + ...snapshotTree(join(p.root, "docs", "generated")), + ...snapshotTree(join(p.root, ".metaobjects", ".gen-state", ".hashes")), + ]; + const before = watched(); + await new Promise((r) => setTimeout(r, 20)); + // A forced run renders everything again and writes zero files. + expect(await gen(p, ["--force"])).toBe(0); + expect(watched()).toEqual(before); + }, + }, "ci": { env: { CI: "true" } }, "failed-run": { change: async (p) => { @@ -260,13 +292,13 @@ describe("codegen-skip-conformance (ADR-0064)", () => { test(`${c.id}: gen ${c.gen}, verify ${c.verify}`, async () => { const runner = RUNNERS[c.id]; if (runner === undefined) throw new Error(`no runner for case "${c.id}"`); - const p = makeProject({ uncacheable: runner.uncacheable === true }); + const p = makeProject({ uncacheable: runner.uncacheable === true, docs: runner.docs === true }); expect(await gen(p)).toBe(0); expect(existsSync(stateFile(p))).toBe(runner.uncacheable !== true); await runner.change?.(p); expect(await genSkips(p, runner)).toBe(c.gen === "skip"); expect(await verifyMayAnswer(p, runner)).toBe(c.verify === "may-answer-no-drift"); - runner.after?.(p); + await runner.after?.(p); }, 30_000); } }); diff --git a/server/typescript/packages/cli/test/init.test.ts b/server/typescript/packages/cli/test/init.test.ts index 3befb26c85..d7c0d2d881 100644 --- a/server/typescript/packages/cli/test/init.test.ts +++ b/server/typescript/packages/cli/test/init.test.ts @@ -871,9 +871,10 @@ describe("initCommand --refresh-docs output (does what it says)", () => { expect(out).not.toContain('"type": "module"'); expect(out).not.toContain("meta migrate --from-db"); - // It should say what it DID do. - expect(out).toContain("Refreshed"); - expect(out).toContain(".metaobjects/AGENTS.md"); + // It should say what it DID do. Straight after init the scaffold is current, so the + // refresh writes nothing and says so (a refresh that changes a file names it, which + // init-refresh-docs.test.ts covers). + expect(out).toContain("already current: no file changed"); // And the claim has to be true: nothing else moved. expect(readFileSync(join(cwd, ".metaobjects", "config.json"), "utf8")).toBe(configBefore); diff --git a/server/typescript/packages/cli/test/integration/verify-codegen-foreign-files.test.ts b/server/typescript/packages/cli/test/integration/verify-codegen-foreign-files.test.ts index 501a51cb35..34db514518 100644 --- a/server/typescript/packages/cli/test/integration/verify-codegen-foreign-files.test.ts +++ b/server/typescript/packages/cli/test/integration/verify-codegen-foreign-files.test.ts @@ -251,7 +251,9 @@ export default defineConfig({ } finally { rmSync(root, { recursive: true, force: true }); } - }); + // Six end-to-end gen/verify runs, each loading the config and rendering (a verify is + // ~1.8s alone), so bun's 5s per-test default is shorter than the work itself. + }, 60_000); test("with no manifest at all, the old conservative verdict stands", async () => { const root = setupRepo(); diff --git a/server/typescript/packages/cli/test/template-eject.test.ts b/server/typescript/packages/cli/test/template-eject.test.ts index a1365b882a..9c8898d4ef 100644 --- a/server/typescript/packages/cli/test/template-eject.test.ts +++ b/server/typescript/packages/cli/test/template-eject.test.ts @@ -307,7 +307,12 @@ describe("ejectTemplates — never overwrites a file without force", () => { expect(readFileSync(join(project, "codegen/templates/b.ts"), "utf8")).toContain("// MINE"); const forced = await ejectTemplates(project, [closure], true); - expect(forced.files.every((f) => f.status === "replaced")).toBe(true); + // --force replaces the edited copy; the two that already hold the shipped bytes are not rewritten. + expect(forced.files.map((f) => [f.path, f.status])).toEqual([ + ["codegen/templates/a.ts", "preserved"], + ["codegen/templates/b.ts", "replaced"], + ["codegen/templates/cube/c.ts", "preserved"], + ]); expect(readFileSync(join(project, "codegen/templates/b.ts"), "utf8")).not.toContain("// MINE"); }); diff --git a/server/typescript/packages/cli/test/unit/docs-site-eject-force.test.ts b/server/typescript/packages/cli/test/unit/docs-site-eject-force.test.ts new file mode 100644 index 0000000000..0d41e6e5a0 --- /dev/null +++ b/server/typescript/packages/cli/test/unit/docs-site-eject-force.test.ts @@ -0,0 +1,38 @@ +// `meta eject docs-site --force` over files that already hold the shipped bytes writes +// nothing: --force replaces what differs, it does not churn what does not. +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, readdirSync, statSync, writeFileSync } from "node:fs"; +import { rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { ejectDocsSite } from "../../src/lib/docs-site-eject.js"; + +const made: string[] = []; +afterEach(async () => { while (made.length > 0) await rm(made.pop()!, { recursive: true, force: true }); }); + +const filesUnder = (dir: string): string[] => + readdirSync(dir, { withFileTypes: true }).flatMap((e) => + e.isDirectory() ? filesUnder(join(dir, e.name)) : [join(dir, e.name)]).sort(); + +describe("ejectDocsSite --force", () => { + test("rewrites only the file that differs from the shipped copy", async () => { + const root = mkdtempSync(join(process.env.DEV_SCRATCH || tmpdir(), "docs-site-eject-force-")); + made.push(root); + const first = await ejectDocsSite(root, false); + expect(first.every((f) => f.status === "created")).toBe(true); + + const all = filesUnder(join(root, "codegen", "docs-site")); + const edited = join(root, first[0]!.path); + writeFileSync(edited, "/* owned */\n", "utf8"); + const before = new Map(all.map((f) => [f, statSync(f).mtimeMs])); + await new Promise((r) => setTimeout(r, 20)); + + const forced = await ejectDocsSite(root, true); + expect(forced.filter((f) => f.status === "replaced").map((f) => f.path)).toEqual([first[0]!.path]); + expect(forced.filter((f) => f.status !== "replaced").every((f) => f.status === "preserved" && f.identical === true)).toBe(true); + for (const f of all) { + if (f === edited) expect(statSync(f).mtimeMs).not.toBe(before.get(f)!); + else expect(statSync(f).mtimeMs).toBe(before.get(f)!); + } + }); +}); diff --git a/server/typescript/packages/cli/test/unit/init-refresh-docs.test.ts b/server/typescript/packages/cli/test/unit/init-refresh-docs.test.ts index 64f14ba05e..3770dbfad5 100644 --- a/server/typescript/packages/cli/test/unit/init-refresh-docs.test.ts +++ b/server/typescript/packages/cli/test/unit/init-refresh-docs.test.ts @@ -1,8 +1,9 @@ import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync } from "node:fs"; +import { mkdtempSync, rmSync, existsSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { init, initCommand } from "../../src/commands/init.js"; +import { hashContents } from "@metaobjectsdev/sdk"; let cwd: string; beforeEach(() => { @@ -53,11 +54,32 @@ describe("init --refresh-docs", () => { test("refresh overwrites AGENTS.md when it is unmodified since last scaffold", async () => { await init({ cwd }); + // Stand in for an older scaffold: different bytes, recorded in the manifest as ours. + const agents = join(cwd, ".metaobjects", "AGENTS.md"); + const manifestPath = join(cwd, ".metaobjects", ".agent-context.json"); + const fresh = readFileSync(agents, "utf8"); + writeFileSync(agents, "an older scaffold\n", "utf8"); + const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as { files: Record }; + manifest.files[".metaobjects/AGENTS.md"] = hashContents("an older scaffold\n"); + writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + "\n", "utf8"); + const result = await init({ cwd, refreshDocs: true }); expect(result.created).toContain(".metaobjects/AGENTS.md"); + expect(readFileSync(agents, "utf8")).toBe(fresh); expect(existsSync(join(cwd, ".metaobjects", "AGENTS.md.new"))).toBe(false); }); + test("a refresh that changes nothing rewrites no file, the manifest included", async () => { + await init({ cwd }); + const watched = [join(cwd, ".metaobjects", "AGENTS.md"), join(cwd, ".metaobjects", ".agent-context.json")]; + const before = watched.map((f) => statSync(f).mtimeMs); + await new Promise((r) => setTimeout(r, 20)); + const result = await init({ cwd, refreshDocs: true }); + expect(watched.map((f) => statSync(f).mtimeMs)).toEqual(before); + expect(result.created).not.toContain(".metaobjects/AGENTS.md"); + expect(result.created).not.toContain(".metaobjects/.agent-context.json"); + }); + test("--refresh-docs works on a fresh repo too (full init runs)", async () => { await init({ cwd, refreshDocs: true }); expect(existsSync(join(cwd, ".metaobjects", "AGENTS.md"))).toBe(true); diff --git a/server/typescript/packages/codegen-ts/src/contract/build-openapi.ts b/server/typescript/packages/codegen-ts/src/contract/build-openapi.ts index 126d40db34..b2c9ef3076 100644 --- a/server/typescript/packages/codegen-ts/src/contract/build-openapi.ts +++ b/server/typescript/packages/codegen-ts/src/contract/build-openapi.ts @@ -3,8 +3,8 @@ // mounts. `components.schemas` is the canonical JSON Schema (an OpenAPI 3.1 schema IS JSON Schema // 2020-12), so the two artifacts cannot disagree. // -// It states the cross-port contract only. The TS-only filter extensions (`?search`, `filter[or]`) -// are left out, and so are the `405` refusals on a read-only surface, which are not operations a +// It states the per-field list parameters only. `?search` and `filter[or]` / `filter[and]` (in +// the REST contract since 1.3.0) are not described yet. Nor are the `405` refusals on a read-only surface, which are not operations a // caller can use (the api docs omit them for the same reason): a read-only resource says so in the // description of its operations instead. // diff --git a/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts b/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts index 8295b5d03a..5988cf8dc4 100644 --- a/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts @@ -37,42 +37,14 @@ // preservation to think about: regenerate and the page is current. import { physicalNamingGuideUrl } from "@metaobjectsdev/metadata/release-docs"; -import { - CARDINALITY_MANY, - CARDINALITY_ONE, - FIELD_SUBTYPE_ENUM, - ORIGIN_AGGREGATE_ATTR_AGG, - ORIGIN_AGGREGATE_ATTR_OF, - ORIGIN_AGGREGATE_ATTR_VIA, - ORIGIN_ATTR_ORDER_BY, - ORIGIN_PASSTHROUGH_ATTR_FROM, - ORIGIN_PASSTHROUGH_ATTR_VIA, - ORIGIN_SUBTYPE_AGGREGATE, - ORIGIN_SUBTYPE_COMPUTED, - ORIGIN_SUBTYPE_FIRST, - ORIGIN_SUBTYPE_PASSTHROUGH, - RELATIONSHIP_ATTR_CARDINALITY, - RELATIONSHIP_ATTR_OBJECT_REF, - RELATIONSHIP_ATTR_ON_DELETE, - RELATIONSHIP_ATTR_THROUGH, - PHYSICAL_NAME_ATTR_BY_KIND, - SOURCE_ROLE_PRIMARY, - TYPE_ORIGIN, - resolveColumnName, - physicalNamingOf, - physicalNamingRemovedMessage, -} from "@metaobjectsdev/metadata"; -import type { MetaField, MetaObject } from "@metaobjectsdev/metadata"; +import { physicalNamingOf, physicalNamingRemovedMessage } from "@metaobjectsdev/metadata"; import type { EmittedFile, Generator, GeneratorFactory } from "../generator.js"; -import { resolveObjectNames } from "../names.js"; -import { isAbstract } from "../instance-artifacts.js"; -import { isReport } from "../source-detect.js"; -import { enumValues, intValueMapOf } from "../enum-meta.js"; import { renderAgentSchemaPage } from "./agent-schema-page.js"; import { renderAgentUiPage } from "./agent-ui-page.js"; import { renderAgentRequirementsPage } from "./agent-requirements-page.js"; import type { AgentSchemaInput } from "./agent-schema-input.js"; import { DOCS_TARGET_NAME } from "../docs-run.js"; +import { docsTemplateRoot, projectProvider } from "../render-engine/framework-provider.js"; /** All three pages live here, under the docs root. */ const DEFAULT_AGENT_DIR = "agent"; @@ -89,125 +61,10 @@ export interface AgentDocsFileOpts { * page rather than a page of unknowns. */ schema?: AgentSchemaInput; -} - -/** One `origin.*` child rendered as a lineage phrase. `origin.*` NEVER inherits, so the - * own-accessor read here is the correct one rather than an ADR-0039 slip. */ -function lineageOf(field: MetaField): string | undefined { - const origin = field.ownChildren().find((c) => c.type === TYPE_ORIGIN); - if (origin === undefined) return undefined; - // Human-facing text: references print as the author wrote them (ADR-0059). - const str = (name: string): string | undefined => { - const v = origin.authoredAttr(name); - return typeof v === "string" && v !== "" ? v : undefined; - }; - switch (origin.subType) { - case ORIGIN_SUBTYPE_PASSTHROUGH: { - const from = str(ORIGIN_PASSTHROUGH_ATTR_FROM); - const via = str(ORIGIN_PASSTHROUGH_ATTR_VIA); - return `passthrough from \`${from ?? "?"}\`${via === undefined ? "" : ` via \`${via}\``}`; - } - case ORIGIN_SUBTYPE_AGGREGATE: { - const agg = str(ORIGIN_AGGREGATE_ATTR_AGG) ?? "?"; - const of = str(ORIGIN_AGGREGATE_ATTR_OF); - const via = str(ORIGIN_AGGREGATE_ATTR_VIA); - return `\`${agg}\`${of === undefined ? "" : ` of \`${of}\``}${via === undefined ? "" : ` via \`${via}\``}`; - } - case ORIGIN_SUBTYPE_FIRST: { - const of = str(ORIGIN_AGGREGATE_ATTR_OF); - const via = str(ORIGIN_AGGREGATE_ATTR_VIA); - const order = str(ORIGIN_ATTR_ORDER_BY); - return `first${of === undefined ? "" : ` \`${of}\``}${via === undefined ? "" : ` via \`${via}\``}` + - `${order === undefined ? "" : ` ordered by \`${order}\``}`; - } - case ORIGIN_SUBTYPE_COMPUTED: - // The @expr tree is structured; naming it is enough to route a reader to the - // declaration, and rendering a tree into a cell would be a second SQL lowering. - return "computed from a declared `@expr`"; - default: - return `\`origin.${origin.subType}\``; - } -} - -/** - * The cardinality phrase, from the DECLARING object's side. - * - * `@cardinality: one` does NOT mean one-to-one. It means this object holds the foreign - * key — many rows of it point at one target row — which is what `relation-resolver.ts` - * builds a belongs-to `one()` relation from. Rendering it as "one-to-one" told a reader - * the target row is claimed by at most one row here, which is the direction that makes - * someone write a lookup expecting a single result. - * - * `@cardinality` is OPTIONAL vocabulary (min 0), and ABSENT is its own answer: no - * navigation is generated at all. Folding that into "one-to-one" invented a shape the - * model never declared. - */ -function cardinalityPhrase(cardinality: unknown, through: unknown): string { - if (cardinality === CARDINALITY_MANY) { - return typeof through === "string" && through !== "" ? "many-to-many" : "one-to-many"; - } - if (cardinality === CARDINALITY_ONE) return "many-to-one"; - return "cardinality not declared"; -} - -/** `- \`Order.lines\` — one-to-many → \`OrderLine\`` */ -function relationshipLines(objects: readonly MetaObject[]): string[] { - const out: string[] = []; - for (const obj of objects) { - for (const rel of obj.relationships()) { - const cardinality = rel.attr(RELATIONSHIP_ATTR_CARDINALITY); - // References print as the author wrote them (ADR-0059); the loaded value is canonical. - const target = rel.authoredAttr(RELATIONSHIP_ATTR_OBJECT_REF); - const through = rel.authoredAttr(RELATIONSHIP_ATTR_THROUGH); - const onDelete = rel.attr(RELATIONSHIP_ATTR_ON_DELETE); - // The FQN, not the short name: this line is an ADDRESS a reader searches for. - const parts = [`\`${obj.resolutionKey()}.${rel.name}\``, `\`${rel.subType}\``]; - parts.push( - `${cardinalityPhrase(cardinality, through)} → \`${String(target ?? "?")}\``, - ); - if (typeof through === "string" && through !== "") parts.push(`through \`${through}\``); - if (typeof onDelete === "string" && onDelete !== "") parts.push(`on delete \`${onDelete}\``); - out.push(`- ${parts.join(" · ")}`); - } - } - return out; -} - -/** - * `| \`Order.status\` | OPEN, CLOSED | string-backed |` - * - * `objects` IS ONLY THE TABLE-BACKED SUBSET OF THE MODEL — the caller scopes it to the - * objects the snapshot actually holds as tables. This section sits on the SCHEMA page, so - * every row it prints is read as a statement about a column. Walking every loaded object - * printed rows for abstract bases, for `object.value`s that have no column anywhere, and - * for projections whose "column" is a view expression — three kinds of thing the physical - * schema does not contain. - * - * It also says nothing about a `CHECK`. Whether the database constrains the members is - * `table.checks`, which is already on this page from the snapshot, and an `@isArray` - * enum deliberately gets none (`migrate-ts` skips it) — so asserting one here was a - * SECOND derivation of a fact the page already carries correctly, in the direction that - * promises the database will refuse a value it will accept. - */ -function enumLines(objects: readonly MetaObject[]): string[] { - const rows: string[] = []; - for (const obj of objects) { - for (const field of obj.fields()) { - if (field.subType !== FIELD_SUBTYPE_ENUM) continue; - const members = enumValues(field); - if (members === undefined || members.length === 0) continue; - const intMap = intValueMapOf(field); - const backing = - intMap === undefined - ? "string-backed" - : `int-backed (${members.map((m) => `${m}=${intMap[m]}`).join(", ")})`; - rows.push( - `| \`${obj.resolutionKey()}.${field.name}\` | ${members.map((m) => `\`${m}\``).join(", ")} | ${backing} |`, - ); - } - } - if (rows.length === 0) return []; - return ["| Field | Members | Storage |", "|---|---|---|", ...rows]; + /** Directory whose `templates/agent/{schema,requirements}.md.mustache` (and + * `templates/requirements/requirements.md.mustache`, the embedded ledger) override the + * shipped pages, relative to the project. Default: the project's own `templates/`. */ + templates?: string; } export const agentDocsFile = function agentDocsFile(opts?: AgentDocsFileOpts): Generator { @@ -223,8 +80,10 @@ export const agentDocsFile = function agentDocsFile(opts?: AgentDocsFileOpts): G name: "agent-docs", target: opts?.target ?? DOCS_TARGET_NAME, generate(ctx) { - const objects = ctx.loadedRoot.objects(); const files: EmittedFile[] = []; + // The schema and requirements pages render shared templates; a same-named template + // under the project's `templates/` (or under `opts.templates`) replaces one. + const provider = projectProvider(docsTemplateRoot(ctx, opts?.templates)); // What the run computes for this generator (docs-run.ts): the schema is built by the // caller that owns the schema builder, on first ask. Options win: they are what a // direct caller of the factory states. @@ -232,71 +91,10 @@ export const agentDocsFile = function agentDocsFile(opts?: AgentDocsFileOpts): G const columnNamingStrategy = ctx.renderContext?.columnNamingStrategy ?? physicalNamingOf(ctx.loadedRoot).columns; // ---- schema.md + // The model walk (column → declaring field, view lineage, relationships, enums) is + // the page builder's; this passes it the model, the schema and the naming. if (schemaInput !== undefined) { - const schema = schemaInput; - // The qualified names the snapshot actually holds. An object whose physical name - // is not one of these contributes nothing to the physical schema (an abstract - // base, a sourceless value, an `@unmanaged` object) and must not appear on a page - // describing it — `buildExpectedSchema`'s Pass 1 owns those skip rules and this - // reads its answer rather than re-deriving them. - const tableNames = new Set(schema.tables.map((t) => schema.qualify(t))); - const viewNames = new Set(schema.views.map((v) => schema.qualify(v))); - // The objects backed by a TABLE in the snapshot — the enum section's scope, since - // a row there is read as a statement about a column. - const tableBacked: MetaObject[] = []; - // column → declaring field, per qualified table name. `resolveObjectNames` is the - // ONE field→column resolver — the same one the names artifact and the DDL use — - // so this mapping cannot disagree with the column it labels. - const declaredBy = new Map>(); - const viewLineage = new Map(); - // Qualified names of the views a view-backed object.report owns (FR-044). Empty for a - // model with no report, so the page is byte-identical to what it was before reports. - const reportViews = new Set(); - for (const obj of objects) { - const names = resolveObjectNames(obj, columnNamingStrategy); - // The PRIMARY source's physical name and schema — `names.name` is the object's - // metamodel name since 0.25.0, which would match nothing in the snapshot. - const primary = names?.sources[SOURCE_ROLE_PRIMARY]; - const physical = primary === undefined - ? undefined - : primary[(PHYSICAL_NAME_ATTR_BY_KIND.get(primary.kind) ?? "") as keyof typeof primary]; - if (typeof physical !== "string") continue; - const key = schema.qualify({ name: physical, schema: primary?.schema }); - const isTable = tableNames.has(key); - if (!isTable && !viewNames.has(key)) continue; - // ABSTRACT BASES ARE EXCLUDED, and being in the snapshot does not exempt them: - // an abstract base that declares the `source.rdb` its concrete child inherits - // resolves to that child's table, so the qualified-name test admits it and the - // page printed the base's enum a second time under a different owner. - // `buildExpectedSchema`'s Pass 1 skips abstracts; this reads the same rule. - if (isTable && !isAbstract(obj)) tableBacked.push(obj); - if (!isTable && isReport(obj)) reportViews.add(key); - let map = declaredBy.get(key); - if (map === undefined) { - map = new Map(); - declaredBy.set(key, map); - } - const lineage: string[] = []; - for (const field of obj.fields()) { - const column = resolveColumnName(field, columnNamingStrategy); - // A TPH base and its subtypes share one table: first writer wins, so the - // base's own column keeps its label rather than being relabelled by whichever - // subtype was walked last. - if (!map.has(column)) { - map.set(column, { field: field.name, type: `${field.type}.${field.subType}` }); - } - const line = lineageOf(field); - if (line !== undefined) lineage.push(`| \`${column}\` | ${line} |`); - } - if (lineage.length > 0) viewLineage.set(key, lineage); - } - const content = renderAgentSchemaPage(schema, { - declaredBy, - viewLineage, - reportViews, - relationships: relationshipLines(objects), - enums: enumLines(tableBacked), - }); + const content = renderAgentSchemaPage(ctx.loadedRoot, schemaInput, columnNamingStrategy, { provider }); if (content !== "") files.push({ path: `${dir}/schema.md`, content }); } @@ -333,7 +131,7 @@ export const agentDocsFile = function agentDocsFile(opts?: AgentDocsFileOpts): G } // ---- requirements.md - const requirements = renderAgentRequirementsPage(ctx.loadedRoot, ctx.inLedger); + const requirements = renderAgentRequirementsPage(ctx.loadedRoot, ctx.inLedger, provider); if (requirements !== "") files.push({ path: `${dir}/requirements.md`, content: requirements }); return files; diff --git a/server/typescript/packages/codegen-ts/src/generators/agent-requirements-page.ts b/server/typescript/packages/codegen-ts/src/generators/agent-requirements-page.ts index 4e3eee64a8..f70f8d5ae6 100644 --- a/server/typescript/packages/codegen-ts/src/generators/agent-requirements-page.ts +++ b/server/typescript/packages/codegen-ts/src/generators/agent-requirements-page.ts @@ -31,14 +31,26 @@ // against 19 of 40 — and the page an agent is told to read *before adding a capability* is // the last place to drop it. The cost is bytes on a large estate; the alternative is a page // that silently loses the only part with evidence behind it. +// +// BUILDER, THEN TEMPLATE. `agentRequirementsPageData` makes every cell and line; the shared +// template `templates/agent/requirements.md.mustache` lays them out, and every port renders +// it from the same data (`fixtures/docs-page-conformance/`). The embedded ledger is the +// `requirements` page's own template rendered in its embedded form, so the two cannot +// disagree. import { REQUIREMENT_ATTR_STATEMENT } from "@metaobjectsdev/metadata"; import type { MetaData } from "@metaobjectsdev/metadata"; +import type { Provider } from "@metaobjectsdev/render"; import { GENERATED_HEADER } from "../constants.js"; import { concernOf, walkRequirements } from "../requirement-walk.js"; +import { frameworkTemplatesProvider } from "../render-engine/framework-provider.js"; +import { renderDocPage } from "../render-engine/doc-page.js"; import { requirementRows } from "./requirements-view.js"; import { renderRequirementsMarkdown } from "./requirements-markdown.js"; +/** The shared template of `agent/requirements.md`. */ +export const AGENT_REQUIREMENTS_PAGE_REF = "agent/requirements.md"; + const GENERATED_MARKER = ``; /** @@ -108,98 +120,82 @@ function oneLine(text: string): string { return text.replace(/\s+/g, " ").trim(); } -/** - * Render the page. Returns "" for a model declaring no requirements — the same contract - * `requirementsFile()` keeps, and the only reason a surface that is on by default is a - * no-op for a project without a ledger. - */ -export function renderAgentRequirementsPage( +/** What `agent/requirements.md.mustache` renders. */ +export interface AgentRequirementsPageData { + readonly generatedMarker: string; + /** False when no requirement resolves to a model node: the page says why instead. */ + readonly hasNodeIndex: boolean; + /** One row per claimed node; `claims` is the finished cell (`
`-joined). */ + readonly nodeIndex: readonly { readonly address: string; readonly concern: string; readonly claims: string }[]; + readonly hasStatements: boolean; + /** One line per stated requirement in the index, sorted by path; `statement` is one line, `|` escaped. */ + readonly statements: readonly { readonly path: string; readonly subType: string; readonly statement: string }[]; + /** The ledger, rendered by the `requirements` template in its embedded form, with no + * trailing line break (the template supplies the page's last one). */ + readonly ledger: string; +} + +/** The data the agent requirements template renders. Undefined for a model declaring no + * requirements, which gets no page. */ +export function agentRequirementsPageData( root: MetaData, inLedger?: (fqn: string) => boolean, -): string { + provider?: Provider, +): AgentRequirementsPageData | undefined { const rows = requirementRows(root, inLedger); - if (rows.length === 0) return ""; + if (rows.length === 0) return undefined; const index = buildNodeIndex(root, inLedger); - const out: string[] = []; - out.push(GENERATED_MARKER); - out.push(""); - out.push("# Requirements"); - out.push(""); - out.push( - "Read this before adding a capability, and before extending anything that looks like " + - "it already does what you were asked for.", - ); - out.push(""); - out.push( - "- A requirement is **prescriptive**: it states what should be true, never what " + - "happened. `status: retired` means the capability was BUILT and deliberately " + - "REMOVED — that entry is a prohibition, not history, and the right response to it " + - "is to stop, not to rebuild.", - ); - out.push( - "- The **node index** below answers *\"does anything claim the thing I am about to " + - "change?\"*. Match the literal FQN.", - ); - out.push( - "- **The ledger under it is not the same list.** A retired capability carries no " + - "`@implementedBy` — there is nothing left to point at — so it appears there and " + - "in no index. Read it before you conclude a capability does not exist yet.", - ); - out.push(""); - - if (index.length > 0) { - out.push("## Node index"); - out.push(""); - out.push("| Node | Kind | Claimed by |"); - out.push("|---|---|---|"); - for (const entry of index) { - const claims = entry.claims + // The statements ride below the table: they are prose, they repeat across nodes a + // shared architectural entry claims, and putting one in a cell forces the table wide. + const stated = new Map(); + for (const entry of index) { + for (const c of entry.claims) { + if (c.statement !== undefined) stated.set(c.path, { subType: c.subType, statement: c.statement }); + } + } + const statements = [...stated.entries()] + .sort((a, b) => a[0].localeCompare(b[0])) + .map(([path, { subType, statement }]) => ({ path, subType, statement: mdCell(oneLine(statement)) })); + return { + generatedMarker: GENERATED_MARKER, + hasNodeIndex: index.length > 0, + nodeIndex: index.map((entry) => ({ + address: entry.address, + concern: entry.concern, + claims: entry.claims .map((c) => { const level = c.level === undefined ? "" : ` L${c.level}`; const status = c.status === undefined ? "" : ` (${c.status})`; return `\`${c.path}\`${level}${status}`; }) - .join("
"); - out.push(`| \`${entry.address}\` | \`${entry.concern}\` | ${claims} |`); - } - out.push(""); - // The statements ride below the table: they are prose, they repeat across nodes a - // shared architectural entry claims, and putting one in a cell forces the table wide. - const stated = new Map(); - for (const entry of index) { - for (const c of entry.claims) { - if (c.statement !== undefined) stated.set(c.path, { subType: c.subType, statement: c.statement }); - } - } - if (stated.size > 0) { - out.push("### What those requirements say"); - out.push(""); - for (const [path, { subType, statement }] of [...stated.entries()].sort((a, b) => a[0].localeCompare(b[0]))) { - out.push(`- \`${path}\` (\`${subType}\`) — ${mdCell(oneLine(statement))}`); - } - out.push(""); - } - } else { - out.push("## Node index"); - out.push(""); - out.push( - "No requirement resolves to a model node. The common reason is the ordinary one: an " + - "entry at L4 or L5 that simply declares no `@implementedBy` yet, which is legal " + - "and is what a `planned` entry looks like. The others are an entry sitting ABOVE " + - "the L4 link floor (where a claim is not permitted), a `retired` entry (where it " + - "is forbidden outright), and a claim that names a node nothing resolves — " + - "`meta verify` is what says which.", - ); - out.push(""); - } - - out.push("## The ledger"); - out.push(""); - // The SAME renderer the `requirements` surface uses. A second rendering of the ledger - // would be a second thing to keep true. `embedded` drops its own H1 and demotes every - // heading one level, so the entries nest under this section instead of escaping it. - out.push(renderRequirementsMarkdown(rows, { embedded: true }).replace(/\n+$/, "")); + .join("
"), + })), + hasStatements: statements.length > 0, + statements, + // The SAME template the `requirements` surface uses. A second rendering of the ledger + // would be a second thing to keep true. `embedded` drops its own H1 and demotes every + // heading one level, so the entries nest under this section instead of escaping it. + ledger: renderRequirementsMarkdown(rows, { embedded: true, ...(provider !== undefined && { provider }) }).replace(/\n+$/, ""), + }; +} - return `${out.join("\n").replace(/\n+$/, "")}\n`; +/** + * Render the page. Returns "" for a model declaring no requirements — the same contract + * `requirementsFile()` keeps, and the only reason a surface that is on by default is a + * no-op for a project without a ledger. + */ +export function renderAgentRequirementsPage( + root: MetaData, + inLedger?: (fqn: string) => boolean, + provider?: Provider, +): string { + const data = agentRequirementsPageData(root, inLedger, provider); + if (data === undefined) return ""; + return renderDocPage( + AGENT_REQUIREMENTS_PAGE_REF, + data, + provider ?? frameworkTemplatesProvider, + "agent/requirements.md", + ); } diff --git a/server/typescript/packages/codegen-ts/src/generators/agent-schema-page.ts b/server/typescript/packages/codegen-ts/src/generators/agent-schema-page.ts index fbe5fb2d5c..fbf7e96b2e 100644 --- a/server/typescript/packages/codegen-ts/src/generators/agent-schema-page.ts +++ b/server/typescript/packages/codegen-ts/src/generators/agent-schema-page.ts @@ -19,9 +19,47 @@ // is excluded — all rules `buildExpectedSchema`'s Pass 1 already owns. Walking entities // here would mean re-implementing those skip rules and drifting from them. The declaring // object is named per table from the provenance map instead. +// +// BUILDER, THEN TEMPLATE. `agentSchemaPageData` makes every cell and line; the shared +// template `templates/agent/schema.md.mustache` lays them out, and every port renders it +// from the same data (`fixtures/docs-page-conformance/`). `physical: false` is the page a +// port without the expected schema writes (design call 17): no SQL type column, no +// indexes, no checks — the dialect-only facts. Everything else is derivable from the model. -import { GENERATION_INCREMENT, GENERATION_UUID } from "@metaobjectsdev/metadata"; +import { + CARDINALITY_MANY, + CARDINALITY_ONE, + FIELD_SUBTYPE_ENUM, + GENERATION_INCREMENT, + GENERATION_UUID, + ORIGIN_AGGREGATE_ATTR_AGG, + ORIGIN_AGGREGATE_ATTR_OF, + ORIGIN_AGGREGATE_ATTR_VIA, + ORIGIN_ATTR_ORDER_BY, + ORIGIN_PASSTHROUGH_ATTR_FROM, + ORIGIN_PASSTHROUGH_ATTR_VIA, + ORIGIN_SUBTYPE_AGGREGATE, + ORIGIN_SUBTYPE_COMPUTED, + ORIGIN_SUBTYPE_FIRST, + ORIGIN_SUBTYPE_PASSTHROUGH, + PHYSICAL_NAME_ATTR_BY_KIND, + RELATIONSHIP_ATTR_CARDINALITY, + RELATIONSHIP_ATTR_OBJECT_REF, + RELATIONSHIP_ATTR_ON_DELETE, + RELATIONSHIP_ATTR_THROUGH, + SOURCE_ROLE_PRIMARY, + TYPE_ORIGIN, + resolveColumnName, +} from "@metaobjectsdev/metadata"; +import type { ColumnNamingStrategy, MetaField, MetaObject, MetaRoot } from "@metaobjectsdev/metadata"; +import type { Provider } from "@metaobjectsdev/render"; import { GENERATED_HEADER } from "../constants.js"; +import { enumValues, intValueMapOf } from "../enum-meta.js"; +import { isAbstract } from "../instance-artifacts.js"; +import { resolveObjectNames } from "../names.js"; +import { frameworkTemplatesProvider } from "../render-engine/framework-provider.js"; +import { renderDocPage } from "../render-engine/doc-page.js"; +import { isReport } from "../source-detect.js"; import type { AgentSchemaInput, SchemaColumnLike, @@ -30,6 +68,9 @@ import type { SchemaTableLike, } from "./agent-schema-input.js"; +/** The shared template of `agent/schema.md`. */ +export const AGENT_SCHEMA_PAGE_REF = "agent/schema.md"; + const GENERATED_MARKER = ``; /** Markdown-escape a cell whose text may contain a `|` (a CHECK expression can). */ @@ -56,14 +97,15 @@ function cols(list: readonly string[]): string { * than one row. The Indexes section below carries the full key; this cell only has to stop * being wrong about it. */ -function keyCell(table: SchemaTableLike, column: SchemaColumnLike): string { +function keyCell(table: SchemaTableLike, column: SchemaColumnLike, physical: boolean): string { const roles: string[] = []; if (table.primaryKey.includes(column.name)) { roles.push(table.primaryKey.length > 1 ? "PK (composite)" : "PK"); } const fk = table.foreignKeys.find((f) => f.columns.includes(column.name)); if (fk !== undefined) roles.push(`FK → \`${fk.refTable}\``); - const covering = table.indexes.filter((i) => i.columns.includes(column.name)); + // An index is a dialect fact: a model-only page states the keys the model declares. + const covering = physical ? table.indexes.filter((i) => i.columns.includes(column.name)) : []; const unique = covering.find((i) => i.unique); const index = unique ?? covering[0]; if (index !== undefined) { @@ -99,130 +141,347 @@ function indexLine(ix: SchemaIndexLike): string { const parts = [`\`${ix.name}\``, ix.unique ? "unique" : "index", `on ${key}`]; if (ix.using !== undefined && ix.using !== "" && ix.using !== "btree") parts.push(`using \`${ix.using}\``); if (ix.where !== undefined && ix.where !== "") parts.push(`where \`${mdCell(ix.where)}\``); - return `- ${parts.join(" · ")}`; + return parts.join(" · "); } -function fkLine(fk: SchemaFkLike): string { - const parts = [ - `\`${fk.name}\``, - `${cols(fk.columns)} → \`${fk.refTable}\`(${cols(fk.refColumns)})`, - ]; +/** + * A model-only page states the key alone. The constraint NAME comes from the schema + * conventions and the referential ACTIONS from the expected schema's resolution ladder (the + * reference, then its relationship, then the reverse one, then the subtype's default), and + * only the expected schema applies either. The Relationships section carries the actions the + * model authored. + */ +function fkLine(fk: SchemaFkLike, physical: boolean): string { + const key = `${cols(fk.columns)} → \`${fk.refTable}\`(${cols(fk.refColumns)})`; + if (!physical) return key; + const parts = [`\`${fk.name}\``, key]; if (fk.onDelete !== undefined && fk.onDelete !== "") parts.push(`on delete \`${fk.onDelete}\``); if (fk.onUpdate !== undefined && fk.onUpdate !== "") parts.push(`on update \`${fk.onUpdate}\``); - return `- ${parts.join(" · ")}`; + return parts.join(" · "); +} + +/** One `origin.*` child rendered as a lineage phrase. `origin.*` NEVER inherits, so the + * own-accessor read here is the correct one rather than an ADR-0039 slip. */ +function lineageOf(field: MetaField): string | undefined { + const origin = field.ownChildren().find((c) => c.type === TYPE_ORIGIN); + if (origin === undefined) return undefined; + // Human-facing text: references print as the author wrote them (ADR-0059). + const str = (name: string): string | undefined => { + const v = origin.authoredAttr(name); + return typeof v === "string" && v !== "" ? v : undefined; + }; + switch (origin.subType) { + case ORIGIN_SUBTYPE_PASSTHROUGH: { + const from = str(ORIGIN_PASSTHROUGH_ATTR_FROM); + const via = str(ORIGIN_PASSTHROUGH_ATTR_VIA); + return `passthrough from \`${from ?? "?"}\`${via === undefined ? "" : ` via \`${via}\``}`; + } + case ORIGIN_SUBTYPE_AGGREGATE: { + const agg = str(ORIGIN_AGGREGATE_ATTR_AGG) ?? "?"; + const of = str(ORIGIN_AGGREGATE_ATTR_OF); + const via = str(ORIGIN_AGGREGATE_ATTR_VIA); + return `\`${agg}\`${of === undefined ? "" : ` of \`${of}\``}${via === undefined ? "" : ` via \`${via}\``}`; + } + case ORIGIN_SUBTYPE_FIRST: { + const of = str(ORIGIN_AGGREGATE_ATTR_OF); + const via = str(ORIGIN_AGGREGATE_ATTR_VIA); + const order = str(ORIGIN_ATTR_ORDER_BY); + return `first${of === undefined ? "" : ` \`${of}\``}${via === undefined ? "" : ` via \`${via}\``}` + + `${order === undefined ? "" : ` ordered by \`${order}\``}`; + } + case ORIGIN_SUBTYPE_COMPUTED: + // The @expr tree is structured; naming it is enough to route a reader to the + // declaration, and rendering a tree into a cell would be a second SQL lowering. + return "computed from a declared `@expr`"; + default: + return `\`origin.${origin.subType}\``; + } +} + +/** + * The cardinality phrase, from the DECLARING object's side. + * + * `@cardinality: one` does NOT mean one-to-one. It means this object holds the foreign + * key — many rows of it point at one target row — which is what `relation-resolver.ts` + * builds a belongs-to `one()` relation from. Rendering it as "one-to-one" told a reader + * the target row is claimed by at most one row here, which is the direction that makes + * someone write a lookup expecting a single result. + * + * `@cardinality` is OPTIONAL vocabulary (min 0), and ABSENT is its own answer: no + * navigation is generated at all. Folding that into "one-to-one" invented a shape the + * model never declared. + */ +function cardinalityPhrase(cardinality: unknown, through: unknown): string { + if (cardinality === CARDINALITY_MANY) { + return typeof through === "string" && through !== "" ? "many-to-many" : "one-to-many"; + } + if (cardinality === CARDINALITY_ONE) return "many-to-one"; + return "cardinality not declared"; +} + +/** `\`Order.lines\` · \`association\` · one-to-many → \`OrderLine\``: one line each, no bullet. */ +function relationshipLines(objects: readonly MetaObject[]): string[] { + const out: string[] = []; + for (const obj of objects) { + for (const rel of obj.relationships()) { + const cardinality = rel.attr(RELATIONSHIP_ATTR_CARDINALITY); + // References print as the author wrote them (ADR-0059); the loaded value is canonical. + const target = rel.authoredAttr(RELATIONSHIP_ATTR_OBJECT_REF); + const through = rel.authoredAttr(RELATIONSHIP_ATTR_THROUGH); + const onDelete = rel.attr(RELATIONSHIP_ATTR_ON_DELETE); + // The FQN, not the short name: this line is an ADDRESS a reader searches for. + const parts = [`\`${obj.resolutionKey()}.${rel.name}\``, `\`${rel.subType}\``]; + parts.push( + `${cardinalityPhrase(cardinality, through)} → \`${String(target ?? "?")}\``, + ); + if (typeof through === "string" && through !== "") parts.push(`through \`${through}\``); + if (typeof onDelete === "string" && onDelete !== "") parts.push(`on delete \`${onDelete}\``); + out.push(parts.join(" · ")); + } + } + return out; } /** - * One table's section: the declaring object, its description, the column table, then - * whichever of indexes / foreign keys / checks the table actually has. + * One enum row: `Order.status`, its members, its storage. + * + * `objects` IS ONLY THE TABLE-BACKED SUBSET OF THE MODEL — the caller scopes it to the + * objects the snapshot actually holds as tables. This section sits on the SCHEMA page, so + * every row it prints is read as a statement about a column. Walking every loaded object + * printed rows for abstract bases, for `object.value`s that have no column anywhere, and + * for projections whose "column" is a view expression — three kinds of thing the physical + * schema does not contain. * - * `declaredBy` maps a physical column name back to the FIELD that declared it — the - * mapping an agent needs to go from a query it is reading to the metadata it must edit, - * and the one thing the snapshot alone cannot supply. + * It also says nothing about a `CHECK`. Whether the database constrains the members is + * `table.checks`, which is already on this page from the snapshot, and an `@isArray` + * enum deliberately gets none (`migrate-ts` skips it) — so asserting one here was a + * SECOND derivation of a fact the page already carries correctly, in the direction that + * promises the database will refuse a value it will accept. */ -function tableSection( +function enumRows(objects: readonly MetaObject[]): AgentSchemaEnumRow[] { + const rows: AgentSchemaEnumRow[] = []; + for (const obj of objects) { + for (const field of obj.fields()) { + if (field.subType !== FIELD_SUBTYPE_ENUM) continue; + const members = enumValues(field); + if (members === undefined || members.length === 0) continue; + const intMap = intValueMapOf(field); + const storage = + intMap === undefined + ? "string-backed" + : `int-backed (${members.map((m) => `${m}=${intMap[m]}`).join(", ")})`; + rows.push({ + field: `${obj.resolutionKey()}.${field.name}`, + members: members.map((m) => `\`${m}\``).join(", "), + storage, + }); + } + } + return rows; +} + +/** One column row of a table, every cell finished. `sqlTypeCell` and `defaultCell` are "" + * on a model-only page, which has neither column. */ +export interface AgentSchemaColumnRow { + readonly name: string; + readonly fieldCell: string; + readonly declaredCell: string; + readonly sqlTypeCell: string; + readonly nullCell: string; + readonly defaultCell: string; + readonly keyCell: string; +} + +export interface AgentSchemaTable { + /** The qualified name in backticks: `` `schema.name` `` or `` `name` ``. */ + readonly heading: string; + readonly tableDeclaredBy?: string; + readonly tableDescription?: string; + readonly columns: readonly AgentSchemaColumnRow[]; + readonly hasDescribed: boolean; + readonly described: readonly { readonly name: string; readonly text: string }[]; + readonly hasIndexes: boolean; + readonly indexes: readonly string[]; + readonly hasForeignKeys: boolean; + readonly foreignKeys: readonly string[]; + readonly hasChecks: boolean; + readonly checks: readonly string[]; +} + +export interface AgentSchemaView { + readonly heading: string; + readonly viewDeclaredBy?: string; + readonly hasLineage: boolean; + readonly lineage: readonly { readonly column: string; readonly text: string }[]; +} + +export interface AgentSchemaEnumRow { + /** `pkg::Order.status` — the address a reader searches for. */ + readonly field: string; + readonly members: string; + readonly storage: string; +} + +/** What `agent/schema.md.mustache` renders. */ +export interface AgentSchemaPageData { + readonly generatedMarker: string; + /** True when the page carries the dialect facts: SQL types, indexes, checks. */ + readonly physical: boolean; + /** The dialect a physical page names; `""` on a model-only page. */ + readonly dialect: string; + readonly descriptionNudge: boolean; + readonly hasTables: boolean; + readonly tables: readonly AgentSchemaTable[]; + readonly hasViews: boolean; + /** True when a view-backed `object.report` owns one of the views: the intro names reports too. */ + readonly hasReportView: boolean; + readonly views: readonly AgentSchemaView[]; + readonly hasRelationships: boolean; + readonly relationships: readonly string[]; + readonly hasEnums: boolean; + readonly enums: readonly AgentSchemaEnumRow[]; +} + +/** + * What the model contributes to the page: per qualified table or view name, the column → + * declaring-field map and the view lineage; the qualified names report views own; and the + * relationship and enum rows. + */ +interface ModelFacts { + readonly declaredBy: ReadonlyMap>; + readonly viewLineage: ReadonlyMap; + readonly reportViews: ReadonlySet; + readonly relationships: readonly string[]; + readonly enums: readonly AgentSchemaEnumRow[]; +} + +function modelFacts(root: MetaRoot, schema: AgentSchemaInput, columnNamingStrategy: ColumnNamingStrategy): ModelFacts { + const objects = root.objects(); + // The qualified names the snapshot actually holds. An object whose physical name is not + // one of these contributes nothing to the physical schema (an abstract base, a sourceless + // value, an `@unmanaged` object) and must not appear on a page describing it — + // `buildExpectedSchema`'s Pass 1 owns those skip rules and this reads its answer rather + // than re-deriving them. + const tableNames = new Set(schema.tables.map((t) => schema.qualify(t))); + const viewNames = new Set(schema.views.map((v) => schema.qualify(v))); + // The objects backed by a TABLE in the snapshot — the enum section's scope, since a row + // there is read as a statement about a column. + const tableBacked: MetaObject[] = []; + // column → declaring field, per qualified table name. `resolveObjectNames` is the ONE + // field→column resolver — the same one the names artifact and the DDL use — so this + // mapping cannot disagree with the column it labels. + const declaredBy = new Map>(); + const viewLineage = new Map(); + // Qualified names of the views a view-backed object.report owns (FR-044). Empty for a + // model with no report, so the page is byte-identical to what it was before reports. + const reportViews = new Set(); + for (const obj of objects) { + const names = resolveObjectNames(obj, columnNamingStrategy); + // The PRIMARY source's physical name and schema — `names.name` is the object's + // metamodel name since 0.25.0, which would match nothing in the snapshot. + const primary = names?.sources[SOURCE_ROLE_PRIMARY]; + const physical = primary === undefined + ? undefined + : primary[(PHYSICAL_NAME_ATTR_BY_KIND.get(primary.kind) ?? "") as keyof typeof primary]; + if (typeof physical !== "string") continue; + const key = schema.qualify({ name: physical, schema: primary?.schema }); + const isTable = tableNames.has(key); + if (!isTable && !viewNames.has(key)) continue; + // ABSTRACT BASES ARE EXCLUDED, and being in the snapshot does not exempt them: an + // abstract base that declares the `source.rdb` its concrete child inherits resolves to + // that child's table, so the qualified-name test admits it and the page printed the + // base's enum a second time under a different owner. `buildExpectedSchema`'s Pass 1 + // skips abstracts; this reads the same rule. + if (isTable && !isAbstract(obj)) tableBacked.push(obj); + if (!isTable && isReport(obj)) reportViews.add(key); + let map = declaredBy.get(key); + if (map === undefined) { + map = new Map(); + declaredBy.set(key, map); + } + const lineage: { column: string; text: string }[] = []; + for (const field of obj.fields()) { + const column = resolveColumnName(field, columnNamingStrategy); + // A TPH base and its subtypes share one table: first writer wins, so the base's own + // column keeps its label rather than being relabelled by whichever subtype was + // walked last. + if (!map.has(column)) { + map.set(column, { field: field.name, type: `${field.type}.${field.subType}` }); + } + const text = lineageOf(field); + if (text !== undefined) lineage.push({ column, text }); + } + if (lineage.length > 0) viewLineage.set(key, lineage); + } + return { declaredBy, viewLineage, reportViews, relationships: relationshipLines(objects), enums: enumRows(tableBacked) }; +} + +function tableOf( table: SchemaTableLike, input: AgentSchemaInput, + physical: boolean, fqn: string | undefined, declaredBy: ReadonlyMap, -): string[] { - const out: string[] = []; - const qualified = table.schema === undefined ? `\`${table.name}\`` : `\`${table.schema}.${table.name}\``; - out.push(`### ${qualified}`); - out.push(""); - if (fqn !== undefined) out.push(`Declared by \`${fqn}\`.`); - if (table.description !== undefined && table.description !== "") { - out.push(""); - out.push(`> ${oneLine(table.description)}`); - } - out.push(""); - out.push("| Column | Field | Declared | SQL type | Null | Default | Key |"); - out.push("|---|---|---|---|---|---|---|"); - for (const c of table.columns) { - const declared = declaredBy.get(c.name); - out.push( - `| \`${c.name}\` | ${declared === undefined ? "" : `\`${declared.field}\``} | ` + - `${declared === undefined ? "" : `\`${declared.type}\``} | \`${mdCell(input.columnType(c))}\` | ` + - `${c.nullable ? "yes" : "no"} | ${defaultCell(c)} | ${keyCell(table, c)} |`, - ); - } - // Column descriptions ride BELOW the table rather than as an eighth cell: a sentence - // in a cell forces the whole table wide, and most columns have none. +): AgentSchemaTable { const described = table.columns.filter((c) => c.description !== undefined && c.description !== ""); - if (described.length > 0) { - out.push(""); - for (const c of described) out.push(`- \`${c.name}\` — ${oneLine(c.description ?? "")}`); - } - if (table.indexes.length > 0) { - out.push(""); - out.push("**Indexes**"); - out.push(""); - for (const ix of table.indexes) out.push(indexLine(ix)); - } - if (table.foreignKeys.length > 0) { - out.push(""); - out.push("**Foreign keys**"); - out.push(""); - for (const fk of table.foreignKeys) out.push(fkLine(fk)); - } - if (table.checks.length > 0) { - out.push(""); - out.push("**Checks**"); - out.push(""); - for (const ck of table.checks) out.push(`- \`${ck.name}\` — \`${mdCell(ck.expression)}\``); - } - out.push(""); - return out; + // The dialect facts. A model-only page omits them: the expected schema is what knows them. + const indexes = physical ? table.indexes.map(indexLine) : []; + const checks = physical ? table.checks.map((ck) => `\`${ck.name}\` — \`${mdCell(ck.expression)}\``) : []; + const foreignKeys = table.foreignKeys.map((fk) => fkLine(fk, physical)); + return { + heading: table.schema === undefined ? `\`${table.name}\`` : `\`${table.schema}.${table.name}\``, + ...(fqn !== undefined && { tableDeclaredBy: fqn }), + ...(table.description !== undefined && table.description !== "" && { tableDescription: oneLine(table.description) }), + // `declaredBy` maps a physical column name back to the FIELD that declared it — the + // mapping an agent needs to go from a query it is reading to the metadata it must edit, + // and the one thing the snapshot alone cannot supply. + columns: table.columns.map((c) => { + const declared = declaredBy.get(c.name); + return { + name: c.name, + fieldCell: declared === undefined ? "" : `\`${declared.field}\``, + declaredCell: declared === undefined ? "" : `\`${declared.type}\``, + sqlTypeCell: physical ? `\`${mdCell(input.columnType(c))}\`` : "", + nullCell: c.nullable ? "yes" : "no", + // A default is written in the dialect's SQL spelling: a dialect fact. + defaultCell: physical ? defaultCell(c) : "", + keyCell: keyCell(table, c, physical), + }; + }), + // Column descriptions ride BELOW the table rather than as an eighth cell: a sentence + // in a cell forces the whole table wide, and most columns have none. + hasDescribed: described.length > 0, + described: described.map((c) => ({ name: c.name, text: oneLine(c.description ?? "") })), + hasIndexes: indexes.length > 0, + indexes, + hasForeignKeys: foreignKeys.length > 0, + foreignKeys, + hasChecks: checks.length > 0, + checks, + }; } export interface AgentSchemaPageOptions { - /** Column → declaring field, per QUALIFIED table name. Supplied by the generator, which - * holds the loaded model; see `agentDocsFile`. */ - readonly declaredBy: ReadonlyMap>; - /** Per-projection lineage lines, keyed by QUALIFIED view name. */ - readonly viewLineage: ReadonlyMap; - /** QUALIFIED names of the views owned by a view-backed `object.report`. Omitted or empty - * means no report view is on the page, and the Views intro keeps its pre-report wording. */ - readonly reportViews?: ReadonlySet; - /** Relationship lines, already rendered from the model. */ - readonly relationships: readonly string[]; - /** Enum lines, already rendered from the model. */ - readonly enums: readonly string[]; + /** False writes the model-only page: no SQL type or default column, no indexes (in the + * Key column too), no checks, no constraint names, no referential actions. Default true. */ + readonly physical?: boolean; + /** Where the template is resolved. Default: the package's own templates. */ + readonly provider?: Provider; } /** - * Render the whole page. Returns "" when there is no physical schema at all, which is - * what lets the surface emit no FILE rather than a page describing nothing. + * The data the schema template renders. Undefined when there is no physical schema at all, + * which is what lets the surface emit no FILE rather than a page describing nothing. */ -export function renderAgentSchemaPage( +export function agentSchemaPageData( + root: MetaRoot, input: AgentSchemaInput, - opts: AgentSchemaPageOptions, -): string { - if (input.tables.length === 0 && input.views.length === 0) return ""; - - const out: string[] = []; - out.push(GENERATED_MARKER); - out.push(""); - out.push("# Schema"); - out.push(""); - out.push( - `The physical shape of the \`${input.dialect}\` database this model generates. ` + - "Read it before writing a query, a migration, or anything that names a table or a column.", - ); - out.push(""); - out.push( - "- The **DDL is not repeated here.** The migration files are the DDL, they are " + - "generated, and they are what runs — this page describes the schema they produce.", - ); - out.push( - "- Change the schema by changing the **metadata** and running `meta migrate`. Never " + - "hand-apply SQL to a live database: it drifts from the migration history and " + - "collides at the next migrate.", - ); - out.push( - "- `Field` and `Declared` are the METADATA names. Edit those; the column name follows.", - ); - out.push(""); + columnNamingStrategy: ColumnNamingStrategy, + opts?: { readonly physical?: boolean }, +): AgentSchemaPageData | undefined { + if (input.tables.length === 0 && input.views.length === 0) return undefined; + const physical = opts?.physical !== false; + const facts = modelFacts(root, input, columnNamingStrategy); // The semantics nudge. A schema page carrying business meaning beside the columns is // worth more to a reader working from it than any format choice this page could make — @@ -230,89 +489,59 @@ export function renderAgentSchemaPage( // snapshot already threads here to emit `COMMENT ON`. A model declaring none renders a // page of names with nothing to disambiguate them, and says so, because silently // omitting the highest-value content teaches an adopter that it does not exist. - const anyDescription = - input.tables.some( - (t) => - (t.description !== undefined && t.description !== "") || - t.columns.some((c) => c.description !== undefined && c.description !== ""), - ); - if (!anyDescription && input.tables.length > 0) { - out.push( - "> **Nothing in this model declares a `description`.** The tables and columns below " + - "are named but not explained. Adding `description` to an entity or a field is the " + - "single highest-value change to this page: it is what tells a reader *which* of " + - "two plausible columns to use, and it is the same text `meta migrate` emits as a " + - "`COMMENT ON`, so it lands in the database too.", - ); - out.push(""); - } - - if (input.tables.length > 0) { - out.push("## Tables"); - out.push(""); - for (const table of [...input.tables].sort((a, b) => a.name.localeCompare(b.name))) { + const anyDescription = input.tables.some( + (t) => + (t.description !== undefined && t.description !== "") || + t.columns.some((c) => c.description !== undefined && c.description !== ""), + ); + const tables = [...input.tables] + .sort((a, b) => a.name.localeCompare(b.name)) + .map((table) => { const key = input.qualify(table); - out.push( - ...tableSection( - table, - input, - input.provenance.get(key), - opts.declaredBy.get(key) ?? new Map(), - ), - ); - } - } - - if (input.views.length > 0) { - out.push("## Views"); - out.push(""); - // A model with no report view must render exactly what it rendered before FR-044 - // (no-churn: `meta verify --codegen` would flag drift after an upgrade otherwise). - const hasReportView = input.views.some((v) => opts.reportViews?.has(input.qualify(v)) === true); - out.push( - (hasReportView - ? "A view is generated from its projection's `origin.*` children or its report's dimensions and measures — it is derived, " - : "A view is generated from its projection's `origin.*` children — it is derived, ") + - "never hand-written. Editing the view SQL directly is drift the tool cannot see.", - ); - out.push(""); - for (const view of [...input.views].sort((a, b) => a.name.localeCompare(b.name))) { + return tableOf(table, input, physical, input.provenance.get(key), facts.declaredBy.get(key) ?? new Map()); + }); + const views = [...input.views] + .sort((a, b) => a.name.localeCompare(b.name)) + .map((view): AgentSchemaView => { const key = input.qualify(view); - const qualified = view.schema === undefined ? `\`${view.name}\`` : `\`${view.schema}.${view.name}\``; - out.push(`### ${qualified}`); - out.push(""); const fqn = input.provenance.get(key); - if (fqn !== undefined) out.push(`Declared by \`${fqn}\`.`); - const lineage = opts.viewLineage.get(key) ?? []; - if (lineage.length > 0) { - out.push(""); - out.push("| Column | Lineage |"); - out.push("|---|---|"); - out.push(...lineage); - } - out.push(""); - } - } - - if (opts.relationships.length > 0) { - out.push("## Relationships"); - out.push(""); - out.push(...opts.relationships); - out.push(""); - } - - if (opts.enums.length > 0) { - out.push("## Enums"); - out.push(""); - out.push( - "Members are the values the wire and the generated types use. Whether the DATABASE " + - "also refuses a value outside the set is that table's **Checks** above — an " + - "`@isArray` enum carries none, and neither does a view column.", - ); - out.push(""); - out.push(...opts.enums); - out.push(""); - } + const lineage = facts.viewLineage.get(key) ?? []; + return { + heading: view.schema === undefined ? `\`${view.name}\`` : `\`${view.schema}.${view.name}\``, + ...(fqn !== undefined && { viewDeclaredBy: fqn }), + hasLineage: lineage.length > 0, + lineage, + }; + }); + return { + generatedMarker: GENERATED_MARKER, + physical, + dialect: physical ? input.dialect : "", + descriptionNudge: !anyDescription && input.tables.length > 0, + hasTables: tables.length > 0, + tables, + hasViews: views.length > 0, + // A model with no report view must render exactly what it rendered before FR-044 + // (no-churn: `meta verify --codegen` would flag drift after an upgrade otherwise). + hasReportView: input.views.some((v) => facts.reportViews.has(input.qualify(v))), + views, + hasRelationships: facts.relationships.length > 0, + relationships: facts.relationships, + hasEnums: facts.enums.length > 0, + enums: facts.enums, + }; +} - return `${out.join("\n").replace(/\n+$/, "")}\n`; +/** Render the whole page; "" when there is no physical schema at all. */ +export function renderAgentSchemaPage( + root: MetaRoot, + input: AgentSchemaInput, + columnNamingStrategy: ColumnNamingStrategy, + opts?: AgentSchemaPageOptions, +): string { + const data = agentSchemaPageData(root, input, columnNamingStrategy, opts); + if (data === undefined) return ""; + const page = renderDocPage(AGENT_SCHEMA_PAGE_REF, data, opts?.provider ?? frameworkTemplatesProvider, "agent/schema.md"); + // A page ends on exactly one line break, whichever section came last. + return `${page.replace(/\n+$/, "")}\n`; } diff --git a/server/typescript/packages/codegen-ts/src/generators/docs-site-file.ts b/server/typescript/packages/codegen-ts/src/generators/docs-site-file.ts index 4bf117cb2c..b5b8153fe1 100644 --- a/server/typescript/packages/codegen-ts/src/generators/docs-site-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/docs-site-file.ts @@ -20,8 +20,7 @@ // diagrams. It loads the model with its own loader, from whole source DIRECTORIES // (one page group each), so it reads the collection's source roots off the context. -import { mkdtempSync, readFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync } from "node:fs"; import { basename, join, resolve } from "node:path"; import { existsSync } from "node:fs"; import { canonicalSerializeEffective } from "@metaobjectsdev/metadata"; @@ -35,6 +34,7 @@ import { import type { EmittedFile, GenContext, Generator, GeneratorFactory } from "../generator.js"; import { DOCS_TARGET_NAME } from "../docs-run.js"; import { buildApiModelForRun } from "./api-model.js"; +import { makeScratchDir, removeTree } from "../scratch-dir.js"; /** The site lands here, under the target. */ const DEFAULT_SITE_DIR = "site"; @@ -152,12 +152,12 @@ function ownedSiteDirs(project: string): { templatesDir?: string; assetsDir?: st * in a scratch directory and returned as files for the runner to write. `build` returns the * page paths it wrote, relative to that directory. */ async function buildInScratch(prefix: string, build: (outDir: string) => string[] | Promise): Promise { - const scratch = mkdtempSync(join(tmpdir(), "meta-docs-site-")); + const scratch = makeScratchDir("meta-docs-site-"); try { const paths = await build(scratch); return paths.map((path) => ({ path: `${prefix}${path}`, content: readFileSync(join(scratch, path), "utf8") })); } finally { - rmSync(scratch, { recursive: true, force: true }); + removeTree(scratch); } } diff --git a/server/typescript/packages/codegen-ts/src/generators/requirements-file.ts b/server/typescript/packages/codegen-ts/src/generators/requirements-file.ts index f2255dfebb..6843d0366d 100644 --- a/server/typescript/packages/codegen-ts/src/generators/requirements-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/requirements-file.ts @@ -7,7 +7,8 @@ // METADATA ALONE. This generator reads `ctx.loadedRoot` and NOTHING else — no filesystem // walk, no config read, no test-source scan. That sentence is what rules out reviving the // retired `@verifiedBy` scan here, and it only keeps being true if nobody adds a second -// input. +// input. The one file it may read is a page TEMPLATE (the project's `templates/requirements/` +// override), which shapes the layout and never adds a fact. // // AN EMPTY LEDGER EMITS ZERO FILES, not an empty page, so a project without a ledger that // lists this generator gets nothing rather than a page saying there is nothing. @@ -26,6 +27,7 @@ import { renderRequirementsMarkdown } from "./requirements-markdown.js"; import { renderRequirementsToon } from "./requirements-toon.js"; import { requirementRows } from "./requirements-view.js"; import { DOCS_TARGET_NAME } from "../docs-run.js"; +import { docsTemplateRoot, projectProvider } from "../render-engine/framework-provider.js"; /** The human-facing index. */ const MARKDOWN_FILENAME = "requirements.md"; @@ -37,6 +39,9 @@ export interface RequirementsFileOpts { outDir?: string; /** Named output target. Default `"docs"`, which `targets` must declare. */ target?: string; + /** Directory whose `templates/requirements/requirements.{md,toon}.mustache` override the + * shipped pages, relative to the project. Default: the project's own `templates/`. */ + templates?: string; } export const requirementsFile = function requirementsFile( @@ -54,9 +59,10 @@ export const requirementsFile = function requirementsFile( // "zero FILES", which only this line can provide. if (rows.length === 0) return []; + const provider = projectProvider(docsTemplateRoot(ctx, opts?.templates)); const files: EmittedFile[] = [ - { path: `${dirPrefix}${MARKDOWN_FILENAME}`, content: renderRequirementsMarkdown(rows) }, - { path: `${dirPrefix}${TOON_FILENAME}`, content: renderRequirementsToon(rows) }, + { path: `${dirPrefix}${MARKDOWN_FILENAME}`, content: renderRequirementsMarkdown(rows, { provider }) }, + { path: `${dirPrefix}${TOON_FILENAME}`, content: renderRequirementsToon(rows, provider) }, ]; return files; }), diff --git a/server/typescript/packages/codegen-ts/src/generators/requirements-markdown.ts b/server/typescript/packages/codegen-ts/src/generators/requirements-markdown.ts index d71d1cdaa5..aeba5ea778 100644 --- a/server/typescript/packages/codegen-ts/src/generators/requirements-markdown.ts +++ b/server/typescript/packages/codegen-ts/src/generators/requirements-markdown.ts @@ -16,9 +16,23 @@ // // PROSE LIVES HERE, STRUCTURE LIVES IN THE TOON SIBLING. TOON quotes every comma-bearing // string, so statements and violations dilute it badly. The split is not stylistic. +// +// BUILDER, THEN TEMPLATE. The page is the shared Mustache template +// `templates/requirements/requirements.md.mustache` fed the data `requirementsLedgerData` +// builds; every other port renders the same template from the same data, pinned in +// `fixtures/docs-page-conformance/`. Every decision (heading depth, which title survives, +// the fact bar, the embedded demotion) is made HERE: the template only lays the lines out. +// An adopter changes the page by dropping a same-named template under the project's +// `templates/`. +import type { Provider } from "@metaobjectsdev/render"; +import { frameworkTemplatesProvider } from "../render-engine/framework-provider.js"; +import { renderDocPage } from "../render-engine/doc-page.js"; import type { RequirementRow } from "./requirements-view.js"; +/** The shared template both the `requirements` page and the agent page's ledger render. */ +export const REQUIREMENTS_PAGE_REF = "requirements/requirements.md"; + /** `##` for a root-level requirement, deepening with nesting. `#` is the page title. */ function heading(depth: number): string { return "#".repeat(Math.min(depth + 2, 6)); @@ -90,29 +104,53 @@ function facts(r: RequirementRow): string { return parts.join(" · "); } -function renderOne(r: RequirementRow): string { - const out: string[] = [headingLine(r), "", facts(r), ""]; - - if (r.statement !== undefined) out.push(r.statement, ""); - // The prescriptive pair. A requirement MUST be violable, so the counterexample is not - // decoration — it is what makes the statement checkable, and it reads beside it. - if (r.counterexample !== undefined) out.push(`**Counterexample:** ${r.counterexample}`, ""); - if (r.description !== undefined) out.push(r.description, ""); - - if (r.implementedBy.length > 0) { - out.push(`**Implemented by:** ${r.implementedBy.map((c) => `\`${c}\``).join(", ")}`, ""); - } +/** One ledger entry, every line finished. An absent optional line is an absent key. */ +export interface RequirementsLedgerEntry { + readonly heading: string; + readonly facts: string; + readonly statement?: string; + /** The whole line, `**Counterexample:** …`. */ + readonly counterexample?: string; + readonly description?: string; + /** The whole line, `**Implemented by:** …`. */ + readonly implementedBy?: string; +} - return out.join("\n"); +/** What `requirements/requirements.md.mustache` renders. */ +export interface RequirementsLedgerData { + /** True when the ledger is a section of the agent page: no `# Requirements` title. */ + readonly embedded: boolean; + readonly count: number; + /** `"s"`, or `""` for exactly one entry. */ + readonly plural: string; + readonly entries: readonly RequirementsLedgerEntry[]; } /** - * Render the ledger as one markdown index. - * - * Returns the EMPTY STRING for an empty ledger rather than a headed-but-empty page. - * The generator keys on that to emit no file at all, which is in turn what lets the - * surface default to on without changing output for any project lacking a ledger. + * One extra `#` on every line that starts a heading, capped at h6 exactly as `heading()` + * caps. Applied to each finished LINE of an embedded entry (a statement can hold a line + * that starts with `#`, and it moves down with the rest). */ +function demote(text: string): string { + return text.replace(/^(#{1,6}) /gm, (_m, hashes: string) => `${"#".repeat(Math.min(hashes.length + 1, 6))} `); +} + +function entryOf(r: RequirementRow, embedded: boolean): RequirementsLedgerEntry { + const line = embedded ? demote : (text: string): string => text; + return { + heading: line(headingLine(r)), + facts: line(facts(r)), + ...(r.statement !== undefined && { statement: line(r.statement) }), + // The prescriptive pair. A requirement MUST be violable, so the counterexample is not + // decoration — it is what makes the statement checkable, and it reads beside it. + ...(r.counterexample !== undefined && { counterexample: line(`**Counterexample:** ${r.counterexample}`) }), + ...(r.description !== undefined && { description: line(r.description) }), + ...(r.implementedBy.length > 0 && { + implementedBy: line(`**Implemented by:** ${r.implementedBy.map((c) => `\`${c}\``).join(", ")}`), + }), + }; +} + export interface RequirementsMarkdownOpts { /** * Render the ledger as a SECTION of a larger page rather than as the page. @@ -123,38 +161,45 @@ export interface RequirementsMarkdownOpts { * document silently loses its outline. So the title is dropped and every heading moves * down one level. * - * A POST-HOC REGEX OVER THIS FUNCTION'S OUTPUT would do the same thing and would be the - * wrong shape: heading depth is this renderer's decision (it already caps at h6), and a - * caller rewriting it from outside would have to re-derive that cap and would drift from - * it the next time this file changes. + * The demotion is the BUILDER's, not a regex over the rendered page: heading depth is + * this file's decision (it already caps at h6), and a caller rewriting it from outside + * would have to re-derive that cap and would drift from it the next time this file changes. */ readonly embedded?: boolean; + /** Where the template is resolved. Default: the package's own templates. */ + readonly provider?: Provider; +} + +/** The data the ledger template renders, for a non-empty ledger. */ +export function requirementsLedgerData( + rows: readonly RequirementRow[], + opts?: { readonly embedded?: boolean }, +): RequirementsLedgerData { + const embedded = opts?.embedded === true; + return { + embedded, + count: rows.length, + plural: rows.length === 1 ? "" : "s", + entries: rows.map((r) => entryOf(r, embedded)), + }; } +/** + * Render the ledger as one markdown index. + * + * Returns the EMPTY STRING for an empty ledger rather than a headed-but-empty page. + * The generator keys on that to emit no file at all, which is in turn what lets the + * surface default to on without changing output for any project lacking a ledger. + */ export function renderRequirementsMarkdown( rows: readonly RequirementRow[], opts?: RequirementsMarkdownOpts, ): string { if (rows.length === 0) return ""; - - const body = rows.map(renderOne); - if (opts?.embedded === true) { - return [ - `${rows.length} declared requirement${rows.length === 1 ? "" : "s"}, in declaration order.`, - "", - // One extra `#` on every heading line, capped at h6 exactly as `heading()` caps. - ...body.map((entry) => - entry.replace(/^(#{1,6}) /gm, (_m, hashes: string) => - `${"#".repeat(Math.min(hashes.length + 1, 6))} `, - ), - ), - ].join("\n"); - } - return [ - "# Requirements", - "", - `${rows.length} declared requirement${rows.length === 1 ? "" : "s"}, in declaration order.`, - "", - ...body, - ].join("\n"); + return renderDocPage( + REQUIREMENTS_PAGE_REF, + requirementsLedgerData(rows, opts), + opts?.provider ?? frameworkTemplatesProvider, + "requirements.md", + ); } diff --git a/server/typescript/packages/codegen-ts/src/generators/requirements-toon.ts b/server/typescript/packages/codegen-ts/src/generators/requirements-toon.ts index 47b76bade8..cc5af0a286 100644 --- a/server/typescript/packages/codegen-ts/src/generators/requirements-toon.ts +++ b/server/typescript/packages/codegen-ts/src/generators/requirements-toon.ts @@ -21,21 +21,53 @@ // // `notes` NEVER APPEARS — RequirementRow does not carry it (documentation.json charters // it internal-only). Nothing to strip, by construction. +// +// BUILDER, THEN TEMPLATE, like the markdown sibling: `requirementsToonData` makes every cell +// a finished TOON literal (quoted where TOON requires it) and the shared template +// `templates/requirements/requirements.toon.mustache` lays the header and rows out. Every +// port renders that template from the same data (`fixtures/docs-page-conformance/`). The +// file ends WITHOUT a line break, as a TOON document does. import { encode } from "@toon-format/toon"; +import type { Provider } from "@metaobjectsdev/render"; +import { frameworkTemplatesProvider } from "../render-engine/framework-provider.js"; +import { renderDocPage } from "../render-engine/doc-page.js"; import type { RequirementRow } from "./requirements-view.js"; -/** The row shape the artifact declares. Field ORDER is the wire contract — a reader - * diffing two runs sees a reordering as noise, so it is fixed here rather than left - * to object-literal order elsewhere. */ -interface ToonRow { - readonly path: string; - readonly subType: string; - readonly level: number | string; - readonly status: string; - readonly disposition: string; - readonly claims: string; - readonly statement: string; +/** The shared template of the machine-facing artifact. */ +export const REQUIREMENTS_TOON_REF = "requirements/requirements.toon"; + +/** The row's columns. ORDER is the wire contract — a reader diffing two runs sees a + * reordering as noise, so it is fixed here rather than left to object-literal order. */ +export const REQUIREMENTS_TOON_FIELDS = [ + "path", + "subType", + "level", + "status", + "disposition", + "claims", + "statement", +] as const; + +/** What `requirements/requirements.toon.mustache` renders. */ +export interface RequirementsToonData { + readonly count: number; + /** `{path,subType,…}`: the declared header fields, comma-joined in their braces (a + * Mustache template cannot write a literal brace beside a tag). */ + readonly fields: string; + /** Each row as its finished cells, comma-joined: `a.b,functional,4,"",…`. */ + readonly rows: readonly { readonly line: string }[]; +} + +/** + * One cell as TOON writes it inside a comma-delimited row: a number bare, a string bare + * when it is safe and quoted (with TOON's escapes) when it is not — empty, padded, numeric- + * or literal-looking, or carrying a delimiter, a colon, a quote, a bracket or a control + * character. Read off the reference encoder rather than re-implemented: a key/value line + * quotes its value under the same rule a tabular row uses for the default delimiter. + */ +export function toonCell(value: string | number): string { + return encode({ c: value }).slice("c: ".length); } /** TOON is tabular: a field absent on one row and present on another breaks the uniform @@ -45,20 +77,35 @@ function cell(v: string | undefined): string { return v ?? ""; } -export function renderRequirementsToon(rows: readonly RequirementRow[]): string { - if (rows.length === 0) return ""; - - const table: ToonRow[] = rows.map((r) => ({ - path: r.path, - subType: r.subType, - level: r.level ?? "", - status: cell(r.status), - disposition: cell(r.disposition), - // Joined rather than nested: a nested array per row would cost the tabular header, - // which is the entire reason this format was picked. - claims: r.implementedBy.join(" "), - statement: cell(r.statement), - })); +/** The data the TOON template renders, for a non-empty ledger. */ +export function requirementsToonData(rows: readonly RequirementRow[]): RequirementsToonData { + return { + count: rows.length, + fields: `{${REQUIREMENTS_TOON_FIELDS.join(",")}}`, + rows: rows.map((r) => ({ + line: [ + r.path, + r.subType, + r.level ?? "", + cell(r.status), + cell(r.disposition), + // Joined rather than nested: a nested array per row would cost the tabular header, + // which is the entire reason this format was picked. + r.implementedBy.join(" "), + cell(r.statement), + ] + .map(toonCell) + .join(","), + })), + }; +} - return encode({ requirements: table }); +export function renderRequirementsToon(rows: readonly RequirementRow[], provider?: Provider): string { + if (rows.length === 0) return ""; + return renderDocPage( + REQUIREMENTS_TOON_REF, + requirementsToonData(rows), + provider ?? frameworkTemplatesProvider, + "requirements.toon", + ); } diff --git a/server/typescript/packages/codegen-ts/src/index.ts b/server/typescript/packages/codegen-ts/src/index.ts index 4cb6741bb4..79f17f5cd5 100644 --- a/server/typescript/packages/codegen-ts/src/index.ts +++ b/server/typescript/packages/codegen-ts/src/index.ts @@ -289,7 +289,10 @@ export { export { renderBarrel } from "./templates/barrel.js"; export type { BarrelEntry } from "./templates/barrel.js"; export { renderFilterType } from "./templates/filter-type.js"; -export { renderFilterAllowlist, renderSortAllowlist } from "./templates/filter-allowlist.js"; +export { + filterAllowlistRules, renderFilterAllowlist, renderSortAllowlist, sortAllowlistRules, + type FilterAllowlistRule, type SortAllowlistRule, +} from "./templates/filter-allowlist.js"; export { renderEntityConstants, renderValueObjectConstants, resourcePath } from "./templates/entity-constants.js"; export { renderQueriesFile } from "./templates/queries-file.js"; // #348 — which CRUD verbs a generated routes file mounts. Public because an OWNED @@ -410,6 +413,36 @@ export type { RequirementRow } from "./generators/requirements-view.js"; // author that `summary` is invisible while `title` is the entry's label. Both halves of // that claim need to be checkable against the projection rather than asserted in prose. export { requirementRows } from "./generators/requirements-view.js"; +// The four pages' builders and renderers. Each page is a shared Mustache template fed the +// data its builder returns (`fixtures/docs-page-conformance/` pins both, for every port), so +// an owned generator can change the data, the template, or both. +export { + REQUIREMENTS_PAGE_REF, + requirementsLedgerData, + renderRequirementsMarkdown, + type RequirementsLedgerData, + type RequirementsLedgerEntry, + type RequirementsMarkdownOpts, +} from "./generators/requirements-markdown.js"; +export { + REQUIREMENTS_TOON_REF, + requirementsToonData, + renderRequirementsToon, + type RequirementsToonData, +} from "./generators/requirements-toon.js"; +export { + AGENT_REQUIREMENTS_PAGE_REF, + agentRequirementsPageData, + renderAgentRequirementsPage, + type AgentRequirementsPageData, +} from "./generators/agent-requirements-page.js"; +export { + AGENT_SCHEMA_PAGE_REF, + agentSchemaPageData, + renderAgentSchemaPage, + type AgentSchemaPageData, + type AgentSchemaPageOptions, +} from "./generators/agent-schema-page.js"; export type { RequirementTestsOpts, RequirementTestRenderer, diff --git a/server/typescript/packages/codegen-ts/src/reference/agent-docs.ts b/server/typescript/packages/codegen-ts/src/reference/agent-docs.ts index 37972a25c3..e4426ee83c 100644 --- a/server/typescript/packages/codegen-ts/src/reference/agent-docs.ts +++ b/server/typescript/packages/codegen-ts/src/reference/agent-docs.ts @@ -15,11 +15,12 @@ // touching persistence; ui.md, read before touching a form or a grid; // requirements.md, read before adding a capability. A tier with nothing to // describe emits no file. -// customize: which of the three pages are written and where (`generate`), the schema -// page's inputs (`lineageOf`, `cardinalityPhrase`, `relationshipLines`, -// `enumLines` and the loop that builds `declaredBy`). The page renderers +// customize: which of the three pages are written and where (`generate`), and the +// `templates` option, which swaps the mustache templates the pages render +// through. The model walk (`modelFacts`, `lineageOf`, `relationshipLines`, +// `enumRows`) lives in `agent-schema-page`; the page renderers // (`agent-schema-page`, `agent-ui-page`, `agent-requirements-page`) are -// copied beside it into codegen/templates/. +// copied beside this file into codegen/templates/ by `meta eject`. // composes-with: api-docs (the fourth file the always-on pointer names, `api/AGENT-API.md`, // is the api reference's, not this one's). // @@ -44,38 +45,10 @@ // own. An empty page is no file. import { physicalNamingGuideUrl } from "@metaobjectsdev/metadata/release-docs"; +import { physicalNamingOf, physicalNamingRemovedMessage } from "@metaobjectsdev/metadata"; import { - CARDINALITY_MANY, - CARDINALITY_ONE, - FIELD_SUBTYPE_ENUM, - ORIGIN_AGGREGATE_ATTR_AGG, - ORIGIN_AGGREGATE_ATTR_OF, - ORIGIN_AGGREGATE_ATTR_VIA, - ORIGIN_ATTR_ORDER_BY, - ORIGIN_PASSTHROUGH_ATTR_FROM, - ORIGIN_PASSTHROUGH_ATTR_VIA, - ORIGIN_SUBTYPE_AGGREGATE, - ORIGIN_SUBTYPE_COMPUTED, - ORIGIN_SUBTYPE_FIRST, - ORIGIN_SUBTYPE_PASSTHROUGH, - RELATIONSHIP_ATTR_CARDINALITY, - RELATIONSHIP_ATTR_OBJECT_REF, - RELATIONSHIP_ATTR_ON_DELETE, - RELATIONSHIP_ATTR_THROUGH, - PHYSICAL_NAME_ATTR_BY_KIND, - SOURCE_ROLE_PRIMARY, - TYPE_ORIGIN, - resolveColumnName, - physicalNamingOf, - physicalNamingRemovedMessage, -} from "@metaobjectsdev/metadata"; -import type { MetaField, MetaObject } from "@metaobjectsdev/metadata"; -import { - enumValues, - intValueMapOf, - isAbstract, - isReport, - resolveObjectNames, + docsTemplateRoot, + projectProvider, type AgentSchemaInput, type EmittedFile, type Generator, @@ -100,125 +73,10 @@ export interface AgentDocsFileOpts { * project with no physical schema gets no schema page rather than a page of unknowns. */ schema?: AgentSchemaInput; -} - -/** One `origin.*` child rendered as a lineage phrase. `origin.*` NEVER inherits, so the - * own-accessor read here is the correct one rather than an ADR-0039 slip. */ -function lineageOf(field: MetaField): string | undefined { - const origin = field.ownChildren().find((c) => c.type === TYPE_ORIGIN); - if (origin === undefined) return undefined; - // Human-facing text: references print as the author wrote them (ADR-0059). - const str = (name: string): string | undefined => { - const v = origin.authoredAttr(name); - return typeof v === "string" && v !== "" ? v : undefined; - }; - switch (origin.subType) { - case ORIGIN_SUBTYPE_PASSTHROUGH: { - const from = str(ORIGIN_PASSTHROUGH_ATTR_FROM); - const via = str(ORIGIN_PASSTHROUGH_ATTR_VIA); - return `passthrough from \`${from ?? "?"}\`${via === undefined ? "" : ` via \`${via}\``}`; - } - case ORIGIN_SUBTYPE_AGGREGATE: { - const agg = str(ORIGIN_AGGREGATE_ATTR_AGG) ?? "?"; - const of = str(ORIGIN_AGGREGATE_ATTR_OF); - const via = str(ORIGIN_AGGREGATE_ATTR_VIA); - return `\`${agg}\`${of === undefined ? "" : ` of \`${of}\``}${via === undefined ? "" : ` via \`${via}\``}`; - } - case ORIGIN_SUBTYPE_FIRST: { - const of = str(ORIGIN_AGGREGATE_ATTR_OF); - const via = str(ORIGIN_AGGREGATE_ATTR_VIA); - const order = str(ORIGIN_ATTR_ORDER_BY); - return `first${of === undefined ? "" : ` \`${of}\``}${via === undefined ? "" : ` via \`${via}\``}` + - `${order === undefined ? "" : ` ordered by \`${order}\``}`; - } - case ORIGIN_SUBTYPE_COMPUTED: - // The @expr tree is structured; naming it is enough to route a reader to the - // declaration, and rendering a tree into a cell would be a second SQL lowering. - return "computed from a declared `@expr`"; - default: - return `\`origin.${origin.subType}\``; - } -} - -/** - * The cardinality phrase, from the DECLARING object's side. - * - * `@cardinality: one` does NOT mean one-to-one. It means this object holds the foreign - * key — many rows of it point at one target row — which is what `relation-resolver.ts` - * builds a belongs-to `one()` relation from. Rendering it as "one-to-one" told a reader - * the target row is claimed by at most one row here, which is the direction that makes - * someone write a lookup expecting a single result. - * - * `@cardinality` is OPTIONAL vocabulary (min 0), and ABSENT is its own answer: no - * navigation is generated at all. Folding that into "one-to-one" invented a shape the - * model never declared. - */ -function cardinalityPhrase(cardinality: unknown, through: unknown): string { - if (cardinality === CARDINALITY_MANY) { - return typeof through === "string" && through !== "" ? "many-to-many" : "one-to-many"; - } - if (cardinality === CARDINALITY_ONE) return "many-to-one"; - return "cardinality not declared"; -} - -/** `- \`Order.lines\` — one-to-many → \`OrderLine\`` */ -function relationshipLines(objects: readonly MetaObject[]): string[] { - const out: string[] = []; - for (const obj of objects) { - for (const rel of obj.relationships()) { - const cardinality = rel.attr(RELATIONSHIP_ATTR_CARDINALITY); - // References print as the author wrote them (ADR-0059); the loaded value is canonical. - const target = rel.authoredAttr(RELATIONSHIP_ATTR_OBJECT_REF); - const through = rel.authoredAttr(RELATIONSHIP_ATTR_THROUGH); - const onDelete = rel.attr(RELATIONSHIP_ATTR_ON_DELETE); - // The FQN, not the short name: this line is an ADDRESS a reader searches for. - const parts = [`\`${obj.resolutionKey()}.${rel.name}\``, `\`${rel.subType}\``]; - parts.push( - `${cardinalityPhrase(cardinality, through)} → \`${String(target ?? "?")}\``, - ); - if (typeof through === "string" && through !== "") parts.push(`through \`${through}\``); - if (typeof onDelete === "string" && onDelete !== "") parts.push(`on delete \`${onDelete}\``); - out.push(`- ${parts.join(" · ")}`); - } - } - return out; -} - -/** - * `| \`Order.status\` | OPEN, CLOSED | string-backed |` - * - * `objects` IS ONLY THE TABLE-BACKED SUBSET OF THE MODEL — the caller scopes it to the - * objects the snapshot actually holds as tables. This section sits on the SCHEMA page, so - * every row it prints is read as a statement about a column. Walking every loaded object - * printed rows for abstract bases, for `object.value`s that have no column anywhere, and - * for projections whose "column" is a view expression — three kinds of thing the physical - * schema does not contain. - * - * It also says nothing about a `CHECK`. Whether the database constrains the members is - * `table.checks`, which is already on this page from the snapshot, and an `@isArray` - * enum deliberately gets none (`migrate-ts` skips it) — so asserting one here was a - * SECOND derivation of a fact the page already carries correctly, in the direction that - * promises the database will refuse a value it will accept. - */ -function enumLines(objects: readonly MetaObject[]): string[] { - const rows: string[] = []; - for (const obj of objects) { - for (const field of obj.fields()) { - if (field.subType !== FIELD_SUBTYPE_ENUM) continue; - const members = enumValues(field); - if (members === undefined || members.length === 0) continue; - const intMap = intValueMapOf(field); - const backing = - intMap === undefined - ? "string-backed" - : `int-backed (${members.map((m) => `${m}=${intMap[m]}`).join(", ")})`; - rows.push( - `| \`${obj.resolutionKey()}.${field.name}\` | ${members.map((m) => `\`${m}\``).join(", ")} | ${backing} |`, - ); - } - } - if (rows.length === 0) return []; - return ["| Field | Members | Storage |", "|---|---|---|", ...rows]; + /** Directory whose `templates/agent/{schema,requirements}.md.mustache` (and + * `templates/requirements/requirements.md.mustache`, the embedded ledger) override the + * shipped pages, relative to the project. Default: the project's own `templates/`. */ + templates?: string; } export const agentDocsFile = function agentDocsFile(opts?: AgentDocsFileOpts): Generator { @@ -234,8 +92,10 @@ export const agentDocsFile = function agentDocsFile(opts?: AgentDocsFileOpts): G name: "agent-docs", target: opts?.target ?? DOCS_TARGET_NAME, generate(ctx) { - const objects = ctx.loadedRoot.objects(); const files: EmittedFile[] = []; + // The schema and requirements pages render shared templates; a same-named template + // under the project's `templates/` (or under `opts.templates`) replaces one. + const provider = projectProvider(docsTemplateRoot(ctx, opts?.templates)); // What the run computes for this generator: the schema, built on first ask by the // caller that owns the schema builder, and the project's column naming. Options win: // they are what a direct caller of the factory states. @@ -243,71 +103,10 @@ export const agentDocsFile = function agentDocsFile(opts?: AgentDocsFileOpts): G const columnNamingStrategy = ctx.renderContext?.columnNamingStrategy ?? physicalNamingOf(ctx.loadedRoot).columns; // ---- schema.md + // The model walk (column → declaring field, view lineage, relationships, enums) is + // the page builder's; this passes it the model, the schema and the naming. if (schemaInput !== undefined) { - const schema = schemaInput; - // The qualified names the snapshot actually holds. An object whose physical name - // is not one of these contributes nothing to the physical schema (an abstract - // base, a sourceless value, an `@unmanaged` object) and must not appear on a page - // describing it — `buildExpectedSchema`'s Pass 1 owns those skip rules and this - // reads its answer rather than re-deriving them. - const tableNames = new Set(schema.tables.map((t) => schema.qualify(t))); - const viewNames = new Set(schema.views.map((v) => schema.qualify(v))); - // The objects backed by a TABLE in the snapshot — the enum section's scope, since - // a row there is read as a statement about a column. - const tableBacked: MetaObject[] = []; - // column → declaring field, per qualified table name. `resolveObjectNames` is the - // ONE field→column resolver — the same one the names artifact and the DDL use — - // so this mapping cannot disagree with the column it labels. - const declaredBy = new Map>(); - const viewLineage = new Map(); - // Qualified names of the views a view-backed object.report owns (FR-044). Empty for a - // model with no report, so the page is byte-identical to what it was before reports. - const reportViews = new Set(); - for (const obj of objects) { - const names = resolveObjectNames(obj, columnNamingStrategy); - // The PRIMARY source's physical name and schema — `names.name` is the object's - // metamodel name since 0.25.0, which would match nothing in the snapshot. - const primary = names?.sources[SOURCE_ROLE_PRIMARY]; - const physical = primary === undefined - ? undefined - : primary[(PHYSICAL_NAME_ATTR_BY_KIND.get(primary.kind) ?? "") as keyof typeof primary]; - if (typeof physical !== "string") continue; - const key = schema.qualify({ name: physical, schema: primary?.schema }); - const isTable = tableNames.has(key); - if (!isTable && !viewNames.has(key)) continue; - // ABSTRACT BASES ARE EXCLUDED, and being in the snapshot does not exempt them: - // an abstract base that declares the `source.rdb` its concrete child inherits - // resolves to that child's table, so the qualified-name test admits it and the - // page printed the base's enum a second time under a different owner. - // `buildExpectedSchema`'s Pass 1 skips abstracts; this reads the same rule. - if (isTable && !isAbstract(obj)) tableBacked.push(obj); - if (!isTable && isReport(obj)) reportViews.add(key); - let map = declaredBy.get(key); - if (map === undefined) { - map = new Map(); - declaredBy.set(key, map); - } - const lineage: string[] = []; - for (const field of obj.fields()) { - const column = resolveColumnName(field, columnNamingStrategy); - // A TPH base and its subtypes share one table: first writer wins, so the - // base's own column keeps its label rather than being relabelled by whichever - // subtype was walked last. - if (!map.has(column)) { - map.set(column, { field: field.name, type: `${field.type}.${field.subType}` }); - } - const line = lineageOf(field); - if (line !== undefined) lineage.push(`| \`${column}\` | ${line} |`); - } - if (lineage.length > 0) viewLineage.set(key, lineage); - } - const content = renderAgentSchemaPage(schema, { - declaredBy, - viewLineage, - reportViews, - relationships: relationshipLines(objects), - enums: enumLines(tableBacked), - }); + const content = renderAgentSchemaPage(ctx.loadedRoot, schemaInput, columnNamingStrategy, { provider }); if (content !== "") files.push({ path: `${dir}/schema.md`, content }); } @@ -344,7 +143,7 @@ export const agentDocsFile = function agentDocsFile(opts?: AgentDocsFileOpts): G } // ---- requirements.md - const requirements = renderAgentRequirementsPage(ctx.loadedRoot, ctx.inLedger); + const requirements = renderAgentRequirementsPage(ctx.loadedRoot, ctx.inLedger, provider); if (requirements !== "") files.push({ path: `${dir}/requirements.md`, content: requirements }); return files; diff --git a/server/typescript/packages/codegen-ts/src/reference/requirements.ts b/server/typescript/packages/codegen-ts/src/reference/requirements.ts index 937d740a5f..a3e80ce948 100644 --- a/server/typescript/packages/codegen-ts/src/reference/requirements.ts +++ b/server/typescript/packages/codegen-ts/src/reference/requirements.ts @@ -28,12 +28,15 @@ // renderers from `../generators/` — which `meta eject` copies into your project and points at // your copy. // -// METADATA ALONE: this generator reads `ctx.loadedRoot` and NOTHING else. An EMPTY LEDGER +// METADATA ALONE: this generator reads `ctx.loadedRoot` and NOTHING else (a page template +// under the project's `templates/requirements/` shapes the layout and adds no fact). An EMPTY LEDGER // EMITS ZERO FILES, not an empty page. BOTH FILES, UNCONDITIONALLY: a drift gate wants the // machine-readable artifact committed regardless of who ran it. import { + docsTemplateRoot, oncePerRun, + projectProvider, type EmittedFile, type Generator, type GeneratorFactory, @@ -53,6 +56,9 @@ export interface RequirementsFileOpts { outDir?: string; /** Named output target. Default `"docs"`, which `targets` must declare. */ target?: string; + /** Directory whose `templates/requirements/requirements.{md,toon}.mustache` override the + * shipped pages, relative to the project. Default: the project's own `templates/`. */ + templates?: string; } export const requirementsFile = function requirementsFile( @@ -70,9 +76,10 @@ export const requirementsFile = function requirementsFile( // "zero FILES", which only this line can provide. if (rows.length === 0) return []; + const provider = projectProvider(docsTemplateRoot(ctx, opts?.templates)); const files: EmittedFile[] = [ - { path: `${dirPrefix}${MARKDOWN_FILENAME}`, content: renderRequirementsMarkdown(rows) }, - { path: `${dirPrefix}${TOON_FILENAME}`, content: renderRequirementsToon(rows) }, + { path: `${dirPrefix}${MARKDOWN_FILENAME}`, content: renderRequirementsMarkdown(rows, { provider }) }, + { path: `${dirPrefix}${TOON_FILENAME}`, content: renderRequirementsToon(rows, provider) }, ]; return files; }), diff --git a/server/typescript/packages/codegen-ts/src/render-engine/embedded-templates.generated.ts b/server/typescript/packages/codegen-ts/src/render-engine/embedded-templates.generated.ts index ee5199bdc4..e6e10bc9d1 100644 --- a/server/typescript/packages/codegen-ts/src/render-engine/embedded-templates.generated.ts +++ b/server/typescript/packages/codegen-ts/src/render-engine/embedded-templates.generated.ts @@ -6,9 +6,13 @@ // `templates/` directory is unavailable. Keys are provider resolve refs // (path under templates/ minus the .mustache suffix). export const EMBEDDED_FRAMEWORK_TEMPLATES: Record = { + "agent/requirements.md": "{{{generatedMarker}}}\n\n# Requirements\n\nRead this before adding a capability, and before extending anything that looks like it already does what you were asked for.\n\n- A requirement is **prescriptive**: it states what should be true, never what happened. `status: retired` means the capability was BUILT and deliberately REMOVED — that entry is a prohibition, not history, and the right response to it is to stop, not to rebuild.\n- The **node index** below answers *\"does anything claim the thing I am about to change?\"*. Match the literal FQN.\n- **The ledger under it is not the same list.** A retired capability carries no `@implementedBy` — there is nothing left to point at — so it appears there and in no index. Read it before you conclude a capability does not exist yet.\n\n## Node index\n\n{{#hasNodeIndex}}\n| Node | Kind | Claimed by |\n|---|---|---|\n{{#nodeIndex}}\n| `{{{address}}}` | `{{{concern}}}` | {{{claims}}} |\n{{/nodeIndex}}\n{{#hasStatements}}\n\n### What those requirements say\n\n{{#statements}}\n- `{{{path}}}` (`{{{subType}}}`) — {{{statement}}}\n{{/statements}}\n{{/hasStatements}}\n{{/hasNodeIndex}}\n{{^hasNodeIndex}}\nNo requirement resolves to a model node. The common reason is the ordinary one: an entry at L4 or L5 that simply declares no `@implementedBy` yet, which is legal and is what a `planned` entry looks like. The others are an entry sitting ABOVE the L4 link floor (where a claim is not permitted), a `retired` entry (where it is forbidden outright), and a claim that names a node nothing resolves — `meta verify` is what says which.\n{{/hasNodeIndex}}\n\n## The ledger\n\n{{{ledger}}}\n", + "agent/schema.md": "{{{generatedMarker}}}\n\n# Schema\n\n{{#physical}}\nThe physical shape of the `{{{dialect}}}` database this model generates. Read it before writing a query, a migration, or anything that names a table or a column.\n{{/physical}}\n{{^physical}}\nThe tables, columns and keys this model declares. Read it before writing a query, a migration, or anything that names a table or a column. SQL types, defaults, indexes, checks, constraint names and referential actions are not on this page: the migration files carry them.\n{{/physical}}\n\n- The **DDL is not repeated here.** The migration files are the DDL, they are generated, and they are what runs — this page describes the schema they produce.\n- Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate.\n- `Field` and `Declared` are the METADATA names. Edit those; the column name follows.\n\n{{#descriptionNudge}}\n> **Nothing in this model declares a `description`.** The tables and columns below are named but not explained. Adding `description` to an entity or a field is the single highest-value change to this page: it is what tells a reader *which* of two plausible columns to use, and it is the same text `meta migrate` emits as a `COMMENT ON`, so it lands in the database too.\n\n{{/descriptionNudge}}\n{{#hasTables}}\n## Tables\n\n{{#tables}}\n### {{{heading}}}\n\n{{#tableDeclaredBy}}\nDeclared by `{{{.}}}`.\n{{/tableDeclaredBy}}\n{{#tableDescription}}\n\n> {{{.}}}\n{{/tableDescription}}\n\n{{#physical}}\n| Column | Field | Declared | SQL type | Null | Default | Key |\n|---|---|---|---|---|---|---|\n{{/physical}}\n{{^physical}}\n| Column | Field | Declared | Null | Key |\n|---|---|---|---|---|\n{{/physical}}\n{{#columns}}\n| `{{{name}}}` | {{{fieldCell}}} | {{{declaredCell}}} |{{#physical}} {{{sqlTypeCell}}} |{{/physical}} {{{nullCell}}} |{{#physical}} {{{defaultCell}}} |{{/physical}} {{{keyCell}}} |\n{{/columns}}\n{{#hasDescribed}}\n\n{{#described}}\n- `{{{name}}}` — {{{text}}}\n{{/described}}\n{{/hasDescribed}}\n{{#hasIndexes}}\n\n**Indexes**\n\n{{#indexes}}\n- {{{.}}}\n{{/indexes}}\n{{/hasIndexes}}\n{{#hasForeignKeys}}\n\n**Foreign keys**\n\n{{#foreignKeys}}\n- {{{.}}}\n{{/foreignKeys}}\n{{/hasForeignKeys}}\n{{#hasChecks}}\n\n**Checks**\n\n{{#checks}}\n- {{{.}}}\n{{/checks}}\n{{/hasChecks}}\n\n{{/tables}}\n{{/hasTables}}\n{{#hasViews}}\n## Views\n\nA view is generated from its projection's `origin.*` children{{#hasReportView}} or its report's dimensions and measures{{/hasReportView}} — it is derived, never hand-written. Editing the view SQL directly is drift the tool cannot see.\n\n{{#views}}\n### {{{heading}}}\n\n{{#viewDeclaredBy}}\nDeclared by `{{{.}}}`.\n{{/viewDeclaredBy}}\n{{#hasLineage}}\n\n| Column | Lineage |\n|---|---|\n{{#lineage}}\n| `{{{column}}}` | {{{text}}} |\n{{/lineage}}\n{{/hasLineage}}\n\n{{/views}}\n{{/hasViews}}\n{{#hasRelationships}}\n## Relationships\n\n{{#relationships}}\n- {{{.}}}\n{{/relationships}}\n\n{{/hasRelationships}}\n{{#hasEnums}}\n## Enums\n\nMembers are the values the wire and the generated types use.{{#physical}} Whether the DATABASE also refuses a value outside the set is that table's **Checks** above — an `@isArray` enum carries none, and neither does a view column.{{/physical}}\n\n| Field | Members | Storage |\n|---|---|---|\n{{#enums}}\n| `{{{field}}}` | {{{members}}} | {{{storage}}} |\n{{/enums}}\n{{/hasEnums}}\n", "api/agent-api.md": "{{{generatedMarker}}}\n\n# {{title}}\n\nGenerated API reference for {{project}}; call these exactly as written. {{importNote}}\n{{#hasSetup}}\n\n## Setup\n{{#setup}}\n- `{{handle}}` — {{{note}}} `{{{snippetInline}}}`\n{{/setup}}\n{{/hasSetup}}\n{{#units}}\n\n## {{node}}\n{{#groups}}\n\n`{{importHeader}}`\n{{#symbols}}\n- `{{signature}}` — {{usage}}{{#throwsMarker}} {{throwsMarker}}{{/throwsMarker}}\n{{/symbols}}\n{{/groups}}\n{{#example}}\n\nExample:\n```ts\n{{{example}}}\n```\n{{/example}}\n{{/units}}\n", "api/entity-api.md": "{{{generatedMarker}}}\n\n# {{node}} API\n{{#modelPageHref}}\n\n**Model / metadata:** [{{node}}]({{modelPageHref}})\n{{/modelPageHref}}\n\n> Import paths are relative to your generated-output directory.\n{{#hasSetup}}\n\n## Setup\n\nObtain the runtime handles the calls below need:\n{{#setup}}\n\n- `{{handle}}` — {{{note}}}\n\n```ts\n{{{snippet}}}\n```\n{{/setup}}\n{{/hasSetup}}\n{{#unitExample}}\n\n## Example\n\n```ts\n{{{unitExample}}}\n```\n{{/unitExample}}\n{{#sections}}\n\n## {{heading}}\n{{#symbols}}\n\n### `{{signature}}`\n\n{{usage}}\n\n```ts\n{{importLine}}\n```\n{{#hasFields}}\n\n{{fieldsCaption}}:\n\n| Field | Type | Required | Notes |\n|---|---|---|---|\n{{#fieldRows}}\n| `{{field}}` | `{{{type}}}` | {{required}} | {{notes}} |\n{{/fieldRows}}\n{{/hasFields}}\n{{#mountNote}}\n\nMount: {{{mountNote}}}\n{{/mountNote}}\n{{#throws}}\n\nThrows: {{throws}}\n{{/throws}}\n{{#example}}\n\n```ts\n{{{example}}}\n```\n{{/example}}\n{{/symbols}}\n{{/sections}}\n", "api/index.md": "{{{generatedMarker}}}\n\n# {{title}}\n\n{{intro}}\n{{#hasEntities}}\n\n## Entities\n\n{{#entities}}\n- [{{node}}]({{href}}) — {{summary}} ({{symbolCount}} symbol{{^one}}s{{/one}})\n{{/entities}}\n{{/hasEntities}}\n{{#hasTemplates}}\n\n## Templates\n\n{{#templates}}\n- [{{node}}]({{href}}) — {{summary}} ({{symbolCount}} symbol{{^one}}s{{/one}})\n{{/templates}}\n{{/hasTemplates}}\n", "docs/entity-page.md": "{{{generatedMarker}}}\n\n# {{entity.name}}\n{{#summaryLead}}\n\n{{{.}}}\n{{/summaryLead}}\n{{#descriptionQuote}}\n\n{{{.}}}\n{{/descriptionQuote}}\n{{#apiRefs.0}}\n\n**API reference:** {{/apiRefs.0}}{{#apiRefs}}[{{label}}]({{href}}){{^last}} · {{/last}}{{/apiRefs}}{{#apiRefs.0}}\n{{/apiRefs.0}}\n\n{{{preambleHeader}}}\n{{#hasReport}}\n\n## Report\n\n{{{reportBlock}}}\n{{/hasReport}}\n{{#hasIdentities}}\n\n## Identity\n\n{{#identities}}\n- {{{bullet}}}\n{{/identities}}\n{{/hasIdentities}}\n{{#hasNeighborhoodEr}}\n\n## In context\n\n{{{neighborhoodErBlock}}}\n{{/hasNeighborhoodEr}}\n{{#fields.hasFields}}\n\n## Fields\n\n| Field | Type | Required | Column | Rules |\n|---|---|---|---|---|\n{{#fields.rows}}\n| {{{fieldCell}}} | {{{typeCell}}} | {{requiredCell}} | {{{storageCell}}} | {{{rulesCell}}} |\n{{/fields.rows}}\n{{/fields.hasFields}}\n{{#fieldDetails.hasDetails}}\n\n## Field details\n\n{{#fieldDetails.rows}}\n{{{block}}}\n\n{{/fieldDetails.rows}}\n{{/fieldDetails.hasDetails}}\n{{#hasRelationships}}\n\n## Relationships\n\n{{#relationships}}\n- {{{bullet}}}\n{{/relationships}}\n{{/hasRelationships}}\n{{#hasUsedBy}}\n\n## Used by\n\n{{#usedBy}}\n- {{{bullet}}}\n{{/usedBy}}\n{{/hasUsedBy}}\n{{#hasClaimedBy}}\n\n## Required by\n\n{{#claimedBy}}\n- {{{bullet}}}\n{{/claimedBy}}\n{{/hasClaimedBy}}\n{{#hasReporting}}\n\n## Reporting\n\n{{{reportingBlock}}}\n{{/hasReporting}}\n", "docs/template-page.md": "{{{generatedMarker}}}\n\n# {{name}}\n{{#descriptionQuote}}\n\n{{{.}}}\n{{/descriptionQuote}}\n\n**Kind:** {{kind}}\n\n## Output\n{{^isEmail}}\n\n- Format: `{{format}}`\n{{/isEmail}}\n{{#isEmail}}\n\nMultipart email — rendered as the following parts:\n\n| Part | Source | Format | Escaping |\n|---|---|---|---|\n{{#parts}}\n| {{label}} | `{{ref}}` | `{{format}}` | {{#escaped}}escaped{{/escaped}}{{^escaped}}raw{{/escaped}} |\n{{/parts}}\n{{/isEmail}}\n\n## Input\n\n- Payload: [`{{payload.name}}`]({{payload.link}})\n{{#hasRequiredTags}}\n- Required fields:{{#requiredTags}} `{{.}}`{{/requiredTags}}\n{{/hasRequiredTags}}\n\n## Render contract\n\n- Every field referenced by the template is validated against the payload at generation time; an unknown field fails generation.\n{{#maxChars}}\n- Maximum length: {{.}} characters (rendering longer output fails).\n{{/maxChars}}\n{{#hasRequiredTags}}\n- Required tags must be present:{{#requiredTags}} `{{.}}`{{/requiredTags}}\n{{/hasRequiredTags}}\n\n## Source\n\n{{#sourceRefs}}\n- `{{.}}`\n{{/sourceRefs}}\n{{#templateSourceSection}}\n\n{{{.}}}\n{{/templateSourceSection}}\n\n## Capability\n\n{{capability}}\n", + "requirements/requirements.md": "{{^embedded}}\n# Requirements\n\n{{/embedded}}\n{{{count}}} declared requirement{{{plural}}}, in declaration order.\n{{#entries}}\n\n{{{heading}}}\n\n{{{facts}}}\n{{#statement}}\n\n{{{.}}}\n{{/statement}}\n{{#counterexample}}\n\n{{{.}}}\n{{/counterexample}}\n{{#description}}\n\n{{{.}}}\n{{/description}}\n{{#implementedBy}}\n\n{{{.}}}\n{{/implementedBy}}\n{{/entries}}\n", + "requirements/requirements.toon": "requirements[{{{count}}}]{{{fields}}}:{{#rows}}\n {{{line}}}{{/rows}}", }; diff --git a/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts b/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts index 6a9052139c..8ffd17968f 100644 --- a/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts +++ b/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts @@ -590,16 +590,16 @@ function buildCompositeKeyCallback( return code`${primaryKeySym}({ columns: [${columnRefs}] })`; } -/** Build a JS-style object literal string (not JSON.stringify which uses quoted keys). - * Array values get `as const` appended so Drizzle's text(...,{ enum: [...] }) - * narrows the inferred column type to a literal union instead of bare `string`. */ -function inlineObjectLiteral(obj: Record): string { +/** Build a JS-style object literal string (not JSON.stringify, which quotes every key): + * `{ length: 200 }`, not `{ "length": 200 }`. A key that is not a bare identifier keeps + * its quotes. Array values get `as const` appended so Drizzle's text(...,{ enum: [...] }) + * narrows the inferred column type to a literal union instead of bare `string`. Shared by + * the table template and the existing-view declaration (`view-decl.ts`). */ +export function inlineObjectLiteral(obj: Record): string { const entries = Object.entries(obj).map(([k, v]) => { + const name = /^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k); const lit = JSON.stringify(v); - if (Array.isArray(v)) { - return `${k}: ${lit} as const`; - } - return `${k}: ${lit}`; + return Array.isArray(v) ? `${name}: ${lit} as const` : `${name}: ${lit}`; }); return `{ ${entries.join(", ")} }`; } diff --git a/server/typescript/packages/codegen-ts/src/templates/filter-allowlist.ts b/server/typescript/packages/codegen-ts/src/templates/filter-allowlist.ts index b477b7b59d..de6c4345ff 100644 --- a/server/typescript/packages/codegen-ts/src/templates/filter-allowlist.ts +++ b/server/typescript/packages/codegen-ts/src/templates/filter-allowlist.ts @@ -93,24 +93,45 @@ const INTEGER_SUBTYPES = new Set([ * as UTC, the same rule the generated write schema stores it by. Scalar fields only: an * array field's filter value is not one element of the declared type. */ -function valueShape(f: MetaField): string { - if (f.resolvedIsArray()) return ""; - if (INTEGER_SUBTYPES.has(f.subType)) return ", integer: true as const"; +function valueShape(f: MetaField): FilterRuleValueShape { + if (f.resolvedIsArray()) return {}; + if (INTEGER_SUBTYPES.has(f.subType)) return { integer: true }; if (VALUE_FORMAT_SUBTYPES.has(f.subType)) { - const instant = f.subType === FIELD_SUBTYPE_TIMESTAMP && f.attr(FIELD_ATTR_LOCAL_TIME) !== true - ? ", instant: true as const" - : ""; - return `, format: ${JSON.stringify(f.subType)} as const${instant}`; + const instant = f.subType === FIELD_SUBTYPE_TIMESTAMP && f.attr(FIELD_ATTR_LOCAL_TIME) !== true; + return instant ? { format: f.subType, instant: true } : { format: f.subType }; } if (f.subType === FIELD_SUBTYPE_ENUM) { // Member SYMBOLS for string- and int-backed enums alike: an int-backed column's codec // maps the symbol to its integer when the value is bound. const members = enumValues(f); - if (members !== undefined && members.length > 0) { - return `, enumValues: [${members.map((m) => JSON.stringify(m)).join(", ")}] as const`; - } + if (members !== undefined && members.length > 0) return { enumValues: members }; } - return ""; + return {}; +} + +/** The optional members of a rule beyond `ops` / `subType` / `leadingWildcard`. */ +interface FilterRuleValueShape { + readonly dateValues?: true; + readonly format?: string; + readonly instant?: true; + readonly integer?: true; + readonly enumValues?: readonly string[]; +} + +/** + * One field's filter rule, as data: what `FilterAllowlist` carries for it. The + * runtime-ts `FilterFieldRule` shape, kept structural here so codegen does not depend on + * the runtime package. + */ +export interface FilterAllowlistRule extends FilterRuleValueShape { + readonly ops: readonly string[]; + readonly subType: "string" | "number" | "boolean" | "datetime"; + readonly leadingWildcard: false; +} + +/** One sortable field's rule, as data: what `SortAllowlist` carries for it. */ +export interface SortAllowlistRule { + readonly defaultOrder?: "asc" | "desc"; } function filterableFields(entity: MetaObject, exclude: string | undefined, ctx: RenderContext | undefined): MetaField[] { @@ -134,29 +155,49 @@ function filterableFields(entity: MetaObject, exclude: string | undefined, ctx: * normalized to `"string"` for sqlite/D1 at both config choke points, so no dialect * branching is needed here. Absent `ctx`, or in the default mode, output is unchanged. */ +export function filterAllowlistRules( + entity: MetaObject, + exclude?: string, + ctx?: RenderContext, +): ReadonlyArray { + return filterableFields(entity, exclude, ctx).map((f) => { + // opsForField, not opsForSubType — an int-backed field.enum (@intValueMap) + // stores as an integer, so `like` (a substring match) is not in its band. + const rule: FilterAllowlistRule = { + ops: opsForField(f), + subType: filterSubTypeFor(f.subType), + leadingWildcard: false, + // Only field.timestamp is governed by timestampMode — Drizzle types + // field.date / field.time as strings under every dialect. + ...(ctx?.timestampMode === "date" && f.subType === FIELD_SUBTYPE_TIMESTAMP ? { dateValues: true as const } : {}), + ...valueShape(f), + }; + return [f.name, rule] as const; + }); +} + +/** One rule as the generated allowlist spells it (members in a fixed order, `as const` on each). */ +function filterRuleLiteral(rule: FilterAllowlistRule): string { + const ops = rule.ops.map((o) => JSON.stringify(o)).join(", "); + let out = `{ ops: [${ops}] as const, subType: ${JSON.stringify(rule.subType)} as const, leadingWildcard: false`; + if (rule.dateValues) out += ", dateValues: true as const"; + if (rule.integer) out += ", integer: true as const"; + if (rule.format !== undefined) out += `, format: ${JSON.stringify(rule.format)} as const`; + if (rule.instant) out += ", instant: true as const"; + if (rule.enumValues !== undefined) out += `, enumValues: [${rule.enumValues.map((m) => JSON.stringify(m)).join(", ")}] as const`; + return `${out} }`; +} + export function renderFilterAllowlist(entity: MetaObject, exclude?: string, ctx?: RenderContext): Code { - const fields = filterableFields(entity, exclude, ctx); - if (fields.length === 0) { + const rules = filterAllowlistRules(entity, exclude, ctx); + if (rules.length === 0) { return code` import type { FilterAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; export const ${entity.name}FilterAllowlist = {} as const satisfies FilterAllowlist; `; } - const rows = fields - .map((f) => { - // opsForField, not opsForSubType — an int-backed field.enum (@intValueMap) - // stores as an integer, so `like` (a substring match) is not in its band. - const ops = opsForField(f).map((o) => JSON.stringify(o)).join(", "); - const sub = filterSubTypeFor(f.subType); - // Only field.timestamp is governed by timestampMode — Drizzle types - // field.date / field.time as strings under every dialect. - const dateValues = ctx?.timestampMode === "date" && f.subType === FIELD_SUBTYPE_TIMESTAMP - ? ", dateValues: true as const" - : ""; - return ` ${f.name}: { ops: [${ops}] as const, subType: ${JSON.stringify(sub)} as const, leadingWildcard: false${dateValues}${valueShape(f)} }`; - }) - .join(",\n"); + const rows = rules.map(([name, rule]) => ` ${name}: ${filterRuleLiteral(rule)}`).join(",\n"); return code` import type { FilterAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; @@ -166,34 +207,39 @@ ${rows} `; } -export function renderSortAllowlist(entity: MetaObject, exclude?: string, ctx?: RenderContext): Code { +/** The sortable fields and their rules, as data (what `SortAllowlist` carries). */ +export function sortAllowlistRules( + entity: MetaObject, + exclude?: string, + ctx?: RenderContext, +): ReadonlyArray { // Sortable = explicit @sortable === true, OR (no @sortable AND @filterable === true). - // @sortable: false explicitly opts out. - // Uses shared isSortableField predicate — must stay in sync with renderFilterType. - // `exclude` (FR-017): per-subtype TPH allowlists omit the discriminator. - // A credential is never sortable (isSortableField), nor a column a sibling subtype marks as one. + // @sortable: false explicitly opts out. A credential is never sortable, nor a column a + // sibling subtype marks as one. `exclude` (FR-017): per-subtype TPH allowlists omit the + // discriminator. const credentials = credentialFieldNames(entity, ctx?.loadedRoot); - const sortable = flatSurfaceFields(entity).filter((f) => isSortableField(f) && !credentials.has(f.name) && f.name !== exclude); - if (sortable.length === 0) { + return flatSurfaceFields(entity) + .filter((f) => isSortableField(f) && !credentials.has(f.name) && f.name !== exclude) + .map((f) => { + // The DECLARED order only — an undeclared field stays `{}` so the runtime's own + // `?? "asc"` remains the single place the fallback is spelled. + const defaultOrder = declaredSortDefaultOrder(f); + return [f.name, defaultOrder === undefined ? {} : { defaultOrder }] as const; + }); +} + +export function renderSortAllowlist(entity: MetaObject, exclude?: string, ctx?: RenderContext): Code { + const rules = sortAllowlistRules(entity, exclude, ctx); + if (rules.length === 0) { return code` import type { SortAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; export const ${entity.name}SortAllowlist = {} as const satisfies SortAllowlist; `; } - const rows = sortable - .map((f) => { - // The DECLARED order only — an undeclared field stays `{}` so the runtime's own - // `?? "asc"` remains the single place the fallback is spelled. Read through the - // shared resolver, never off the attr here, so this allowlist and the grid tier - // cannot answer one declaration two ways. - const defaultOrder = declaredSortDefaultOrder(f); - const rule = - defaultOrder === undefined - ? `{}` - : `{ defaultOrder: ${JSON.stringify(defaultOrder)} as const }`; - return ` ${f.name}: ${rule}`; - }) + const rows = rules + .map(([name, rule]) => + ` ${name}: ${rule.defaultOrder === undefined ? "{}" : `{ defaultOrder: ${JSON.stringify(rule.defaultOrder)} as const }`}`) .join(",\n"); return code` import type { SortAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; diff --git a/server/typescript/packages/codegen-ts/src/templates/view-decl.ts b/server/typescript/packages/codegen-ts/src/templates/view-decl.ts index e039ce477f..a6f4be1436 100644 --- a/server/typescript/packages/codegen-ts/src/templates/view-decl.ts +++ b/server/typescript/packages/codegen-ts/src/templates/view-decl.ts @@ -18,6 +18,7 @@ import { mapColumnType, DURATION_COLUMN_FN, type EnumIntCustomType } from "../co import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; import { zodTypeFor } from "./field-meta.js"; +import { inlineObjectLiteral } from "./drizzle-schema.js"; import { columnExpr, type ObjectNames } from "../names.js"; export interface ViewDeclOpts { @@ -111,7 +112,7 @@ function viewColumnLine( : imp(`${spec.fnName}@${spec.importModule}`); const optsArg = spec.fnOptions && Object.keys(spec.fnOptions).length > 0 - ? `, ${optionsLiteral(spec.fnOptions)}` + ? `, ${inlineObjectLiteral(spec.fnOptions)}` : ""; // #204 — of the table modifiers, only `.array()` (postgres native array element // typing) and `.notNull()` (shapes the SELECT type) carry to an existing view; @@ -252,12 +253,3 @@ export function renderViewReadZodObject(fields: readonly MetaField[], opts: View ${joinCode(lines, { on: ",\n" })} })`; } - -/** A column's options as a JS object literal: `{ length: 200 }`, not JSON's `{ "length": 200 }`. */ -function optionsLiteral(options: Record): string { - const entries = Object.entries(options).map(([key, value]) => { - const name = /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key); - return `${name}: ${JSON.stringify(value)}`; - }); - return `{ ${entries.join(", ")} }`; -} diff --git a/server/typescript/packages/codegen-ts/templates/agent/requirements.md.mustache b/server/typescript/packages/codegen-ts/templates/agent/requirements.md.mustache new file mode 100644 index 0000000000..cb7cba06cb --- /dev/null +++ b/server/typescript/packages/codegen-ts/templates/agent/requirements.md.mustache @@ -0,0 +1,34 @@ +{{{generatedMarker}}} + +# Requirements + +Read this before adding a capability, and before extending anything that looks like it already does what you were asked for. + +- A requirement is **prescriptive**: it states what should be true, never what happened. `status: retired` means the capability was BUILT and deliberately REMOVED — that entry is a prohibition, not history, and the right response to it is to stop, not to rebuild. +- The **node index** below answers *"does anything claim the thing I am about to change?"*. Match the literal FQN. +- **The ledger under it is not the same list.** A retired capability carries no `@implementedBy` — there is nothing left to point at — so it appears there and in no index. Read it before you conclude a capability does not exist yet. + +## Node index + +{{#hasNodeIndex}} +| Node | Kind | Claimed by | +|---|---|---| +{{#nodeIndex}} +| `{{{address}}}` | `{{{concern}}}` | {{{claims}}} | +{{/nodeIndex}} +{{#hasStatements}} + +### What those requirements say + +{{#statements}} +- `{{{path}}}` (`{{{subType}}}`) — {{{statement}}} +{{/statements}} +{{/hasStatements}} +{{/hasNodeIndex}} +{{^hasNodeIndex}} +No requirement resolves to a model node. The common reason is the ordinary one: an entry at L4 or L5 that simply declares no `@implementedBy` yet, which is legal and is what a `planned` entry looks like. The others are an entry sitting ABOVE the L4 link floor (where a claim is not permitted), a `retired` entry (where it is forbidden outright), and a claim that names a node nothing resolves — `meta verify` is what says which. +{{/hasNodeIndex}} + +## The ledger + +{{{ledger}}} diff --git a/server/typescript/packages/codegen-ts/templates/agent/schema.md.mustache b/server/typescript/packages/codegen-ts/templates/agent/schema.md.mustache new file mode 100644 index 0000000000..3c3da61ea3 --- /dev/null +++ b/server/typescript/packages/codegen-ts/templates/agent/schema.md.mustache @@ -0,0 +1,118 @@ +{{{generatedMarker}}} + +# Schema + +{{#physical}} +The physical shape of the `{{{dialect}}}` database this model generates. Read it before writing a query, a migration, or anything that names a table or a column. +{{/physical}} +{{^physical}} +The tables, columns and keys this model declares. Read it before writing a query, a migration, or anything that names a table or a column. SQL types, defaults, indexes, checks, constraint names and referential actions are not on this page: the migration files carry them. +{{/physical}} + +- The **DDL is not repeated here.** The migration files are the DDL, they are generated, and they are what runs — this page describes the schema they produce. +- Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. +- `Field` and `Declared` are the METADATA names. Edit those; the column name follows. + +{{#descriptionNudge}} +> **Nothing in this model declares a `description`.** The tables and columns below are named but not explained. Adding `description` to an entity or a field is the single highest-value change to this page: it is what tells a reader *which* of two plausible columns to use, and it is the same text `meta migrate` emits as a `COMMENT ON`, so it lands in the database too. + +{{/descriptionNudge}} +{{#hasTables}} +## Tables + +{{#tables}} +### {{{heading}}} + +{{#tableDeclaredBy}} +Declared by `{{{.}}}`. +{{/tableDeclaredBy}} +{{#tableDescription}} + +> {{{.}}} +{{/tableDescription}} + +{{#physical}} +| Column | Field | Declared | SQL type | Null | Default | Key | +|---|---|---|---|---|---|---| +{{/physical}} +{{^physical}} +| Column | Field | Declared | Null | Key | +|---|---|---|---|---| +{{/physical}} +{{#columns}} +| `{{{name}}}` | {{{fieldCell}}} | {{{declaredCell}}} |{{#physical}} {{{sqlTypeCell}}} |{{/physical}} {{{nullCell}}} |{{#physical}} {{{defaultCell}}} |{{/physical}} {{{keyCell}}} | +{{/columns}} +{{#hasDescribed}} + +{{#described}} +- `{{{name}}}` — {{{text}}} +{{/described}} +{{/hasDescribed}} +{{#hasIndexes}} + +**Indexes** + +{{#indexes}} +- {{{.}}} +{{/indexes}} +{{/hasIndexes}} +{{#hasForeignKeys}} + +**Foreign keys** + +{{#foreignKeys}} +- {{{.}}} +{{/foreignKeys}} +{{/hasForeignKeys}} +{{#hasChecks}} + +**Checks** + +{{#checks}} +- {{{.}}} +{{/checks}} +{{/hasChecks}} + +{{/tables}} +{{/hasTables}} +{{#hasViews}} +## Views + +A view is generated from its projection's `origin.*` children{{#hasReportView}} or its report's dimensions and measures{{/hasReportView}} — it is derived, never hand-written. Editing the view SQL directly is drift the tool cannot see. + +{{#views}} +### {{{heading}}} + +{{#viewDeclaredBy}} +Declared by `{{{.}}}`. +{{/viewDeclaredBy}} +{{#hasLineage}} + +| Column | Lineage | +|---|---| +{{#lineage}} +| `{{{column}}}` | {{{text}}} | +{{/lineage}} +{{/hasLineage}} + +{{/views}} +{{/hasViews}} +{{#hasRelationships}} +## Relationships + +{{#relationships}} +- {{{.}}} +{{/relationships}} + +{{/hasRelationships}} +{{#hasEnums}} +## Enums + +Members are the values the wire and the generated types use.{{#physical}} Whether the DATABASE also refuses a value outside the set is that table's **Checks** above — an `@isArray` enum carries none, and neither does a view column.{{/physical}} + +| Field | Members | Storage | +|---|---|---| +{{#enums}} +| `{{{field}}}` | {{{members}}} | {{{storage}}} | +{{/enums}} +{{/hasEnums}} diff --git a/server/typescript/packages/codegen-ts/templates/requirements/requirements.md.mustache b/server/typescript/packages/codegen-ts/templates/requirements/requirements.md.mustache new file mode 100644 index 0000000000..a200094478 --- /dev/null +++ b/server/typescript/packages/codegen-ts/templates/requirements/requirements.md.mustache @@ -0,0 +1,27 @@ +{{^embedded}} +# Requirements + +{{/embedded}} +{{{count}}} declared requirement{{{plural}}}, in declaration order. +{{#entries}} + +{{{heading}}} + +{{{facts}}} +{{#statement}} + +{{{.}}} +{{/statement}} +{{#counterexample}} + +{{{.}}} +{{/counterexample}} +{{#description}} + +{{{.}}} +{{/description}} +{{#implementedBy}} + +{{{.}}} +{{/implementedBy}} +{{/entries}} diff --git a/server/typescript/packages/codegen-ts/templates/requirements/requirements.toon.mustache b/server/typescript/packages/codegen-ts/templates/requirements/requirements.toon.mustache new file mode 100644 index 0000000000..cae64ef896 --- /dev/null +++ b/server/typescript/packages/codegen-ts/templates/requirements/requirements.toon.mustache @@ -0,0 +1,2 @@ +requirements[{{{count}}}]{{{fields}}}:{{#rows}} + {{{line}}}{{/rows}} \ No newline at end of file diff --git a/server/typescript/packages/codegen-ts/test/adopt-baseline.test.ts b/server/typescript/packages/codegen-ts/test/adopt-baseline.test.ts index bee24e8e1a..6131f5fb5d 100644 --- a/server/typescript/packages/codegen-ts/test/adopt-baseline.test.ts +++ b/server/typescript/packages/codegen-ts/test/adopt-baseline.test.ts @@ -14,8 +14,7 @@ import { manifestEntries, manifestExists } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, writeFileSync, readFileSync, readdirSync, statSync, existsSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { rmSync, writeFileSync, readFileSync, readdirSync, statSync, existsSync } from "node:fs"; import { join, resolve } from "node:path"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; @@ -24,12 +23,13 @@ import { defineConfig } from "../src/metaobjects-config.js"; import { entityFile } from "../src/generators/entity-file.js"; import { queriesFile } from "../src/generators/queries-file.js"; import type { BaselineMode } from "../src/overwrite-policy.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const FIXTURE = resolve(import.meta.dir, "fixtures", "single-entity.json"); let projectRoot: string; -beforeEach(() => { projectRoot = mkdtempSync(join(tmpdir(), "adopt-baseline-")); }); -afterEach(() => { rmSync(projectRoot, { recursive: true, force: true }); }); +beforeEach(() => { projectRoot = makeScratchDir("adopt-baseline-"); }); +afterEach(() => { removeTree(projectRoot); }); const genStateDir = (): string => join(projectRoot, ".metaobjects", ".gen-state"); const outDir = (): string => join(projectRoot, "generated"); @@ -53,7 +53,7 @@ async function gen(opts: { baseline?: BaselineMode; dryRun?: boolean } = {}) { /** The state of a project that predates the committed manifest: output on disk, no gen-state. */ function dropAllGenState(): void { - rmSync(genStateDir(), { recursive: true, force: true }); + removeTree(genStateDir()); } /** Make every generated file differ from fresh output, as an older engine's output would. */ @@ -166,7 +166,7 @@ describe("--baseline=adopt", () => { for (const e of readdirSync(dir)) { const full = join(dir, e); if (e === ".hashes") continue; // the manifest directory is what a clone keeps - if (statSync(full).isDirectory()) { walk(full); rmSync(full, { recursive: true, force: true }); } + if (statSync(full).isDirectory()) { walk(full); removeTree(full); } else if (e !== ".engine.json") rmSync(full, { force: true }); } }; diff --git a/server/typescript/packages/codegen-ts/test/agent-docs-surface.test.ts b/server/typescript/packages/codegen-ts/test/agent-docs-surface.test.ts index 2ee6d5c7e3..ec57eac899 100644 --- a/server/typescript/packages/codegen-ts/test/agent-docs-surface.test.ts +++ b/server/typescript/packages/codegen-ts/test/agent-docs-surface.test.ts @@ -279,7 +279,7 @@ describe("agent/schema.md", () => { // for that shape. `@where`, `@expr` and `@using` were all already rendered; `orders` was the // one member of the set the input type never carried. test("a DESC index says desc — the ordering is not decoration", async () => { - const page = renderAgentSchemaPage(input({ + const page = renderAgentSchemaPage(await load(MODEL), input({ tables: [{ name: "wake_events", columns: [column("id", { identity: "increment" }), column("ts"), column("device_id")], @@ -290,7 +290,7 @@ describe("agent/schema.md", () => { ], foreignKeys: [], checks: [], primaryKey: ["id"], }], - }), { declaredBy: new Map(), viewLineage: new Map(), relationships: [], enums: [] }); + }), "snake_case"); expect(page).toContain("`ts` desc"); // Mixed directions are per-COLUMN: `(device_id ASC, ts DESC)` is a different index from // `(device_id, ts)`, and a reader deciding whether it serves their ORDER BY needs that. @@ -385,13 +385,8 @@ describe("agent/schema.md", () => { expect(files.has("agent/requirements.md")).toBe(true); }); - test("renders nothing at all for an empty schema", () => { - expect(renderAgentSchemaPage(input({ tables: [], views: [] }), { - declaredBy: new Map(), - viewLineage: new Map(), - relationships: [], - enums: [], - })).toBe(""); + test("renders nothing at all for an empty schema", async () => { + expect(renderAgentSchemaPage(await load(MODEL), input({ tables: [], views: [] }), "snake_case")).toBe(""); }); }); @@ -627,27 +622,44 @@ describe("agent/schema.md — the claims it makes about the model", () => { expect(page).not.toContain("report"); }); - test("the Views intro names a report's dimensions and measures once a report view is on the page", () => { - const fleet = fleetSchema(); - const base = { - ...fleet, - views: [{ name: "v_store_totals" }, { name: "v_owner_summary" }], - provenance: new Map([ - ...fleet.provenance, - ["public.v_store_totals", "acme::shop::StoreTotals"], - ]), - }; - const withReport = renderAgentSchemaPage(base, { - declaredBy: new Map(), viewLineage: new Map(), relationships: [], enums: [], - reportViews: new Set(["public.v_store_totals"]), + test("the Views intro names a report's dimensions and measures once a report view is on the page", async () => { + // The report's view is on the page, so the intro names reports too. The SAME schema + // against a model without the report keeps the pre-report sentence: the wording keys on + // a view-backed `object.report` owning one of the page's views, read from the model. + const billing = (withReport: boolean) => ({ + "metadata.root": { + package: "acme::billing", + children: [ + { "object.entity": { name: "Invoice", children: [ + { "source.rdb": { "@table": "invoices" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "status" } }, + { "identity.primary": { name: "id", "@fields": ["id"] } }, + { "dimension.attribute": { name: "invoiceStatus", "@of": "Invoice.status" } }, + { "measure.aggregate": { name: "invoiceCount", "@agg": "count", "@of": "Invoice.id" } }, + ] } }, + ...(withReport + ? [{ "object.report": { name: "StatusTotals", "@from": "Invoice", + "@dimensions": ["invoiceStatus"], "@measures": ["invoiceCount"], + children: [{ "source.rdb": { "@kind": "view", "@view": "v_status_totals" } }] } }] + : []), + ], + }, }); + const schema: AgentSchemaInput = { + dialect: "postgres", + tables: [], + views: [{ name: "v_status_totals" }], + provenance: new Map([["public.v_status_totals", "acme::billing::StatusTotals"]]), + columnType: () => "TEXT", + qualify: (o) => `${o.schema ?? "public"}.${o.name}`, + }; + const withReport = renderAgentSchemaPage(await load(billing(true)), schema, "snake_case"); expect(withReport).toContain( "A view is generated from its projection's `origin.*` children or its report's dimensions and measures — " + "it is derived, never hand-written. ", ); - const without = renderAgentSchemaPage(base, { - declaredBy: new Map(), viewLineage: new Map(), relationships: [], enums: [], reportViews: new Set(), - }); + const without = renderAgentSchemaPage(await load(billing(false)), schema, "snake_case"); expect(without).toContain("A view is generated from its projection's `origin.*` children — it is derived, never hand-written. "); expect(without).not.toContain("report's"); }); diff --git a/server/typescript/packages/codegen-ts/test/agent-ui-page-parity.test.ts b/server/typescript/packages/codegen-ts/test/agent-ui-page-parity.test.ts index 79be12d2ff..4e9163d88c 100644 --- a/server/typescript/packages/codegen-ts/test/agent-ui-page-parity.test.ts +++ b/server/typescript/packages/codegen-ts/test/agent-ui-page-parity.test.ts @@ -68,8 +68,7 @@ // names collide (this fixture is one package and mount→object is keyed by bare name; // the test refuses a fixture where that key is ambiguous rather than guessing). import { describe, test, expect } from "bun:test"; -import { mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { basename, join } from "node:path"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import type { MetaObject, MetaRoot } from "@metaobjectsdev/metadata"; @@ -84,6 +83,7 @@ import { routesFile } from "../src/generators/routes-file.js"; // while the two still spell different addresses for the fixture's TPH subtype. import { buildPkMap, buildRelationMap, makeRenderContext, resourcePath, restPath, runEmitsUiTier } from "../src/index.js"; import { defineConfig, type Dialect } from "../src/metaobjects-config.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; // The dialect decides column builders, never an address or a form, so one arm suffices. // There is no registered constant for it — `Dialect` is codegen config, not metamodel @@ -328,7 +328,7 @@ function parsePage(page: string): Map { } async function generate(apiPrefix: string): Promise { - const repo = mkdtempSync(join(tmpdir(), "agent-ui-parity-")); + const repo = makeScratchDir("agent-ui-parity-"); try { mkdirSync(join(repo, "metaobjects"), { recursive: true }); const fixture = join(repo, "metaobjects", "meta.fleet.json"); @@ -401,7 +401,7 @@ async function generate(apiPrefix: string): Promise { if (page === undefined) throw new Error(`no ${UI_PAGE} emitted; pages: ${agentPages.map((f) => f.path).join(", ")}`); return { root, ownPaths, routes, forms, page: parsePage(page.content) }; } finally { - rmSync(repo, { recursive: true, force: true }); + removeTree(repo); } } diff --git a/server/typescript/packages/codegen-ts/test/ai-llm-call-codegen.test.ts b/server/typescript/packages/codegen-ts/test/ai-llm-call-codegen.test.ts index d131e5927d..95b02d7476 100644 --- a/server/typescript/packages/codegen-ts/test/ai-llm-call-codegen.test.ts +++ b/server/typescript/packages/codegen-ts/test/ai-llm-call-codegen.test.ts @@ -1,16 +1,16 @@ import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync, readdirSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, readdirSync } from "node:fs"; import { join } from "node:path"; import { runGen, defineConfig } from "../src/index.js"; import { barrel } from "../src/generators/barrel.js"; import { entityFile } from "../src/generators/entity-file.js"; import { queriesFile } from "../src/generators/queries-file.js"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; let tmp: string; -beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "ai-codegen-")); }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +beforeEach(() => { tmp = makeScratchDir("ai-codegen-"); }); +afterEach(() => { removeTree(tmp); }); // --------------------------------------------------------------------------- // Inline model: abstract LlmCallBase with representative field types diff --git a/server/typescript/packages/codegen-ts/test/ai-trace-sti.test.ts b/server/typescript/packages/codegen-ts/test/ai-trace-sti.test.ts index 4fcd9f10fd..95c9c05258 100644 --- a/server/typescript/packages/codegen-ts/test/ai-trace-sti.test.ts +++ b/server/typescript/packages/codegen-ts/test/ai-trace-sti.test.ts @@ -1,6 +1,5 @@ import { describe, test, expect } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { runGen, defineConfig } from "../src/index.js"; import { traceHelperFile } from "../src/generators/index.js"; @@ -11,6 +10,7 @@ import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { buildExpectedSchema } from "@metaobjectsdev/migrate-ts"; import { extract, Format, FieldKind, scalar } from "@metaobjectsdev/render"; import ts from "typescript"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const STI_MODEL = JSON.stringify({ "metadata.root": { package: "t::ai", children: [ { "object.value": { name: "ClassifyReq", children: [{ "field.string": { name: "text" } }] } }, @@ -34,15 +34,15 @@ const STI_MODEL = JSON.stringify({ "metadata.root": { package: "t::ai", children ] } }); async function genTrace(): Promise<{ classify: string; summarize: string }> { - const tmp = mkdtempSync(join(tmpdir(), "ai1c-out-")); - const dir = mkdtempSync(join(tmpdir(), "ai1c-model-")); + const tmp = makeScratchDir("ai1c-out-"); + const dir = makeScratchDir("ai1c-model-"); writeFileSync(join(dir, "m.json"), STI_MODEL); // The REAL shipped base, not a bespoke one named the same: `trace-helper` keys on // the `ai` manifest's anchor and compares by node identity (FR-043 §6), so a fixture // declaring its own `LlmCallBase` is exactly the bypass ADR-0024 warned about — it // proved nothing about the path an adopter follows, and now it does not even fire. const loaded = await MetaDataLoader.fromDirectory(dir, { libraries: ["ai"] }); - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); expect(loaded.errors).toEqual([]); const out = await runGen({ config: defineConfig({ outDir: tmp, extStyle: "none", dbImport: "~/db", dialect: "postgres", @@ -90,11 +90,11 @@ describe("ai-trace — a malformed required response field fails the call", () = const js = ts.transpileModule(`${fnSrc}\nexport { unusableRequired };`, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 }, }).outputText; - const dir = mkdtempSync(join(tmpdir(), "ai-trace-unusable-")); + const dir = makeScratchDir("ai-trace-unusable-"); const modPath = join(dir, "unusable.mjs"); writeFileSync(modPath, js); const mod = (await import(modPath)) as { unusableRequired: (r: unknown) => string | null }; - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); const schema = { format: Format.JSON, @@ -131,14 +131,14 @@ describe("ai-trace — redaction threaded through the generated typed path", () describe("ai-trace #1c — STI table collapse", () => { test("N trace subtypes collapse to one prompt_llm_call table", async () => { - const dir = mkdtempSync(join(tmpdir(), "ai1c-schema-")); + const dir = makeScratchDir("ai1c-schema-"); writeFileSync(join(dir, "m.json"), STI_MODEL); // The REAL shipped base, not a bespoke one named the same: `trace-helper` keys on // the `ai` manifest's anchor and compares by node identity (FR-043 §6), so a fixture // declaring its own `LlmCallBase` is exactly the bypass ADR-0024 warned about — it // proved nothing about the path an adopter follows, and now it does not even fire. const loaded = await MetaDataLoader.fromDirectory(dir, { libraries: ["ai"] }); - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); expect(loaded.errors).toEqual([]); loaded.root.physicalNaming = { columns: "literal", tables: "snake_case" }; diff --git a/server/typescript/packages/codegen-ts/test/api-docs-expose.test.ts b/server/typescript/packages/codegen-ts/test/api-docs-expose.test.ts index 74a1ff688f..a35b97499e 100644 --- a/server/typescript/packages/codegen-ts/test/api-docs-expose.test.ts +++ b/server/typescript/packages/codegen-ts/test/api-docs-expose.test.ts @@ -8,12 +8,12 @@ import { buildApiModel } from "../src/generators/api-model.js"; import { routesFile } from "../src/generators/routes-file.js"; import { routesFileHono } from "../src/generators/routes-file-hono.js"; import { runRoutesExpose } from "../src/ui-tier-gate.js"; -import { mkdtempSync, readFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync } from "node:fs"; import { join } from "node:path"; import { runGen } from "../src/runner.js"; import { defineConfig } from "../src/metaobjects-config.js"; import { apiDocsFile } from "../src/generators/api-docs-file.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const ENTITY = (name: string, table: string) => ({ "object.entity": { @@ -209,7 +209,7 @@ describe("a routes generator's filter also removes a read-only surface it does n describe("through meta gen: the written api pages list only the mounted verbs", () => { async function pages(generators: Parameters[0]["generators"]) { const root = await loadRoot(); - const tmp = mkdtempSync(join(tmpdir(), "api-docs-expose-")); + const tmp = makeScratchDir("api-docs-expose-"); try { const { warnings } = await runGen({ config: defineConfig({ @@ -219,7 +219,7 @@ describe("through meta gen: the written api pages list only the mounted verbs", metadata: root, projectRoot: tmp, }); return { product: readFileSync(join(tmp, "docs", "api", "acme", "shop", "Product.md"), "utf8"), warnings }; - } finally { rmSync(tmp, { recursive: true, force: true }); } + } finally { removeTree(tmp); } } test("expose omitting create/update/delete: write routes are not documented; default is unchanged", async () => { diff --git a/server/typescript/packages/codegen-ts/test/api-docs-surfaces.test.ts b/server/typescript/packages/codegen-ts/test/api-docs-surfaces.test.ts index d2d54e2b14..72c22aa56e 100644 --- a/server/typescript/packages/codegen-ts/test/api-docs-surfaces.test.ts +++ b/server/typescript/packages/codegen-ts/test/api-docs-surfaces.test.ts @@ -8,8 +8,7 @@ import { buildApiModel } from "../src/generators/api-model.js"; import { queriesFile } from "../src/generators/queries-file.js"; import { routesFile } from "../src/generators/routes-file.js"; import { routesFileHono } from "../src/generators/routes-file-hono.js"; -import { mkdtempSync, readFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync } from "node:fs"; import { join } from "node:path"; import { runGen } from "../src/runner.js"; import { defineConfig } from "../src/metaobjects-config.js"; @@ -17,6 +16,7 @@ import { apiDocsFile } from "../src/generators/api-docs-file.js"; import { entityFile } from "../src/generators/entity-file.js"; import { docsFile } from "../src/generators/docs-file.js"; import { runEmitsEntityModule, runEmitsQueries, runEmitsRestRoutes } from "../src/ui-tier-gate.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; async function loadRoot() { const res = await new MetaDataLoader().load([ @@ -111,7 +111,7 @@ describe("what the run's generators say they write", () => { describe("through meta gen: the written pages follow the generator list", () => { async function page(generators: Parameters[0]["generators"]): Promise { const root = await loadRoot(); - const tmp = mkdtempSync(join(tmpdir(), "api-docs-surfaces-")); + const tmp = makeScratchDir("api-docs-surfaces-"); try { await runGen({ config: defineConfig({ @@ -121,7 +121,7 @@ describe("through meta gen: the written pages follow the generator list", () => metadata: root, projectRoot: tmp, }); return readFileSync(join(tmp, "docs", "api", "acme", "shop", "Product.md"), "utf8"); - } finally { rmSync(tmp, { recursive: true, force: true }); } + } finally { removeTree(tmp); } } test("entity and docs only: neither the queries nor the routes are described", async () => { diff --git a/server/typescript/packages/codegen-ts/test/array-default-compile.test.ts b/server/typescript/packages/codegen-ts/test/array-default-compile.test.ts index da6c7fdbe8..5de787e4a0 100644 --- a/server/typescript/packages/codegen-ts/test/array-default-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/array-default-compile.test.ts @@ -15,7 +15,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; @@ -25,6 +25,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { GenContext } from "../src/generator.js"; import type { Dialect } from "../src/metaobjects-config.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -106,7 +107,7 @@ async function genAndCompile(dialect: Dialect): Promise f.path)); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } diff --git a/server/typescript/packages/codegen-ts/test/assigned-pk-insert-compile.test.ts b/server/typescript/packages/codegen-ts/test/assigned-pk-insert-compile.test.ts index 5569dae961..bdcf3752f5 100644 --- a/server/typescript/packages/codegen-ts/test/assigned-pk-insert-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/assigned-pk-insert-compile.test.ts @@ -20,7 +20,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; @@ -31,6 +31,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { GenContext } from "../src/generator.js"; import type { Dialect } from "../src/metaobjects-config.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -114,7 +115,7 @@ async function genAndCompile( ts.flattenDiagnosticMessageText(d.messageText, "\n"), ); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } diff --git a/server/typescript/packages/codegen-ts/test/barrel-layout.test.ts b/server/typescript/packages/codegen-ts/test/barrel-layout.test.ts index fd5f0fe80b..b47d718b3b 100644 --- a/server/typescript/packages/codegen-ts/test/barrel-layout.test.ts +++ b/server/typescript/packages/codegen-ts/test/barrel-layout.test.ts @@ -4,7 +4,7 @@ // against either. Pinned here because the CHANGELOG's upgrade note says so. import { describe, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import ts from "typescript"; import { InMemoryStringSource, MetaDataLoader, type MetaObject } from "@metaobjectsdev/metadata"; @@ -17,6 +17,7 @@ import { buildRelationMap } from "../src/relation-resolver.js"; import { resolveTargets } from "../src/metaobjects-config.js"; import type { EmittedFile, GenContext } from "../src/generator.js"; import type { OutputLayout } from "../src/import-path.js"; +import { removeTree } from "../src/scratch-dir.js"; const pk = { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }; const MODEL = { "metadata.root": { package: "acme::blog", children: [ @@ -78,7 +79,7 @@ function compile(files: EmittedFile[]): string[] { return ts.getPreEmitDiagnostics(program).map((d) => `${d.file?.fileName.slice(dir.length + 1) ?? ""} ${ts.flattenDiagnosticMessageText(d.messageText, "\n")}`); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } diff --git a/server/typescript/packages/codegen-ts/test/baseline-fresh-stale-snapshot.test.ts b/server/typescript/packages/codegen-ts/test/baseline-fresh-stale-snapshot.test.ts index 5d37d3de0e..26e0a48f06 100644 --- a/server/typescript/packages/codegen-ts/test/baseline-fresh-stale-snapshot.test.ts +++ b/server/typescript/packages/codegen-ts/test/baseline-fresh-stale-snapshot.test.ts @@ -8,8 +8,7 @@ import { removeManifest, seedLegacyManifest } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, writeFileSync, readFileSync, readdirSync, statSync, existsSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { writeFileSync, readFileSync, readdirSync, statSync, existsSync } from "node:fs"; import { join, resolve } from "node:path"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; @@ -18,12 +17,13 @@ import { defineConfig } from "../src/metaobjects-config.js"; import { entityFile } from "../src/generators/entity-file.js"; import { queriesFile } from "../src/generators/queries-file.js"; import type { BaselineMode } from "../src/overwrite-policy.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const FIXTURE = resolve(import.meta.dir, "fixtures", "single-entity.json"); let projectRoot: string; -beforeEach(() => { projectRoot = mkdtempSync(join(tmpdir(), "adopt-baseline-")); }); -afterEach(() => { rmSync(projectRoot, { recursive: true, force: true }); }); +beforeEach(() => { projectRoot = makeScratchDir("adopt-baseline-"); }); +afterEach(() => { removeTree(projectRoot); }); const genStateDir = (): string => join(projectRoot, ".metaobjects", ".gen-state"); const outDir = (): string => join(projectRoot, "generated"); diff --git a/server/typescript/packages/codegen-ts/test/check-constraint-name-parity.test.ts b/server/typescript/packages/codegen-ts/test/check-constraint-name-parity.test.ts index b98c743776..227478be74 100644 --- a/server/typescript/packages/codegen-ts/test/check-constraint-name-parity.test.ts +++ b/server/typescript/packages/codegen-ts/test/check-constraint-name-parity.test.ts @@ -19,8 +19,7 @@ // This test exists because nothing compared the two emitters. Each was internally // consistent and separately tested, which is precisely how the divergence survived. import { describe, test, expect } from "bun:test"; -import { mkdtempSync, rmSync, writeFileSync, mkdirSync, readdirSync, readFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { writeFileSync, mkdirSync, readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; @@ -29,6 +28,7 @@ import { runGen } from "../src/runner.js"; import { namesFile } from "../src/generators/index.js"; import { entityFile } from "../src/generators/entity-file.js"; import { defineConfig } from "../src/metaobjects-config.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const META = JSON.stringify({ "metadata.root": { @@ -50,7 +50,7 @@ const META = JSON.stringify({ }); async function bothNames(includeNames = false): Promise<{ codegen: string[]; migrate: string[] }> { - const repo = mkdtempSync(join(tmpdir(), "chk-parity-")); + const repo = makeScratchDir("chk-parity-"); try { mkdirSync(join(repo, "metaobjects"), { recursive: true }); const fixture = join(repo, "metaobjects", "meta.chk.json"); @@ -103,7 +103,7 @@ async function bothNames(includeNames = false): Promise<{ codegen: string[]; mig return { codegen, migrate }; } finally { - rmSync(repo, { recursive: true, force: true }); + removeTree(repo); } } diff --git a/server/typescript/packages/codegen-ts/test/codegen-compile-conformance.test.ts b/server/typescript/packages/codegen-ts/test/codegen-compile-conformance.test.ts index 33238de5f3..70470c9012 100644 --- a/server/typescript/packages/codegen-ts/test/codegen-compile-conformance.test.ts +++ b/server/typescript/packages/codegen-ts/test/codegen-compile-conformance.test.ts @@ -31,7 +31,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync, readdirSync, statSync } from "node:fs"; +import { mkdtempSync, writeFileSync, readdirSync, statSync } from "node:fs"; import { join, resolve, dirname } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import ts from "typescript"; @@ -50,6 +50,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { GenContext } from "../src/generator.js"; import { runGen, defineConfig } from "../src/index.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -244,7 +245,7 @@ describe("codegen-compile conformance — the shared fitness corpus", () => { }); expect(diagnostics).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); } @@ -313,7 +314,7 @@ describe("codegen-compile conformance — the shared fitness corpus, package lay }); expect(diagnostics).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); } diff --git a/server/typescript/packages/codegen-ts/test/codegen-dialect-validation.test.ts b/server/typescript/packages/codegen-ts/test/codegen-dialect-validation.test.ts index 9a1b1cf257..8f57f4d240 100644 --- a/server/typescript/packages/codegen-ts/test/codegen-dialect-validation.test.ts +++ b/server/typescript/packages/codegen-ts/test/codegen-dialect-validation.test.ts @@ -2,12 +2,11 @@ // switch and emit `pgTable` code, silently. `"d1"` is the common case: it is a `meta migrate` // transport, and D1 codegen is `"sqlite"`. Both choke points (normalizeConfig, runGen) refuse it. import { describe, test, expect } from "bun:test"; -import { mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { runGen } from "../src/runner.js"; import { normalizeConfig, assertCodegenDialect, CODEGEN_DIALECTS, type MetaobjectsGenConfig } from "../src/metaobjects-config.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const base = { outDir: "gen", generators: [] } as unknown as MetaobjectsGenConfig; @@ -49,7 +48,7 @@ describe("normalizeConfig", () => { describe("runGen", () => { test('refuses dialect "d1" for a project with a sourced object, before writing anything', async () => { - const tmp = mkdtempSync(join(tmpdir(), "codegen-dialect-")); + const tmp = makeScratchDir("codegen-dialect-"); try { const json = JSON.stringify({ "metadata.root": { package: "app", children: [ { "object.entity": { name: "Note", children: [ @@ -61,6 +60,6 @@ describe("runGen", () => { await expect( runGen({ metadata: root, projectRoot: tmp, config: { ...base, outDir: "gen", dialect: "d1" } as unknown as MetaobjectsGenConfig }), ).rejects.toThrow(/invalid codegen dialect "d1"/); - } finally { rmSync(tmp, { recursive: true, force: true }); } + } finally { removeTree(tmp); } }); }); diff --git a/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts b/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts index cc1773e117..a54731dee0 100644 --- a/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts +++ b/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts @@ -3,8 +3,6 @@ // not vary. The corpus proves the bytes hold. This file proves the bytes mean what the docs say. import { describe, expect, test } from "bun:test"; -import { mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; import { join } from "node:path"; import type { MetaObject } from "@metaobjectsdev/metadata"; import { type ContractCase, contractCases, contractTree, loadCaseModel } from "../../scripts/gen-contract-conformance.js"; @@ -15,6 +13,7 @@ import { defineConfig, type Generator, runGen } from "../../src/index.js"; import { jsonSchemaFile as refJsonSchemaFile } from "../../src/reference/contract-schema.js"; import { openApiFile as refOpenApiFile } from "../../src/reference/openapi.js"; import { ajvOver, danglingRefs, type JsonDoc } from "./contract-validators.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; const CASES = new Map(contractCases().map((c) => [c.name, c])); @@ -32,7 +31,7 @@ interface RunOptions { async function emit(c: ContractCase, generators: Generator[], run: RunOptions = {}): Promise> { const root = await loadCaseModel(c); - const dir = mkdtempSync(join(tmpdir(), "contract-behaviour-")); + const dir = makeScratchDir("contract-behaviour-"); try { const outDir = join(dir, "out"); await runGen({ @@ -50,7 +49,7 @@ async function emit(c: ContractCase, generators: Generator[], run: RunOptions = }); return readTree(outDir); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } diff --git a/server/typescript/packages/codegen-ts/test/cube/cube-model-generator.test.ts b/server/typescript/packages/codegen-ts/test/cube/cube-model-generator.test.ts index f5203ba8f8..6fd7df4792 100644 --- a/server/typescript/packages/codegen-ts/test/cube/cube-model-generator.test.ts +++ b/server/typescript/packages/codegen-ts/test/cube/cube-model-generator.test.ts @@ -7,8 +7,7 @@ // loader and run through runGen. import { afterEach, beforeEach, describe, expect, test } from "bun:test"; -import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdtempSync, readdirSync, readFileSync, statSync } from "node:fs"; import { join, relative } from "node:path"; import { InMemoryStringSource, MetaDataLoader, type MetaObject, type MetaRoot } from "@metaobjectsdev/metadata"; import { defineConfig, runGen, type MetaobjectsGenConfig } from "../../src/index.js"; @@ -16,15 +15,16 @@ import { buildCubeModel } from "../../src/cube/build-cube-model.js"; import { CubeModelError, ERR_CUBE_UNSUPPORTED_DIALECT } from "../../src/cube/cube-errors.js"; import { renderCubeYaml } from "../../src/cube/cube-yaml.js"; import { cubeModel } from "../../src/generators/cube-model.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; type Json = Record; let tmp: string; beforeEach(() => { - tmp = mkdtempSync(join(tmpdir(), "cube-model-gen-")); + tmp = makeScratchDir("cube-model-gen-"); }); afterEach(() => { - rmSync(tmp, { recursive: true, force: true }); + removeTree(tmp); }); function entity(name: string, children: Json[], extra: Json = {}): Json { diff --git a/server/typescript/packages/codegen-ts/test/cube/cube-model-orphans.test.ts b/server/typescript/packages/codegen-ts/test/cube/cube-model-orphans.test.ts index 1f75e10c53..9bacffeebc 100644 --- a/server/typescript/packages/codegen-ts/test/cube/cube-model-orphans.test.ts +++ b/server/typescript/packages/codegen-ts/test/cube/cube-model-orphans.test.ts @@ -18,13 +18,13 @@ // reconciles, so none of this is visible to the golden tests. import { afterEach, beforeEach, describe, expect, test } from "bun:test"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { InMemoryStringSource, MetaDataLoader, type MetaRoot } from "@metaobjectsdev/metadata"; import { defineConfig, runGen, type Generator } from "../../src/index.js"; import { cubeModel as builtinCubeModel, ownsCubeFile } from "../../src/generators/cube-model.js"; import { cubeModel as refCubeModel } from "../../src/reference/cube-model.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; type Json = Record; @@ -76,10 +76,10 @@ for (const impl of IMPLEMENTATIONS) { describe(`cube-model orphan cleanup, through runGen: ${impl.label}`, () => { let projectRoot: string; beforeEach(() => { - projectRoot = mkdtempSync(join(tmpdir(), "cube-orphan-e2e-")); + projectRoot = makeScratchDir("cube-orphan-e2e-"); }); afterEach(() => { - rmSync(projectRoot, { recursive: true, force: true }); + removeTree(projectRoot); }); const abs = (rel: string): string => join(projectRoot, rel); @@ -263,10 +263,10 @@ for (const impl of IMPLEMENTATIONS) { describe(`cube-model view cleanup, through runGen: ${impl.label}`, () => { let projectRoot: string; beforeEach(() => { - projectRoot = mkdtempSync(join(tmpdir(), "cube-orphan-view-")); + projectRoot = makeScratchDir("cube-orphan-view-"); }); afterEach(() => { - rmSync(projectRoot, { recursive: true, force: true }); + removeTree(projectRoot); }); const abs = (rel: string): string => join(projectRoot, rel); const VIEW = join(OUT_DIR, "model", "views", "ProgramRoster.yml"); diff --git a/server/typescript/packages/codegen-ts/test/db-schema-generic-compile.test.ts b/server/typescript/packages/codegen-ts/test/db-schema-generic-compile.test.ts index a64b5fb2ab..45f9b22597 100644 --- a/server/typescript/packages/codegen-ts/test/db-schema-generic-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/db-schema-generic-compile.test.ts @@ -34,7 +34,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; @@ -45,6 +45,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { GenContext } from "../src/generator.js"; import type { Dialect } from "../src/metaobjects-config.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -157,7 +158,7 @@ async function genAndCompile(dialect: Dialect, withSchema: boolean): Promise f.path), "consumer.ts"]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } diff --git a/server/typescript/packages/codegen-ts/test/decimal-vo-e2e.test.ts b/server/typescript/packages/codegen-ts/test/decimal-vo-e2e.test.ts index 74ddb6de22..58f5bfee73 100644 --- a/server/typescript/packages/codegen-ts/test/decimal-vo-e2e.test.ts +++ b/server/typescript/packages/codegen-ts/test/decimal-vo-e2e.test.ts @@ -3,7 +3,7 @@ // @precision / @scale, stored and answered as the canonical string. Generated code executed. import { describe, test, expect, beforeAll, afterAll } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { Database } from "bun:sqlite"; @@ -14,6 +14,7 @@ import { MetaDataLoader, InMemoryStringSource, type MetaObject } from "@metaobje import { mountCrudRoutes } from "@metaobjectsdev/runtime-ts/hono"; import { renderZodValidators, renderInsertSchemaOnly } from "../src/templates/zod-validators.js"; import { renderFilterAllowlist } from "../src/templates/filter-allowlist.js"; +import { removeTree } from "../src/scratch-dir.js"; const MODEL = { "metadata.root": { package: "ledger", children: [ @@ -39,7 +40,7 @@ const invoices = sqliteTable("invoices", { }); const dir = mkdtempSync(join(import.meta.dir, "tmp-decimal-vo-")); -afterAll(() => rmSync(dir, { recursive: true, force: true })); +afterAll(() => removeTree(dir)); async function execute(name: string, source: string): Promise> { const file = join(dir, `${name}.ts`); diff --git a/server/typescript/packages/codegen-ts/test/decimal-wire-e2e.test.ts b/server/typescript/packages/codegen-ts/test/decimal-wire-e2e.test.ts index 19365ae882..29b84f80f7 100644 --- a/server/typescript/packages/codegen-ts/test/decimal-wire-e2e.test.ts +++ b/server/typescript/packages/codegen-ts/test/decimal-wire-e2e.test.ts @@ -8,7 +8,7 @@ // is a double. Exactness beyond 15 digits is the Postgres and MySQL lanes' to prove. import { describe, test, expect, beforeAll, afterAll } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { Database } from "bun:sqlite"; @@ -20,6 +20,7 @@ import { mountCrudRoutes } from "@metaobjectsdev/runtime-ts/hono"; import { renderZodValidators } from "../src/templates/zod-validators.js"; import { renderFilterAllowlist } from "../src/templates/filter-allowlist.js"; import { decimalColumnsLine, decimalFieldNames } from "../src/api-surface.js"; +import { removeTree } from "../src/scratch-dir.js"; const MODEL = { "metadata.root": { package: "ledger", children: [ @@ -44,7 +45,7 @@ const entries = sqliteTable("entries", { }); const dir = mkdtempSync(join(import.meta.dir, "tmp-decimal-")); -afterAll(() => rmSync(dir, { recursive: true, force: true })); +afterAll(() => removeTree(dir)); async function execute(name: string, source: string): Promise> { const file = join(dir, `${name}.ts`); diff --git a/server/typescript/packages/codegen-ts/test/declared-index-name-cut.test.ts b/server/typescript/packages/codegen-ts/test/declared-index-name-cut.test.ts index 7aa3a2efff..ca42b592a9 100644 --- a/server/typescript/packages/codegen-ts/test/declared-index-name-cut.test.ts +++ b/server/typescript/packages/codegen-ts/test/declared-index-name-cut.test.ts @@ -6,19 +6,19 @@ // is migrate's answer (written by migrate-ts's runner), and the C# EF context and the Kotlin // Exposed table pass the same file. import { describe, test, expect } from "bun:test"; -import { mkdtempSync, rmSync, readdirSync, readFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readdirSync, readFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; import { runGen } from "../src/runner.js"; import { entityFile } from "../src/generators/entity-file.js"; import { defineConfig } from "../src/metaobjects-config.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const CORPUS = resolve(import.meta.dir, "../../../../../fixtures/foreign-key-index-conformance"); async function generated(dialect: "postgres" | "sqlite"): Promise { - const repo = mkdtempSync(join(tmpdir(), "declared-index-cut-")); + const repo = makeScratchDir("declared-index-cut-"); try { const { root, errors } = await new MetaDataLoader().load([new FileSource(join(CORPUS, "input", "meta.fk.json"))]); expect(errors).toEqual([]); @@ -33,7 +33,7 @@ async function generated(dialect: "postgres" | "sqlite"): Promise { .map((f) => readFileSync(join(outDir, f), "utf8")) .join("\n"); } finally { - rmSync(repo, { recursive: true, force: true }); + removeTree(repo); } } diff --git a/server/typescript/packages/codegen-ts/test/docs-site-explorer.test.ts b/server/typescript/packages/codegen-ts/test/docs-site-explorer.test.ts index b343a604d1..86f4c24a04 100644 --- a/server/typescript/packages/codegen-ts/test/docs-site-explorer.test.ts +++ b/server/typescript/packages/codegen-ts/test/docs-site-explorer.test.ts @@ -2,8 +2,7 @@ // the requirement ledger the caller hands the run, the files the run wrote and the routes it // mounts. It runs after the generators declared beside it, whatever their order. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { MetaDataLoader, type MetaRoot } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; @@ -11,6 +10,7 @@ import { runGen } from "../src/runner.js"; import { defineConfig } from "../src/metaobjects-config.js"; import type { Generator } from "../src/generator.js"; import { docsSiteFile, entityFile, routesFile } from "../src/generators/index.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const FIXTURE = resolve(import.meta.dir, "fixtures", "single-entity.json"); @@ -25,13 +25,13 @@ let root: MetaRoot; // The run's one metadata source directory (the classic site loads whole directories). let sources: string; beforeEach(async () => { - tmp = mkdtempSync(join(tmpdir(), "codegen-docs-site-")); + tmp = makeScratchDir("codegen-docs-site-"); sources = join(tmp, "metaobjects"); mkdirSync(sources); copyFileSync(FIXTURE, join(sources, "meta.blog.json")); root = (await new MetaDataLoader().load([new FileSource(FIXTURE)])).root; }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +afterEach(() => { removeTree(tmp); }); const config = (generators: Generator[]) => defineConfig({ diff --git a/server/typescript/packages/codegen-ts/test/drizzle-duration-column.test.ts b/server/typescript/packages/codegen-ts/test/drizzle-duration-column.test.ts index f7a0bd9ecd..6bc3ea2a24 100644 --- a/server/typescript/packages/codegen-ts/test/drizzle-duration-column.test.ts +++ b/server/typescript/packages/codegen-ts/test/drizzle-duration-column.test.ts @@ -6,7 +6,7 @@ import { describe, test, expect } from "bun:test"; import { Database } from "bun:sqlite"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import ts from "typescript"; @@ -17,6 +17,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { GenContext } from "../src/generator.js"; import type { Dialect } from "../src/metaobjects-config.js"; +import { removeTree } from "../src/scratch-dir.js"; async function loadRoot() { const json = JSON.stringify({ @@ -133,7 +134,7 @@ describe("generated field.duration columns", () => { const diagnostics = compile(dir, files.map((f) => f.path)); expect(diagnostics.map((d) => ts.flattenDiagnosticMessageText(d.messageText, "\n"))).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); } @@ -178,7 +179,7 @@ describe("generated field.duration columns", () => { expect(byMicros).toEqual([{ id: 2 }]); sqlite.close(); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); }); diff --git a/server/typescript/packages/codegen-ts/test/dry-run-reports-refusals.test.ts b/server/typescript/packages/codegen-ts/test/dry-run-reports-refusals.test.ts index 00c945461d..6985563d4a 100644 --- a/server/typescript/packages/codegen-ts/test/dry-run-reports-refusals.test.ts +++ b/server/typescript/packages/codegen-ts/test/dry-run-reports-refusals.test.ts @@ -12,20 +12,20 @@ import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { manifestExists } from "./support/manifest.js"; -import { mkdtempSync, rmSync, writeFileSync, existsSync, readFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { rmSync, writeFileSync, existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { decideAndWrite, previewWriteStatus } from "../src/overwrite-policy.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; let tmp: string; let state: string; beforeEach(() => { - tmp = mkdtempSync(join(tmpdir(), "dry-preview-")); - state = mkdtempSync(join(tmpdir(), "dry-preview-state-")); + tmp = makeScratchDir("dry-preview-"); + state = makeScratchDir("dry-preview-state-"); }); afterEach(() => { - rmSync(tmp, { recursive: true, force: true }); - rmSync(state, { recursive: true, force: true }); + removeTree(tmp); + removeTree(state); }); const opts = () => ({ genStateDir: state, outputRelPath: "User.ts" }); diff --git a/server/typescript/packages/codegen-ts/test/dry-run-writes-nothing.test.ts b/server/typescript/packages/codegen-ts/test/dry-run-writes-nothing.test.ts index e1180bdfa8..833111d77a 100644 --- a/server/typescript/packages/codegen-ts/test/dry-run-writes-nothing.test.ts +++ b/server/typescript/packages/codegen-ts/test/dry-run-writes-nothing.test.ts @@ -10,13 +10,13 @@ // plausible; the disk was the thing that disagreed with it. import { describe, test, expect, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, existsSync, readdirSync, writeFileSync, readFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { rmSync, existsSync, readdirSync, writeFileSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { runGen } from "../src/runner.js"; import { defineConfig } from "../src/metaobjects-config.js"; import { entityFile } from "../src/reference/entity.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const META = JSON.stringify({ "metadata.root": { @@ -39,11 +39,11 @@ const META = JSON.stringify({ const dirs: string[] = []; afterEach(() => { - while (dirs.length > 0) rmSync(dirs.pop()!, { recursive: true, force: true }); + while (dirs.length > 0) removeTree(dirs.pop()!); }); function scratch(): string { - const d = mkdtempSync(join(tmpdir(), "meta-dryrun-")); + const d = makeScratchDir("meta-dryrun-"); dirs.push(d); return d; } diff --git a/server/typescript/packages/codegen-ts/test/empty-generator-reported.test.ts b/server/typescript/packages/codegen-ts/test/empty-generator-reported.test.ts index 981390e63c..bb977af4c9 100644 --- a/server/typescript/packages/codegen-ts/test/empty-generator-reported.test.ts +++ b/server/typescript/packages/codegen-ts/test/empty-generator-reported.test.ts @@ -12,12 +12,13 @@ // standing condition they cannot satisfy. import { describe, test, expect } from "bun:test"; -import { mkdtempSync, rmSync } from "node:fs"; +import { mkdtempSync } from "node:fs"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { runGen, defineConfig } from "../src/index.js"; import { entityFile } from "../src/generators/entity-file.js"; import { namesFile } from "../src/generators/index.js"; +import { removeTree } from "../src/scratch-dir.js"; /** A value object only: nothing DB-backed, so the names generator matches nothing. */ const NO_DB_MODEL = { @@ -69,7 +70,7 @@ async function warningsFor(model: unknown): Promise { }); return r.warnings; } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } @@ -104,7 +105,7 @@ describe("a wired generator that matched nothing is reported", () => { }); expect(Array.isArray(r.warnings)).toBe(true); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); }); diff --git a/server/typescript/packages/codegen-ts/test/engine-version-stamp.test.ts b/server/typescript/packages/codegen-ts/test/engine-version-stamp.test.ts index 8c2410cda2..e22772f80e 100644 --- a/server/typescript/packages/codegen-ts/test/engine-version-stamp.test.ts +++ b/server/typescript/packages/codegen-ts/test/engine-version-stamp.test.ts @@ -3,14 +3,14 @@ // stamp is a separate file from the `.hashes/` manifest and never affects the three-way merge. import { manifestExists } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { loadEngineVersion, saveEngineVersion } from "../src/overwrite-policy.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; let state: string; -beforeEach(() => { state = mkdtempSync(join(tmpdir(), "codegen-engine-")); }); -afterEach(() => { rmSync(state, { recursive: true, force: true }); }); +beforeEach(() => { state = makeScratchDir("codegen-engine-"); }); +afterEach(() => { removeTree(state); }); describe("#232 — gen-state engine-version stamp", () => { test("unstamped gen-state → loadEngineVersion is undefined (pre-#232 / fresh project)", () => { diff --git a/server/typescript/packages/codegen-ts/test/entity-tier-collision.test.ts b/server/typescript/packages/codegen-ts/test/entity-tier-collision.test.ts index d8905fe6a2..d35dd766eb 100644 --- a/server/typescript/packages/codegen-ts/test/entity-tier-collision.test.ts +++ b/server/typescript/packages/codegen-ts/test/entity-tier-collision.test.ts @@ -1,12 +1,12 @@ import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, readdirSync, readFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readdirSync, readFileSync } from "node:fs"; import { join, relative } from "node:path"; import { runGen } from "../src/runner.js"; import { defineConfig } from "../src/metaobjects-config.js"; import { entityFile } from "../src/generators/entity-file.js"; import { barrel } from "../src/generators/barrel.js"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; // ADR-0044 / #228, amended — two same-short-name `object.value`s across // packages. Nothing is renamed: under the package layout each `Note` is declared under its own @@ -27,8 +27,8 @@ async function loadMultiPackageRoot(files: { package: string; children: unknown[ } let tmp: string; -beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "entity-collision-")); }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +beforeEach(() => { tmp = makeScratchDir("entity-collision-"); }); +afterEach(() => { removeTree(tmp); }); async function genFiles( root: Awaited>, diff --git a/server/typescript/packages/codegen-ts/test/exact-optional-property-types-compile.test.ts b/server/typescript/packages/codegen-ts/test/exact-optional-property-types-compile.test.ts index 145cd36cbd..73386920e6 100644 --- a/server/typescript/packages/codegen-ts/test/exact-optional-property-types-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/exact-optional-property-types-compile.test.ts @@ -16,7 +16,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource, type MetaObject } from "@metaobjectsdev/metadata"; @@ -30,6 +30,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { GenContext } from "../src/generator.js"; import type { Dialect } from "../src/metaobjects-config.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -158,7 +159,7 @@ async function generateAndCompile( return `${where}${ts.flattenDiagnosticMessageText(d.messageText, "\n")}`; }); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } diff --git a/server/typescript/packages/codegen-ts/test/extract-tier-collision.test.ts b/server/typescript/packages/codegen-ts/test/extract-tier-collision.test.ts index d4a9844cc4..4c750f9a24 100644 --- a/server/typescript/packages/codegen-ts/test/extract-tier-collision.test.ts +++ b/server/typescript/packages/codegen-ts/test/extract-tier-collision.test.ts @@ -17,7 +17,7 @@ // resolves it via `resolveObjectRef` when (and only when) the payload's own name is shared. import { describe, test, expect, afterAll } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync, readFileSync, readdirSync } from "node:fs"; +import { mkdtempSync, writeFileSync, readFileSync, readdirSync } from "node:fs"; import { join, relative, resolve } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { runGen } from "../src/runner.js"; @@ -25,6 +25,7 @@ import { defineConfig } from "../src/metaobjects-config.js"; import { entityFile } from "../src/generators/entity-file.js"; import { outputParser } from "../src/generators/output-parser-file.js"; import { extractor } from "../src/generators/extractor-file.js"; +import { removeTree } from "../src/scratch-dir.js"; const CORPUS = resolve( import.meta.dir, @@ -33,7 +34,7 @@ const CORPUS = resolve( const TEMP_DIRS: string[] = []; afterAll(() => { - for (const d of TEMP_DIRS) rmSync(d, { recursive: true, force: true }); + for (const d of TEMP_DIRS) removeTree(d); }); async function loadCorpusRoot() { diff --git a/server/typescript/packages/codegen-ts/test/extractor-codegen.test.ts b/server/typescript/packages/codegen-ts/test/extractor-codegen.test.ts index ad6eb186c7..259172e08a 100644 --- a/server/typescript/packages/codegen-ts/test/extractor-codegen.test.ts +++ b/server/typescript/packages/codegen-ts/test/extractor-codegen.test.ts @@ -12,7 +12,7 @@ import { describe, test, expect, afterAll, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; @@ -23,6 +23,7 @@ import { makeRenderContext } from "../src/render-context.js"; import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { GenContext } from "../src/generator.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -126,7 +127,7 @@ declare module "@metaobjectsdev/render" { const TEMP_DIRS: string[] = []; afterAll(() => { - for (const d of TEMP_DIRS) rmSync(d, { recursive: true, force: true }); + for (const d of TEMP_DIRS) removeTree(d); }); async function loadRoot(children: unknown[]) { diff --git a/server/typescript/packages/codegen-ts/test/field-map.test.ts b/server/typescript/packages/codegen-ts/test/field-map.test.ts index c4a7cd5597..095481533e 100644 --- a/server/typescript/packages/codegen-ts/test/field-map.test.ts +++ b/server/typescript/packages/codegen-ts/test/field-map.test.ts @@ -12,6 +12,7 @@ import { renderEntityFile } from "../src/templates/entity-file.js"; import { makeRenderContext } from "../src/render-context.js"; import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; +import { makeScratchDir } from "../src/scratch-dir.js"; const FIXTURE = resolve(import.meta.dir, "fixtures/field-map.yaml"); @@ -63,10 +64,9 @@ describe("field.map loader validation", () => { - field.string: { name: kind } `; const loader = new MetaDataLoader(); - const { writeFileSync, mkdtempSync } = await import("node:fs"); - const { tmpdir } = await import("node:os"); + const { writeFileSync } = await import("node:fs"); const { join } = await import("node:path"); - const dir = mkdtempSync(join(tmpdir(), "fieldmap-")); + const dir = makeScratchDir("fieldmap-"); const f = join(dir, "m.yaml"); writeFileSync(f, yaml); return loader.load([new FileSource(f)]); diff --git a/server/typescript/packages/codegen-ts/test/filter-type-enum-compile.test.ts b/server/typescript/packages/codegen-ts/test/filter-type-enum-compile.test.ts index 59acada456..1f213d567c 100644 --- a/server/typescript/packages/codegen-ts/test/filter-type-enum-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/filter-type-enum-compile.test.ts @@ -14,7 +14,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; @@ -23,6 +23,7 @@ import { makeRenderContext } from "../src/render-context.js"; import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { GenContext } from "../src/generator.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -130,7 +131,7 @@ describe("Filter types an enum filter value as the enum's member union", }); expect(diagnostics).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); }); diff --git a/server/typescript/packages/codegen-ts/test/flattened-reference-compile.test.ts b/server/typescript/packages/codegen-ts/test/flattened-reference-compile.test.ts index 9ead87cb59..67562377d7 100644 --- a/server/typescript/packages/codegen-ts/test/flattened-reference-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/flattened-reference-compile.test.ts @@ -14,7 +14,7 @@ import { describe, expect, test, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { InMemoryStringSource, MetaDataLoader, type MetaObject, type MetaRoot } from "@metaobjectsdev/metadata"; @@ -28,6 +28,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import { buildProjectionViews } from "../src/projection/build-projection-views.js"; import type { EmittedFile, GenContext } from "../src/generator.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -98,7 +99,7 @@ describe("a reference over a flattened value-object member", () => { `${d.file?.fileName.slice(dir.length + 1) ?? ""} ${ts.flattenDiagnosticMessageText(d.messageText, "\n")}`); expect(diagnostics).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); diff --git a/server/typescript/packages/codegen-ts/test/flattened-storage-e2e.test.ts b/server/typescript/packages/codegen-ts/test/flattened-storage-e2e.test.ts index 5262d941ec..267d694738 100644 --- a/server/typescript/packages/codegen-ts/test/flattened-storage-e2e.test.ts +++ b/server/typescript/packages/codegen-ts/test/flattened-storage-e2e.test.ts @@ -9,7 +9,7 @@ // on the row, the write schemas and the filter allowlist. import { describe, test, expect, beforeAll, afterAll } from "bun:test"; -import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs"; +import { mkdtempSync, readFileSync, readdirSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; @@ -30,6 +30,7 @@ import { writeDeniedFieldNames } from "../src/api-surface.js"; import { isTphReadNullTolerant } from "../src/templates/zod-validators.js"; import { flatSurfaceFields } from "../src/flattened.js"; import { renderAgentUiPage } from "../src/generators/agent-ui-page.js"; +import { removeTree } from "../src/scratch-dir.js"; const META = JSON.stringify({ "metadata.root": { package: "acme", children: [ @@ -56,7 +57,7 @@ async function load(): Promise { } const dirs: string[] = []; -afterAll(() => { for (const d of dirs) rmSync(d, { recursive: true, force: true }); }); +afterAll(() => { for (const d of dirs) removeTree(d); }); async function generate(root: MetaRoot, dialect: Dialect, generators: ReturnType[], parent: string): Promise { const repo = mkdtempSync(join(parent, "flat-")); diff --git a/server/typescript/packages/codegen-ts/test/form-date-input-type.test.ts b/server/typescript/packages/codegen-ts/test/form-date-input-type.test.ts index 25f7717300..0a1f83f3ff 100644 --- a/server/typescript/packages/codegen-ts/test/form-date-input-type.test.ts +++ b/server/typescript/packages/codegen-ts/test/form-date-input-type.test.ts @@ -11,15 +11,16 @@ // Executed, not text-matched: the emitted constants module is imported and read. import { describe, test, expect, afterAll } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { MetaDataLoader, InMemoryStringSource, type MetaObject } from "@metaobjectsdev/metadata"; import { renderEntityConstants } from "../src/templates/entity-constants.js"; +import { removeTree } from "../src/scratch-dir.js"; const TEMP_DIRS: string[] = []; afterAll(() => { - for (const d of TEMP_DIRS) rmSync(d, { recursive: true, force: true }); + for (const d of TEMP_DIRS) removeTree(d); }); const MODEL = { diff --git a/server/typescript/packages/codegen-ts/test/form-fractional-input.test.ts b/server/typescript/packages/codegen-ts/test/form-fractional-input.test.ts index dafb5e56c3..ae122b1d6d 100644 --- a/server/typescript/packages/codegen-ts/test/form-fractional-input.test.ts +++ b/server/typescript/packages/codegen-ts/test/form-fractional-input.test.ts @@ -9,16 +9,17 @@ // int / long / currency -> type="number", step left at its default of 1. import { describe, test, expect, afterAll } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { renderEntityConstants } from "../src/templates/entity-constants.js"; import { numericInputControl } from "../src/templates/field-meta.js"; +import { removeTree } from "../src/scratch-dir.js"; const TEMP_DIRS: string[] = []; afterAll(() => { - for (const d of TEMP_DIRS) rmSync(d, { recursive: true, force: true }); + for (const d of TEMP_DIRS) removeTree(d); }); const MODEL = { diff --git a/server/typescript/packages/codegen-ts/test/fr004-verify-demo.test.ts b/server/typescript/packages/codegen-ts/test/fr004-verify-demo.test.ts index ba3c7c8e82..658d91fd58 100644 --- a/server/typescript/packages/codegen-ts/test/fr004-verify-demo.test.ts +++ b/server/typescript/packages/codegen-ts/test/fr004-verify-demo.test.ts @@ -16,8 +16,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; @@ -28,6 +27,7 @@ import { makeRenderContext } from "../src/render-context.js"; import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { GenContext } from "../src/generator.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -178,7 +178,7 @@ describe("FR-004 T7 — THE DEMO (both failures)", () => { // a resolution failure — guard against a false positive from a broken setup. expect(withoutDirective.some((d) => d.code === 2353 || d.code === 2345)).toBe(true); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); diff --git a/server/typescript/packages/codegen-ts/test/fr010-nested-extract-codegen.test.ts b/server/typescript/packages/codegen-ts/test/fr010-nested-extract-codegen.test.ts index f622b56baf..2611e05027 100644 --- a/server/typescript/packages/codegen-ts/test/fr010-nested-extract-codegen.test.ts +++ b/server/typescript/packages/codegen-ts/test/fr010-nested-extract-codegen.test.ts @@ -6,14 +6,15 @@ // single metadata-driven extract path reads the live metadata and assembles the full graph. import { describe, test, expect, afterAll } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource, type MetaRoot } from "@metaobjectsdev/metadata"; import { renderOutputParser } from "../src/templates/output-parser.js"; +import { removeTree } from "../src/scratch-dir.js"; const TEMP_DIRS: string[] = []; afterAll(() => { - for (const d of TEMP_DIRS) rmSync(d, { recursive: true, force: true }); + for (const d of TEMP_DIRS) removeTree(d); }); const PKG = "acme::ai"; diff --git a/server/typescript/packages/codegen-ts/test/fr010-output-codegen.test.ts b/server/typescript/packages/codegen-ts/test/fr010-output-codegen.test.ts index c4b54bdeaf..30778ead16 100644 --- a/server/typescript/packages/codegen-ts/test/fr010-output-codegen.test.ts +++ b/server/typescript/packages/codegen-ts/test/fr010-output-codegen.test.ts @@ -15,15 +15,16 @@ // parser/prompt emit exercised HERE is the one tier that gate does not reach. import { describe, test, expect, afterAll } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { renderOutputParser } from "../src/templates/output-parser.js"; import { renderOutputPrompt } from "../src/templates/output-prompt.js"; +import { removeTree } from "../src/scratch-dir.js"; const TEMP_DIRS: string[] = []; afterAll(() => { - for (const d of TEMP_DIRS) rmSync(d, { recursive: true, force: true }); + for (const d of TEMP_DIRS) removeTree(d); }); async function loadRoot(children: unknown[]) { diff --git a/server/typescript/packages/codegen-ts/test/fresh-clone-regen.test.ts b/server/typescript/packages/codegen-ts/test/fresh-clone-regen.test.ts index e7d834ed3c..420fe35a97 100644 --- a/server/typescript/packages/codegen-ts/test/fresh-clone-regen.test.ts +++ b/server/typescript/packages/codegen-ts/test/fresh-clone-regen.test.ts @@ -13,22 +13,20 @@ import { manifestExists, removeManifest } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { - mkdtempSync, rmSync, readFileSync, writeFileSync, readdirSync, existsSync, statSync, -} from "node:fs"; -import { tmpdir } from "node:os"; +import { rmSync, readFileSync, writeFileSync, readdirSync, existsSync, statSync } from "node:fs"; import { join, resolve } from "node:path"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; import { runGen } from "../src/runner.js"; import { defineConfig } from "../src/metaobjects-config.js"; import { entityFile } from "../src/generators/entity-file.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const FIXTURE = resolve(import.meta.dir, "fixtures", "single-entity.json"); let projectRoot: string; -beforeEach(() => { projectRoot = mkdtempSync(join(tmpdir(), "fresh-clone-")); }); -afterEach(() => { rmSync(projectRoot, { recursive: true, force: true }); }); +beforeEach(() => { projectRoot = makeScratchDir("fresh-clone-"); }); +afterEach(() => { removeTree(projectRoot); }); const genStateDir = (): string => join(projectRoot, ".metaobjects", ".gen-state"); @@ -55,7 +53,7 @@ function simulateFreshClone(): void { for (const entry of readdirSync(dir)) { const full = join(dir, entry); if (entry === ".hashes") continue; // the manifest directory is what a clone keeps - if (statSync(full).isDirectory()) { walk(full); rmSync(full, { recursive: true, force: true }); } + if (statSync(full).isDirectory()) { walk(full); removeTree(full); } else if (entry !== ".engine.json") rmSync(full, { force: true }); } }; diff --git a/server/typescript/packages/codegen-ts/test/gen-state-readers.test.ts b/server/typescript/packages/codegen-ts/test/gen-state-readers.test.ts index 8a8459e70e..ccb5e429a0 100644 --- a/server/typescript/packages/codegen-ts/test/gen-state-readers.test.ts +++ b/server/typescript/packages/codegen-ts/test/gen-state-readers.test.ts @@ -8,8 +8,7 @@ import { manifestEntries, manifestFiles } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync, writeFileSync, existsSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, writeFileSync, existsSync } from "node:fs"; import { join } from "node:path"; import { decideAndWrite, @@ -17,17 +16,18 @@ import { readGeneratedSnapshot, forgetGeneratedPaths, } from "../src/overwrite-policy.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; let root: string; let genStateDir: string; beforeEach(() => { - root = mkdtempSync(join(tmpdir(), "gen-state-readers-")); + root = makeScratchDir("gen-state-readers-"); genStateDir = join(root, ".gen-state"); }); afterEach(() => { - rmSync(root, { recursive: true, force: true }); + removeTree(root); }); /** Write `relPath` through the real policy so the snapshot + hash are produced diff --git a/server/typescript/packages/codegen-ts/test/generated-provenance.test.ts b/server/typescript/packages/codegen-ts/test/generated-provenance.test.ts index 38aa806231..b5ba191ce3 100644 --- a/server/typescript/packages/codegen-ts/test/generated-provenance.test.ts +++ b/server/typescript/packages/codegen-ts/test/generated-provenance.test.ts @@ -3,8 +3,7 @@ // (the explorer builder) can say which files a node produced without matching names. import { LEGACY_HASHES_FILE, manifestEntries, manifestExists, manifestFiles, seedLegacyManifest } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; @@ -12,12 +11,13 @@ import { runGen } from "../src/runner.js"; import { defineConfig } from "../src/metaobjects-config.js"; import { perEntity, perModel, type Generator } from "../src/generator.js"; import { recordGeneratedProvenance } from "../src/overwrite-policy.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const FIXTURE = resolve(import.meta.dir, "fixtures", "single-entity.json"); let tmp: string; -beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "codegen-provenance-")); }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +beforeEach(() => { tmp = makeScratchDir("codegen-provenance-"); }); +afterEach(() => { removeTree(tmp); }); const manifest = (dir: string): Record => manifestEntries(join(dir, ".metaobjects", ".gen-state")); diff --git a/server/typescript/packages/codegen-ts/test/generator-spec-resolution.test.ts b/server/typescript/packages/codegen-ts/test/generator-spec-resolution.test.ts index 6c6f6b9b86..a2e670c56d 100644 --- a/server/typescript/packages/codegen-ts/test/generator-spec-resolution.test.ts +++ b/server/typescript/packages/codegen-ts/test/generator-spec-resolution.test.ts @@ -1,6 +1,5 @@ import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, readdirSync, readFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readdirSync, readFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { runGen } from "../src/runner.js"; import { defineConfig, REMOVED_GENERATOR_NAMES, removedGeneratorMessage, resolveGenerators } from "../src/metaobjects-config.js"; @@ -9,6 +8,7 @@ import { entityFile } from "../src/generators/entity-file.js"; import { routesFile } from "../src/generators/routes-file.js"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; // ADR-0021 #1 (TS parity) — select generators by STABLE-NAME STRING in the // config `generators` array, resolved via the generator registry, as an @@ -19,8 +19,8 @@ import { FileSource } from "@metaobjectsdev/metadata/core"; const FIXTURE = resolve(import.meta.dir, "fixtures", "single-entity.json"); let tmp: string; -beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "codegen-spec-")); }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +beforeEach(() => { tmp = makeScratchDir("codegen-spec-"); }); +afterEach(() => { removeTree(tmp); }); async function loadRoot() { const loader = new MetaDataLoader(); diff --git a/server/typescript/packages/codegen-ts/test/generators/names-file.test.ts b/server/typescript/packages/codegen-ts/test/generators/names-file.test.ts index 9247d10054..30406af373 100644 --- a/server/typescript/packages/codegen-ts/test/generators/names-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/generators/names-file.test.ts @@ -4,21 +4,21 @@ // a sourced entity emits `.names.ts`, a sourceless object emits nothing (#248), and // the generator declares the markers the runner and eventual consumers key off of. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, existsSync, readFileSync, readdirSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, readFileSync, readdirSync } from "node:fs"; import { basename, dirname, join } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { runGen, defineConfig } from "../../src/index.js"; import { entityFile } from "../../src/generators/entity-file.js"; import { namesFile } from "../../src/generators/names-file.js"; import { GENERATED_HEADER, GENERATED_EDIT_NOTE } from "../../src/constants.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; let tmp: string; beforeEach(() => { - tmp = mkdtempSync(join(tmpdir(), "codegen-names-file-")); + tmp = makeScratchDir("codegen-names-file-"); }); afterEach(() => { - rmSync(tmp, { recursive: true, force: true }); + removeTree(tmp); }); async function loadRoot(children: unknown[]) { diff --git a/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts b/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts index c47e29961c..d488beebbe 100644 --- a/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts @@ -33,8 +33,7 @@ // fix the builder, never the gate. import { describe, test, expect } from "bun:test"; -import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource, type MetaObject } from "@metaobjectsdev/metadata"; import { routesFileHono, callableFile, promptRender, extractor, renderHelper } from "../../src/generators/index.js"; @@ -47,6 +46,7 @@ import { makeRenderContext } from "../../src/render-context.js"; import { buildPkMap } from "../../src/pk-resolver.js"; import { buildRelationMap } from "../../src/relation-resolver.js"; import type { Generator, GenContext, EmittedFile } from "../../src/generator.js"; +import { makeScratchDir } from "../../src/scratch-dir.js"; // --------------------------------------------------------------------------- // The rich fixture — one root that hits every documented surface + skip shape. @@ -152,7 +152,7 @@ const FIXTURE = JSON.stringify({ // codegen-time provider (projectProvider(projectRoot)) for its build-time drift // gate, so we materialize a project root with the referenced templates. function makeProjectRoot(): string { - const proj = mkdtempSync(join(tmpdir(), "api-docs-accuracy-")); + const proj = makeScratchDir("api-docs-accuracy-"); const write = (rel: string, body: string) => { const full = join(proj, "templates", rel); mkdirSync(join(full, ".."), { recursive: true }); @@ -1171,7 +1171,7 @@ describe("api-docs ACCURACY gate — writes are documented only where the genera new InMemoryStringSource(READ_WRITE_FIXTURE, { id: "orders.json", format: "json" }), ]); expect(res.errors).toEqual([]); - const projectRoot = mkdtempSync(join(tmpdir(), "api-docs-accuracy-rw-")); + const projectRoot = makeScratchDir("api-docs-accuracy-rw-"); entityFiles = await runGenerator(entityFile(), res.root, projectRoot); queriesFiles = await runGenerator(queriesFile(), res.root, projectRoot); routesFiles = await runGenerator(routesFile(), res.root, projectRoot); diff --git a/server/typescript/packages/codegen-ts/test/golden/api-docs-relative-imports.test.ts b/server/typescript/packages/codegen-ts/test/golden/api-docs-relative-imports.test.ts index 4f9f281d7b..9e428e6e97 100644 --- a/server/typescript/packages/codegen-ts/test/golden/api-docs-relative-imports.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/api-docs-relative-imports.test.ts @@ -23,8 +23,7 @@ import { describe, test, expect, afterAll, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "../compile-timeout.js"; -import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdirSync, writeFileSync } from "node:fs"; import { join, dirname } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource, type MetaObject } from "@metaobjectsdev/metadata"; @@ -41,6 +40,7 @@ import { buildPkMap } from "../../src/pk-resolver.js"; import { buildRelationMap } from "../../src/relation-resolver.js"; import { runGen, defineConfig } from "../../src/index.js"; import type { Generator, GenContext, EmittedFile } from "../../src/generator.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -165,7 +165,7 @@ describe("Fix 1: rendered api-docs import specifiers are `./`-prefixed (copy-pas const TEMP_DIRS: string[] = []; afterAll(() => { - for (const d of TEMP_DIRS) rmSync(d, { recursive: true, force: true }); + for (const d of TEMP_DIRS) removeTree(d); }); /** Run one generator with a structural GenContext (mirrors the accuracy gate). */ @@ -276,7 +276,7 @@ function compile(dir: string, files: string[]): readonly ts.Diagnostic[] { describe("Fix 1: a CRUD consumer from AGENT-API.md COMPILES against the REAL generated code (no TS2307)", () => { test("the doc's `./`-prefixed imports RESOLVE + the CRUD example type-checks", async () => { const root = await loadRoot(); - const projectRoot = mkdtempSync(join(tmpdir(), "api-docs-relimports-proj-")); + const projectRoot = makeScratchDir("api-docs-relimports-proj-"); TEMP_DIRS.push(projectRoot); // 1. Generate the REAL entity + queries code for Product (flat layout). @@ -290,7 +290,7 @@ describe("Fix 1: a CRUD consumer from AGENT-API.md COMPILES against the REAL gen // 3. Lay out a temp output dir exactly as a consumer's generated dir: the // real generated files at the root + a consumer that copy-pastes the // doc's import header + CRUD example body. - const dir = mkdtempSync(join(tmpdir(), "api-docs-relimports-")); + const dir = makeScratchDir("api-docs-relimports-"); TEMP_DIRS.push(dir); const write = (rel: string, body: string) => { const full = join(dir, rel); @@ -353,7 +353,7 @@ const HONO_CHILDREN = CHILDREN; describe("Fix 2: api-docs documents Hono routes when the Hono generator is in the run", () => { test("ctx.config.includeHonoRoutes drives the builder — Hono symbols are documented", async () => { const root = await loadRoot(); - const projectRoot = mkdtempSync(join(tmpdir(), "api-docs-hono-")); + const projectRoot = makeScratchDir("api-docs-hono-"); TEMP_DIRS.push(projectRoot); // The api-docs generator, run with includeHonoRoutes in its ctx.config @@ -371,7 +371,7 @@ describe("Fix 2: api-docs documents Hono routes when the Hono generator is in th test("without includeHonoRoutes, NO Hono symbols are documented (Fastify only)", async () => { const root = await loadRoot(); - const projectRoot = mkdtempSync(join(tmpdir(), "api-docs-nohono-")); + const projectRoot = makeScratchDir("api-docs-nohono-"); TEMP_DIRS.push(projectRoot); const files = await runGenerator(apiDocsFile(), root, projectRoot, { outputLayout: "flat" }); const agentFile = files.find((f) => f.path.endsWith("AGENT-API.md"))!; @@ -392,11 +392,11 @@ describe("Fix 2: api-docs documents Hono routes when the Hono generator is in th // the Hono marker off the declared suite, as for every generator. test("runGen: api-docs in the generator list writes into the docs target and documents the Hono routes", async () => { const root = await loadRoot(); - const projectRoot = mkdtempSync(join(tmpdir(), "api-docs-rungen-")); + const projectRoot = makeScratchDir("api-docs-rungen-"); TEMP_DIRS.push(projectRoot); - const outDir = mkdtempSync(join(tmpdir(), "api-docs-rungen-code-")); - const docsDir = mkdtempSync(join(tmpdir(), "api-docs-rungen-docs-")); + const outDir = makeScratchDir("api-docs-rungen-code-"); + const docsDir = makeScratchDir("api-docs-rungen-docs-"); TEMP_DIRS.push(outDir, docsDir); const result = await runGen({ config: defineConfig({ diff --git a/server/typescript/packages/codegen-ts/test/golden/cross-package-binding-conformance.test.ts b/server/typescript/packages/codegen-ts/test/golden/cross-package-binding-conformance.test.ts index 400dee4116..eeba54925b 100644 --- a/server/typescript/packages/codegen-ts/test/golden/cross-package-binding-conformance.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/cross-package-binding-conformance.test.ts @@ -9,8 +9,7 @@ // before the root `Customer`), so a short-name lookup or a re-resolve in `acme` binds it. import { describe, test, expect } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync, readdirSync, existsSync, statSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, readdirSync, existsSync, statSync } from "node:fs"; import { join, dirname, relative } from "node:path"; import { MetaDataLoader, @@ -27,6 +26,7 @@ import { entityFile } from "../../src/generators/entity-file.js"; import { queriesFile } from "../../src/generators/queries-file.js"; import { routesFile } from "../../src/generators/routes-file.js"; import { buildRelationMap } from "../../src/relation-resolver.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; function findRepoRoot(start: string): string { let dir = start; @@ -120,7 +120,7 @@ describe("cross-package binding conformance (TS)", () => { test("generated modules import the bound target's module, never the wrong same-named one", async () => { const root = await loadFixture(); - const tmp = mkdtempSync(join(tmpdir(), "xpkg-binding-")); + const tmp = makeScratchDir("xpkg-binding-"); const files: Record = {}; try { await runGen({ @@ -143,7 +143,7 @@ describe("cross-package binding conformance (TS)", () => { }; walk(tmp); } finally { - rmSync(tmp, { recursive: true, force: true }); + removeTree(tmp); } // a::Post — the M:N route and the to-one relation reach b::Tag's module. diff --git a/server/typescript/packages/codegen-ts/test/golden/enum-conformance.test.ts b/server/typescript/packages/codegen-ts/test/golden/enum-conformance.test.ts index ec89daab22..b73f81a648 100644 --- a/server/typescript/packages/codegen-ts/test/golden/enum-conformance.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/enum-conformance.test.ts @@ -7,14 +7,14 @@ // shared `enums.ts` module and referenced by the entity (no inline redeclaration). import { describe, test, expect } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync, readdirSync, existsSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, readdirSync, existsSync } from "node:fs"; import { join, dirname, resolve } from "node:path"; import { runGen, defineConfig } from "../../src/index.js"; import { barrel } from "../../src/generators/barrel.js"; import { entityFile } from "../../src/generators/entity-file.js"; import { queriesFile } from "../../src/generators/queries-file.js"; import { MetaDataLoader, InMemoryStringSource, type MetaRoot } from "@metaobjectsdev/metadata"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; function findRepoRoot(start: string): string { let dir = start; @@ -37,7 +37,7 @@ async function loadSharedFixture(): Promise { } async function gen(root: MetaRoot): Promise> { - const tmp = mkdtempSync(join(tmpdir(), "enum-conf-")); + const tmp = makeScratchDir("enum-conf-"); try { await runGen({ config: defineConfig({ @@ -55,7 +55,7 @@ async function gen(root: MetaRoot): Promise> { } return files; } finally { - rmSync(tmp, { recursive: true, force: true }); + removeTree(tmp); } } diff --git a/server/typescript/packages/codegen-ts/test/golden/extractor-render-payload-imports.test.ts b/server/typescript/packages/codegen-ts/test/golden/extractor-render-payload-imports.test.ts index 8185804949..d3ca237ad1 100644 --- a/server/typescript/packages/codegen-ts/test/golden/extractor-render-payload-imports.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/extractor-render-payload-imports.test.ts @@ -17,8 +17,7 @@ import { describe, test, expect, afterAll, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "../compile-timeout.js"; -import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdirSync, writeFileSync } from "node:fs"; import { join, dirname } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource, type MetaObject } from "@metaobjectsdev/metadata"; @@ -31,6 +30,7 @@ import { buildPkMap } from "../../src/pk-resolver.js"; import { buildRelationMap } from "../../src/relation-resolver.js"; import type { GenContext, EmittedFile } from "../../src/generator.js"; import type { Provider } from "@metaobjectsdev/render"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -207,7 +207,7 @@ function compile(dir: string, files: string[]): readonly ts.Diagnostic[] { const TEMP_DIRS: string[] = []; afterAll(() => { - for (const d of TEMP_DIRS) rmSync(d, { recursive: true, force: true }); + for (const d of TEMP_DIRS) removeTree(d); }); describe("extractor/render payload import resolves against the REAL generated VO modules (no ./payloads.js)", () => { @@ -237,7 +237,7 @@ describe("extractor/render payload import resolves against the REAL generated VO // 3. Lay the real generated VO modules + the extractor/render files into a // temp dir exactly as `meta gen` would (the default package layout, R63). - const dir = mkdtempSync(join(tmpdir(), "extractor-render-payload-")); + const dir = makeScratchDir("extractor-render-payload-"); TEMP_DIRS.push(dir); const write = (rel: string, body: string) => { const full = join(dir, rel); diff --git a/server/typescript/packages/codegen-ts/test/golden/fr019-shared-provided-conformance.test.ts b/server/typescript/packages/codegen-ts/test/golden/fr019-shared-provided-conformance.test.ts index 44fc81c8c6..bbdd5e265e 100644 --- a/server/typescript/packages/codegen-ts/test/golden/fr019-shared-provided-conformance.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/fr019-shared-provided-conformance.test.ts @@ -10,8 +10,7 @@ // • A `@provided` enum with no `providedEnumModule` config → a codegen-time error. import { describe, test, expect } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync, readdirSync, existsSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, readdirSync, existsSync } from "node:fs"; import { join, dirname } from "node:path"; import { runGen, defineConfig } from "../../src/index.js"; import { barrel } from "../../src/generators/barrel.js"; @@ -20,6 +19,7 @@ import { queriesFile } from "../../src/generators/queries-file.js"; import { MetaDataLoader, InMemoryStringSource, FIELD_SUBTYPE_ENUM, type MetaObject, type MetaRoot } from "@metaobjectsdev/metadata"; import { sharedEnumForField, materializedSharedEnums } from "../../src/enum-shared.js"; import { renderSharedEnumsFile } from "../../src/templates/enums-file.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; function findRepoRoot(start: string): string { let dir = start; @@ -55,7 +55,7 @@ async function gen( providedEnumModule?: string, only?: (entity: MetaObject) => boolean, ): Promise> { - const tmp = mkdtempSync(join(tmpdir(), "fr019-conf-")); + const tmp = makeScratchDir("fr019-conf-"); try { await runGen({ config: defineConfig({ @@ -73,7 +73,7 @@ async function gen( for (const name of readdirSync(tmp)) if (name.endsWith(".ts")) files[name] = readFileSync(join(tmp, name), "utf-8"); return files; } finally { - rmSync(tmp, { recursive: true, force: true }); + removeTree(tmp); } } diff --git a/server/typescript/packages/codegen-ts/test/golden/golden-output.test.ts b/server/typescript/packages/codegen-ts/test/golden/golden-output.test.ts index 0683060dc9..f5693e5f32 100644 --- a/server/typescript/packages/codegen-ts/test/golden/golden-output.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/golden-output.test.ts @@ -9,8 +9,7 @@ // bun test test/golden/golden-output.test.ts import { describe, it, expect } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync, existsSync, writeFileSync, mkdirSync, readdirSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, existsSync, writeFileSync, mkdirSync, readdirSync } from "node:fs"; import { join, resolve, relative } from "node:path"; import { runGen, defineConfig } from "../../src/index.js"; import { barrel } from "../../src/generators/barrel.js"; @@ -20,6 +19,7 @@ import { routesFile } from "../../src/generators/routes-file.js"; import { formFile } from "@metaobjectsdev/codegen-ts-react"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; const FIXTURE = resolve(import.meta.dir, "../fixtures/trainer-website-shape.json"); const SNAP = join(import.meta.dir, "__snapshots__"); @@ -37,7 +37,7 @@ describe("golden output — byte-identical port gate", () => { for (const dialect of ["sqlite", "postgres"] as const) { it(`generates byte-identical output — ${dialect}`, async () => { // Use a temp dir so runGen can write files; we read them back for comparison. - const tmp = mkdtempSync(join(tmpdir(), `codegen-golden-${dialect}-`)); + const tmp = makeScratchDir(`codegen-golden-${dialect}-`); try { const result = await runGen({ config: defineConfig({ @@ -81,7 +81,7 @@ describe("golden output — byte-identical port gate", () => { expect(snapFiles).toEqual(writtenFiles); } } finally { - rmSync(tmp, { recursive: true, force: true }); + removeTree(tmp); } }); } diff --git a/server/typescript/packages/codegen-ts/test/golden/inheritance-conformance.test.ts b/server/typescript/packages/codegen-ts/test/golden/inheritance-conformance.test.ts index b91649a523..4fbf026470 100644 --- a/server/typescript/packages/codegen-ts/test/golden/inheritance-conformance.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/inheritance-conformance.test.ts @@ -5,14 +5,14 @@ // and that the abstract bases emit no instance table. import { describe, test, expect } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync, readdirSync, existsSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, readdirSync, existsSync } from "node:fs"; import { join, dirname } from "node:path"; import { runGen, defineConfig } from "../../src/index.js"; import { barrel } from "../../src/generators/barrel.js"; import { entityFile } from "../../src/generators/entity-file.js"; import { queriesFile } from "../../src/generators/queries-file.js"; import { MetaDataLoader, InMemoryStringSource, type MetaRoot } from "@metaobjectsdev/metadata"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; function findRepoRoot(start: string): string { let dir = start; @@ -35,7 +35,7 @@ async function loadSharedFixture(): Promise { } async function gen(root: MetaRoot): Promise> { - const tmp = mkdtempSync(join(tmpdir(), "inh-conf-")); + const tmp = makeScratchDir("inh-conf-"); try { await runGen({ config: defineConfig({ @@ -51,7 +51,7 @@ async function gen(root: MetaRoot): Promise> { for (const name of readdirSync(tmp)) if (name.endsWith(".ts")) files[name] = readFileSync(join(tmp, name), "utf-8"); return files; } finally { - rmSync(tmp, { recursive: true, force: true }); + removeTree(tmp); } } diff --git a/server/typescript/packages/codegen-ts/test/golden/package-layout.test.ts b/server/typescript/packages/codegen-ts/test/golden/package-layout.test.ts index 87b369a84f..1e6372f1ab 100644 --- a/server/typescript/packages/codegen-ts/test/golden/package-layout.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/package-layout.test.ts @@ -16,17 +16,7 @@ // bun test test/golden/package-layout.test.ts import { describe, it, expect } from "bun:test"; -import { - mkdtempSync, - rmSync, - readFileSync, - existsSync, - writeFileSync, - mkdirSync, - readdirSync, - statSync, -} from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, existsSync, writeFileSync, mkdirSync, readdirSync, statSync } from "node:fs"; import { join, resolve, relative, dirname } from "node:path"; import { runGen, defineConfig } from "../../src/index.js"; import { namesFile } from "../../src/generators/index.js"; @@ -37,6 +27,7 @@ import { routesFile } from "../../src/generators/routes-file.js"; import { formFile } from "@metaobjectsdev/codegen-ts-react"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; const FIXTURE = resolve(import.meta.dir, "../fixtures/packaged-shape.json"); const SNAP = join(import.meta.dir, "__snapshots__/package"); @@ -68,7 +59,7 @@ const metadataRoot = loadResult.root; describe("golden output — package layout placement + import gate", () => { it("generates correct file placement and imports — sqlite / outputLayout:package", async () => { - const tmp = mkdtempSync(join(tmpdir(), "codegen-golden-pkg-")); + const tmp = makeScratchDir("codegen-golden-pkg-"); try { const result = await runGen({ config: defineConfig({ @@ -119,7 +110,7 @@ describe("golden output — package layout placement + import gate", () => { expect(snapFiles).toEqual(writtenFiles); } } finally { - rmSync(tmp, { recursive: true, force: true }); + removeTree(tmp); } }); }); diff --git a/server/typescript/packages/codegen-ts/test/hash-manifest-store.test.ts b/server/typescript/packages/codegen-ts/test/hash-manifest-store.test.ts index 76122ee5bc..2b655bfc3d 100644 --- a/server/typescript/packages/codegen-ts/test/hash-manifest-store.test.ts +++ b/server/typescript/packages/codegen-ts/test/hash-manifest-store.test.ts @@ -1,7 +1,7 @@ // ADR-0064 Amendment 1: the hash manifest is one file per model package. The vectors are the // shared ones every port runs (`fixtures/codegen-skip-conformance/manifests.json`). import { afterEach, beforeEach, describe, expect, test } from "bun:test"; -import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { buildPlacementIndex, @@ -10,6 +10,7 @@ import { readManifestState, } from "../src/hash-manifest-store.js"; import { forgetGeneratedPaths, listGeneratedPaths, withManifestBatch, writeManifestFiles } from "../src/overwrite-policy.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; interface Vectors { objects: { name: string; package: string }[]; @@ -33,11 +34,11 @@ const INDEX = buildPlacementIndex(VECTORS.objects); let tmp: string; let state: string; beforeEach(() => { - tmp = mkdtempSync(join(process.env.DEV_SCRATCH ?? "/tmp", "hash-manifest-store-")); + tmp = makeScratchDir("hash-manifest-store-"); state = join(tmp, ".metaobjects", ".gen-state"); mkdirSync(state, { recursive: true }); }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +afterEach(() => { removeTree(tmp); }); const dirOf = (): string => join(state, ".hashes"); const files = (): string[] => (existsSync(dirOf()) ? readdirSync(dirOf()).sort() : []); diff --git a/server/typescript/packages/codegen-ts/test/int-enum-array-compile.test.ts b/server/typescript/packages/codegen-ts/test/int-enum-array-compile.test.ts index efd058bab1..b7dc67a885 100644 --- a/server/typescript/packages/codegen-ts/test/int-enum-array-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/int-enum-array-compile.test.ts @@ -7,7 +7,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; @@ -17,6 +17,7 @@ import { makeRenderContext } from "../src/render-context.js"; import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { GenContext } from "../src/generator.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -86,7 +87,7 @@ describe("int-backed field.enum ARRAY — generated modules compile", () => { const diagnostics = compile(dir, [...files.map((f) => f.path)]); expect(diagnostics.map((d) => `${d.file?.fileName ?? ""}: ${ts.flattenDiagnosticMessageText(d.messageText, "\n")}`)).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); } diff --git a/server/typescript/packages/codegen-ts/test/integration.test.ts b/server/typescript/packages/codegen-ts/test/integration.test.ts index d27312ab37..2cbbbb8956 100644 --- a/server/typescript/packages/codegen-ts/test/integration.test.ts +++ b/server/typescript/packages/codegen-ts/test/integration.test.ts @@ -2,8 +2,7 @@ // End-to-end gate that proves Tasks 1-16 produce production-quality output. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync, readdirSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, readdirSync } from "node:fs"; import { join, resolve } from "node:path"; import { runGen, defineConfig } from "../src/index.js"; import { barrel } from "../src/generators/barrel.js"; @@ -12,10 +11,11 @@ import { queriesFile } from "../src/generators/queries-file.js"; import { routesFile } from "../src/generators/routes-file.js"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; let tmp: string; -beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "codegen-integration-")); }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +beforeEach(() => { tmp = makeScratchDir("codegen-integration-"); }); +afterEach(() => { removeTree(tmp); }); const FIXTURE = resolve(import.meta.dir, "fixtures/trainer-website-shape.json"); diff --git a/server/typescript/packages/codegen-ts/test/jsonb-open-bag-zod.test.ts b/server/typescript/packages/codegen-ts/test/jsonb-open-bag-zod.test.ts index b979fa9b76..68223195fc 100644 --- a/server/typescript/packages/codegen-ts/test/jsonb-open-bag-zod.test.ts +++ b/server/typescript/packages/codegen-ts/test/jsonb-open-bag-zod.test.ts @@ -19,6 +19,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import { fieldTsTypeString } from "../src/templates/inferred-types.js"; import { metaField } from "./_meta-build.js"; +import { makeScratchDir } from "../src/scratch-dir.js"; const YAML = `metadata: package: t @@ -35,10 +36,9 @@ const YAML = `metadata: `; async function loadDoc() { - const { writeFileSync, mkdtempSync } = await import("node:fs"); - const { tmpdir } = await import("node:os"); + const { writeFileSync } = await import("node:fs"); const { join } = await import("node:path"); - const dir = mkdtempSync(join(tmpdir(), "jsonb-zod-")); + const dir = makeScratchDir("jsonb-zod-"); const f = join(dir, "doc.yaml"); writeFileSync(f, YAML); const loader = new MetaDataLoader(); diff --git a/server/typescript/packages/codegen-ts/test/jsonb-vo-read-typed-compile.test.ts b/server/typescript/packages/codegen-ts/test/jsonb-vo-read-typed-compile.test.ts index 7cac3179f0..8a7225475c 100644 --- a/server/typescript/packages/codegen-ts/test/jsonb-vo-read-typed-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/jsonb-vo-read-typed-compile.test.ts @@ -10,7 +10,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource, type MetaObject, type MetaRoot } from "@metaobjectsdev/metadata"; @@ -21,6 +21,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { EmittedFile, GenContext } from "../src/generator.js"; import type { Dialect } from "../src/metaobjects-config.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -118,7 +119,7 @@ async function compileCaller(dialect: Dialect, body: string): Promise writeFileSync(join(dir, "caller.ts"), caller); return compile(dir, [...files.map((f) => f.path), "caller.ts"]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } @@ -134,7 +135,7 @@ for (const dialect of ["postgres", "sqlite"] as const) { expect(customer).toContain(".$type()"); expect(customer).toMatch(/import (type \{[^}]*\bAddress\b|\{[^}]*\btype Address\b)/); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); diff --git a/server/typescript/packages/codegen-ts/test/layout-ratchet/allowlist.json b/server/typescript/packages/codegen-ts/test/layout-ratchet/allowlist.json index 79dc71217a..b21469aa7b 100644 --- a/server/typescript/packages/codegen-ts/test/layout-ratchet/allowlist.json +++ b/server/typescript/packages/codegen-ts/test/layout-ratchet/allowlist.json @@ -13,7 +13,6 @@ "codegen-ts/src/client-directive.ts": "Prepends the \"use client\" directive to client artifacts by string concatenation. Converts with the TanStack and Angular writer PR, when client artifacts use TsWriter.header().", "codegen-ts/src/constants.ts": "Builds the sidecar comment line of generated files with a typed line break. Converts with the entity tier A writer PR (schema, relations, constants, enums, value objects, filters, inferred types).", "codegen-ts/src/cube/cube-yaml.ts": "Emits the Cube data-model YAML with hand-typed indentation. Converts with the data-format emitters (Cube, Prisma) writer PR.", - "codegen-ts/src/generators/agent-requirements-page.ts": "Emits the agent requirements markdown page; template strings with hand-typed line breaks and indentation. Converts with the docs and markdown writer PR; its output is documentation, not code an adopter edits, so it goes after the code generators.", "codegen-ts/src/generators/agent-schema-page.ts": "Emits the agent schema markdown page; template strings with hand-typed line breaks and indentation. Converts with the docs and markdown writer PR; its output is documentation, not code an adopter edits, so it goes after the code generators.", "codegen-ts/src/generators/agent-ui-page.ts": "Emits the agent UI markdown page; template strings with hand-typed line breaks and indentation. Converts with the docs and markdown writer PR; its output is documentation, not code an adopter edits, so it goes after the code generators.", "codegen-ts/src/generators/api-doc-render.ts": "Emits the API documentation markdown; template strings with hand-typed line breaks and indentation. Converts with the docs and markdown writer PR; its output is documentation, not code an adopter edits, so it goes after the code generators.", @@ -21,7 +20,6 @@ "codegen-ts/src/generators/docs-file.ts": "Emits the per-entity docs page; template strings with hand-typed line breaks and indentation. Converts with the docs and markdown writer PR; its output is documentation, not code an adopter edits, so it goes after the code generators.", "codegen-ts/src/generators/prompt-render-file.ts": "Emits the prompt render module; template strings with hand-typed line breaks and indentation. Converts with the prompt-tier writer PR (output parser, prompt, extractor, render and trace helpers).", "codegen-ts/src/generators/report-doc.ts": "Emits the report documentation markdown; template strings with hand-typed line breaks and indentation. Converts with the docs and markdown writer PR; its output is documentation, not code an adopter edits, so it goes after the code generators.", - "codegen-ts/src/generators/requirements-markdown.ts": "Emits the requirements ledger markdown; template strings with hand-typed line breaks and indentation. Converts with the docs and markdown writer PR; its output is documentation, not code an adopter edits, so it goes after the code generators.", "codegen-ts/src/generators/template-doc-builder.ts": "Builds the template documentation markdown; template strings with hand-typed line breaks and indentation. Converts with the docs and markdown writer PR; its output is documentation, not code an adopter edits, so it goes after the code generators.", "codegen-ts/src/generators/template-source-render.ts": "Renders template source into documentation blocks; template strings with hand-typed line breaks and indentation. Converts with the docs and markdown writer PR; its output is documentation, not code an adopter edits, so it goes after the code generators.", "codegen-ts/src/prisma/render-prisma-schema.ts": "Emits the Prisma schema with hand-typed indentation and newline joins. Converts with the data-format emitters (Cube, Prisma) writer PR.", diff --git a/server/typescript/packages/codegen-ts/test/manifest-branch-merge.test.ts b/server/typescript/packages/codegen-ts/test/manifest-branch-merge.test.ts index d42e94ce02..2cdd160c20 100644 --- a/server/typescript/packages/codegen-ts/test/manifest-branch-merge.test.ts +++ b/server/typescript/packages/codegen-ts/test/manifest-branch-merge.test.ts @@ -2,7 +2,7 @@ // files in DIFFERENT packages produce manifests that merge with nothing to resolve. With the // single `.hashes.json` the same two branches conflict on that one file. import { afterEach, beforeEach, describe, expect, test } from "bun:test"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { spawnSync } from "node:child_process"; import { join } from "node:path"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; @@ -10,10 +10,11 @@ import { FileSource } from "@metaobjectsdev/metadata/core"; import { runGen } from "../src/runner.js"; import { defineConfig } from "../src/metaobjects-config.js"; import { perEntity, perModel, type Generator } from "../src/generator.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; let tmp: string; -beforeEach(() => { tmp = mkdtempSync(join(process.env.DEV_SCRATCH ?? "/tmp", "manifest-merge-")); }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +beforeEach(() => { tmp = makeScratchDir("manifest-merge-"); }); +afterEach(() => { removeTree(tmp); }); const entity = (pkg: string, name: string): string => JSON.stringify({ "metadata.root": { package: pkg, children: [{ "object.entity": { name, children: [ diff --git a/server/typescript/packages/codegen-ts/test/manifest-write-once.test.ts b/server/typescript/packages/codegen-ts/test/manifest-write-once.test.ts index 1fd5f12e9f..82d1270ccf 100644 --- a/server/typescript/packages/codegen-ts/test/manifest-write-once.test.ts +++ b/server/typescript/packages/codegen-ts/test/manifest-write-once.test.ts @@ -3,8 +3,7 @@ // of a large project's run time, for the same bytes one write produces. import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test"; import * as fs from "node:fs"; -import { mkdirSync, mkdtempSync, rmSync, readFileSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdirSync, rmSync, readFileSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; @@ -14,12 +13,13 @@ import { entityFile } from "../src/generators/entity-file.js"; import { queriesFile } from "../src/generators/queries-file.js"; import { barrel } from "../src/generators/barrel.js"; import { isManifestPath, manifestEntries, manifestFiles, removeManifest, seedLegacyManifest } from "./support/manifest.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const FIXTURE = resolve(import.meta.dir, "fixtures", "two-entities-fk.json"); let project: string; -beforeEach(() => { project = mkdtempSync(join(tmpdir(), "codegen-manifest-once-")); }); -afterEach(() => { rmSync(project, { recursive: true, force: true }); }); +beforeEach(() => { project = makeScratchDir("codegen-manifest-once-"); }); +afterEach(() => { removeTree(project); }); /** Manifest-file writes during one run: path -> times written. */ async function gen(): Promise> { diff --git a/server/typescript/packages/codegen-ts/test/names-extends-chain.test.ts b/server/typescript/packages/codegen-ts/test/names-extends-chain.test.ts index af8dd55500..33e94bd3a9 100644 --- a/server/typescript/packages/codegen-ts/test/names-extends-chain.test.ts +++ b/server/typescript/packages/codegen-ts/test/names-extends-chain.test.ts @@ -13,14 +13,14 @@ // which is the outcome this change exists to prevent. import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, rmSync, readdirSync, readFileSync, statSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdtempSync, readdirSync, readFileSync, statSync } from "node:fs"; import { join, relative } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { runGen, defineConfig } from "../src/index.js"; import { namesFile } from "../src/generators/index.js"; import { entityFile } from "../src/generators/entity-file.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -126,7 +126,7 @@ describe("names artifacts extend rather than restate", () => { expect(base?.includes("table: ")).toBe(false); expect(base?.includes("view: ")).toBe(false); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); @@ -146,7 +146,7 @@ describe("names artifacts extend rather than restate", () => { // readOnly, and spreading it would leak an absent shape onto a child that has one. expect(author).not.toContain("...BaseEntityNames,"); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); @@ -167,7 +167,7 @@ describe("names artifacts extend rather than restate", () => { expect(sub).not.toContain("zz_auths"); expect(sub).not.toContain('kind: { name: "kind"'); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); @@ -203,7 +203,7 @@ describe("names artifacts extend rather than restate", () => { .map((d) => `${d.file?.fileName ?? ""}: ${ts.flattenDiagnosticMessageText(d.messageText, " ")}`); expect(errors).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); }); @@ -270,7 +270,7 @@ describe("a key-only abstract is a link in the chain, not a node to walk past", expect(widget).toContain("...AuditedNames.identities,"); expect(widget).not.toContain('by_email: {'); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); @@ -302,7 +302,7 @@ describe("a key-only abstract is a link in the chain, not a node to walk past", .map((d) => `${d.file?.fileName ?? ""}: ${ts.flattenDiagnosticMessageText(d.messageText, " ")}`); expect(errors).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); }); @@ -369,7 +369,7 @@ describe("a scoped run still names the shared table", () => { .map((d) => `${d.file?.fileName ?? ""}: ${ts.flattenDiagnosticMessageText(d.messageText, " ")}`); expect(errs).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); }); @@ -400,7 +400,7 @@ describe("namesFile({ filter }) narrows emission without breaking the extends ch // And the surviving artifact still really extends the base it kept. expect(tree["Author.names.ts"]).toContain("BaseEntityNames"); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); @@ -412,7 +412,7 @@ describe("namesFile({ filter }) narrows emission without breaking the extends ch "Auth.names.ts", "Author.names.ts", "BaseEntity.names.ts", "CouponAuth.names.ts", ]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); }); diff --git a/server/typescript/packages/codegen-ts/test/names-reference-compile.test.ts b/server/typescript/packages/codegen-ts/test/names-reference-compile.test.ts index 0abfa75d4b..22ec40700f 100644 --- a/server/typescript/packages/codegen-ts/test/names-reference-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/names-reference-compile.test.ts @@ -24,7 +24,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; @@ -36,6 +36,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { GenContext } from "../src/generator.js"; import type { Dialect } from "../src/metaobjects-config.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -132,7 +133,7 @@ async function genAndCompile( ); return { errors, emitted: files.map((f) => f.content).join("\n") }; } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } diff --git a/server/typescript/packages/codegen-ts/test/naming/collection-name-collision-wiring.test.ts b/server/typescript/packages/codegen-ts/test/naming/collection-name-collision-wiring.test.ts index 33621ef8e3..8a7e6e052f 100644 --- a/server/typescript/packages/codegen-ts/test/naming/collection-name-collision-wiring.test.ts +++ b/server/typescript/packages/codegen-ts/test/naming/collection-name-collision-wiring.test.ts @@ -4,8 +4,6 @@ // TS twin) emits neither, so it never refuses them. import { describe, test, expect } from "bun:test"; -import { mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { runGen } from "../../src/runner.js"; @@ -15,6 +13,7 @@ import { apiDocsFile } from "../../src/generators/api-docs-file.js"; import { entityFile } from "../../src/generators/entity-file.js"; import { routesFile } from "../../src/generators/routes-file.js"; import { ERR_COLLECTION_NAME_COLLISION } from "../../src/naming/collection-name-collision.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; const entity = (name: string, table: string) => ({ "object.entity": { @@ -32,7 +31,7 @@ async function run(names: [string, string], generators: Parameters { diff --git a/server/typescript/packages/codegen-ts/test/naming/collection-name-wiring.test.ts b/server/typescript/packages/codegen-ts/test/naming/collection-name-wiring.test.ts index f69eb37050..c87f1db9bb 100644 --- a/server/typescript/packages/codegen-ts/test/naming/collection-name-wiring.test.ts +++ b/server/typescript/packages/codegen-ts/test/naming/collection-name-wiring.test.ts @@ -6,7 +6,7 @@ import { describe, expect, test, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "../compile-timeout.js"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { @@ -23,6 +23,7 @@ import { buildRelationMap } from "../../src/relation-resolver.js"; import { assertNoCollectionNameCollisions } from "../../src/naming/collection-name-collision.js"; import { hookListNameSegment, listFnName, reverseFinderFnName } from "../../src/naming.js"; import type { EmittedFile, GenContext } from "../../src/generator.js"; +import { removeTree } from "../../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -86,7 +87,7 @@ function compile(files: Map): string[] { return ts.getPreEmitDiagnostics(program).map((d) => `${d.file?.fileName.slice(dir.length + 1) ?? ""} ${ts.flattenDiagnosticMessageText(d.messageText, "\n")}`); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } diff --git a/server/typescript/packages/codegen-ts/test/naming/collection-name.test.ts b/server/typescript/packages/codegen-ts/test/naming/collection-name.test.ts index 36afb5684a..bae59d4a13 100644 --- a/server/typescript/packages/codegen-ts/test/naming/collection-name.test.ts +++ b/server/typescript/packages/codegen-ts/test/naming/collection-name.test.ts @@ -4,8 +4,7 @@ // it. import { describe, test, expect, afterEach } from "bun:test"; -import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, readFileSync, readdirSync } from "node:fs"; import { join, relative } from "node:path"; import { MetaDataLoader, InMemoryStringSource, collectionNameOf, pluralizer, registerPluralizer, @@ -17,6 +16,7 @@ import { entityFile } from "../../src/generators/entity-file.js"; import { queriesFile } from "../../src/generators/queries-file.js"; import { routesFile } from "../../src/generators/routes-file.js"; import { resourcePath } from "../../src/templates/entity-ui-descriptor.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; type Json = Record; @@ -47,7 +47,7 @@ async function load(historyAttrs: Json = {}): Promise { } async function gen(root: MetaRoot): Promise<{ files: Map; warnings: string[] }> { - const tmp = mkdtempSync(join(tmpdir(), "mo-collection-")); + const tmp = makeScratchDir("mo-collection-"); try { const { warnings } = await runGen({ config: defineConfig({ @@ -65,7 +65,7 @@ async function gen(root: MetaRoot): Promise<{ files: Map; warnin } return { files, warnings }; } finally { - rmSync(tmp, { recursive: true, force: true }); + removeTree(tmp); } } diff --git a/server/typescript/packages/codegen-ts/test/naming/name-claims.test.ts b/server/typescript/packages/codegen-ts/test/naming/name-claims.test.ts index fdf541d466..897d0cb0f0 100644 --- a/server/typescript/packages/codegen-ts/test/naming/name-claims.test.ts +++ b/server/typescript/packages/codegen-ts/test/naming/name-claims.test.ts @@ -5,8 +5,7 @@ // generator that is not wired claims nothing, so a docs-only run refuses nothing. import { describe, test, expect } from "bun:test"; -import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, mkdtempSync, readFileSync, readdirSync } from "node:fs"; import { join, relative, resolve } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource, type MetaObject } from "@metaobjectsdev/metadata"; @@ -23,6 +22,7 @@ import { routesFile } from "../../src/generators/routes-file.js"; import { routesFileHono } from "../../src/generators/routes-file-hono.js"; import { barrel } from "../../src/generators/barrel.js"; import type { OutputLayout } from "../../src/import-path.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; type Json = Record; @@ -58,7 +58,7 @@ async function run( outputLayout: OutputLayout = "flat", extra: { emitAbstractShapes?: boolean } = {}, ): Promise> { - const tmp = mkdtempSync(join(tmpdir(), "name-claims-")); + const tmp = makeScratchDir("name-claims-"); try { await runGen({ config: defineConfig({ @@ -74,7 +74,7 @@ async function run( if (e.isFile()) out.set(relative(src, join(e.parentPath, e.name)), readFileSync(join(e.parentPath, e.name), "utf8")); } return out; - } finally { rmSync(tmp, { recursive: true, force: true }); } + } finally { removeTree(tmp); } } describe("NameClaims", () => { @@ -301,6 +301,6 @@ describe("a value object is never renamed", () => { const diagnostics = ts.getPreEmitDiagnostics(program) .map((d) => `${d.file ? relative(dir, d.file.fileName) : "?"}: TS${d.code} ${ts.flattenDiagnosticMessageText(d.messageText, "\n")}`); expect(diagnostics).toEqual([]); - } finally { rmSync(dir, { recursive: true, force: true }); } + } finally { removeTree(dir); } }); }); diff --git a/server/typescript/packages/codegen-ts/test/no-magic-physical-names.test.ts b/server/typescript/packages/codegen-ts/test/no-magic-physical-names.test.ts index 0631040983..d0f4fdf67b 100644 --- a/server/typescript/packages/codegen-ts/test/no-magic-physical-names.test.ts +++ b/server/typescript/packages/codegen-ts/test/no-magic-physical-names.test.ts @@ -42,8 +42,7 @@ // because it belongs to no field of any object. import { describe, it, expect } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync, readdirSync, statSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, readdirSync, statSync } from "node:fs"; import { join, relative } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { runGen, defineConfig } from "../src/index.js"; @@ -52,6 +51,7 @@ import { barrel } from "../src/generators/barrel.js"; import { entityFile } from "../src/generators/entity-file.js"; import { queriesFile } from "../src/generators/queries-file.js"; import { routesFile } from "../src/generators/routes-file.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; // --------------------------------------------------------------------------- // The de-blinded fixture. @@ -434,7 +434,7 @@ async function generate(dialect: (typeof DIALECTS)[number]): Promise e.message)).toEqual([]); - const dir = mkdtempSync(join(tmpdir(), "no-magic-")); + const dir = makeScratchDir("no-magic-"); try { await runGen({ config: defineConfig({ @@ -452,7 +452,7 @@ async function generate(dialect: (typeof DIALECTS)[number]): Promise { projectRoot = mkdtempSync(join(tmpdir(), "no-manifest-")); }); -afterEach(() => { rmSync(projectRoot, { recursive: true, force: true }); }); +beforeEach(() => { projectRoot = makeScratchDir("no-manifest-"); }); +afterEach(() => { removeTree(projectRoot); }); const genStateDir = (): string => join(projectRoot, ".metaobjects", ".gen-state"); const outDir = (): string => join(projectRoot, "generated"); @@ -50,7 +50,7 @@ async function gen(opts: { dryRun?: boolean } = {}) { /** Drop the whole gen-state: the state of a project whose .gitignore still reads * `.gen-state/`, cloned fresh. */ function dropAllGenState(): void { - rmSync(genStateDir(), { recursive: true, force: true }); + removeTree(genStateDir()); } /** Keep the manifest, drop only the bodies: a MIGRATED project, cloned fresh. */ @@ -59,7 +59,7 @@ function dropBodiesOnly(): void { for (const e of readdirSync(dir)) { const full = join(dir, e); if (e === ".hashes") continue; // the manifest directory is what a clone keeps - if (statSync(full).isDirectory()) { walk(full); rmSync(full, { recursive: true, force: true }); } + if (statSync(full).isDirectory()) { walk(full); removeTree(full); } else if (e !== ".engine.json") rmSync(full, { force: true }); } }; diff --git a/server/typescript/packages/codegen-ts/test/nodenext-safe-imports.test.ts b/server/typescript/packages/codegen-ts/test/nodenext-safe-imports.test.ts index 28576645fd..9543ff4456 100644 --- a/server/typescript/packages/codegen-ts/test/nodenext-safe-imports.test.ts +++ b/server/typescript/packages/codegen-ts/test/nodenext-safe-imports.test.ts @@ -16,7 +16,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, rmSync, readdirSync, readFileSync } from "node:fs"; +import { mkdtempSync, readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { runGen, defineConfig } from "../src/index.js"; @@ -26,6 +26,7 @@ import { entityFile } from "../src/generators/entity-file.js"; import { queriesFile } from "../src/generators/queries-file.js"; import { routesFile } from "../src/generators/routes-file.js"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -104,7 +105,7 @@ describe("generated relative imports are nodenext-safe", () => { await genTo(dir, "js"); expect(extensionErrorsUnderNodeNext(dir)).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); @@ -114,7 +115,7 @@ describe("generated relative imports are nodenext-safe", () => { await genTo(dir, "none"); expect(extensionErrorsUnderNodeNext(dir).length).toBeGreaterThan(0); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); @@ -125,7 +126,7 @@ describe("generated relative imports are nodenext-safe", () => { const routes = readFileSync(join(dir, "Author.routes.ts"), "utf8"); expect(routes).toContain('from "../db.js"'); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); }); diff --git a/server/typescript/packages/codegen-ts/test/orphan-sweep.test.ts b/server/typescript/packages/codegen-ts/test/orphan-sweep.test.ts index 43def1de76..5e5da617ca 100644 --- a/server/typescript/packages/codegen-ts/test/orphan-sweep.test.ts +++ b/server/typescript/packages/codegen-ts/test/orphan-sweep.test.ts @@ -11,24 +11,24 @@ import { setManifestEntry } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, existsSync, writeFileSync, readFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { rmSync, existsSync, writeFileSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { decideAndWrite, listGeneratedPaths } from "../src/overwrite-policy.js"; import { sweepOrphans, type OrphanJob } from "../src/orphan-sweep.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; let root: string; let genStateDir: string; let outDir: string; beforeEach(() => { - root = mkdtempSync(join(tmpdir(), "orphan-sweep-")); + root = makeScratchDir("orphan-sweep-"); genStateDir = join(root, ".gen-state"); outDir = join(root, "src", "generated"); }); afterEach(() => { - rmSync(root, { recursive: true, force: true }); + removeTree(root); }); /** Generate `relPath` (project-relative) the way the runner does. */ diff --git a/server/typescript/packages/codegen-ts/test/out-of-project-output.test.ts b/server/typescript/packages/codegen-ts/test/out-of-project-output.test.ts index 0a82e71374..2e6e5557a1 100644 --- a/server/typescript/packages/codegen-ts/test/out-of-project-output.test.ts +++ b/server/typescript/packages/codegen-ts/test/out-of-project-output.test.ts @@ -12,26 +12,26 @@ import { manifestEntries } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync, readdirSync, existsSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, readdirSync, existsSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; import { runGen } from "../src/runner.js"; import { defineConfig } from "../src/metaobjects-config.js"; import { entityFile } from "../src/generators/entity-file.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const FIXTURE = resolve(import.meta.dir, "fixtures", "single-entity.json"); let projectRoot: string; let elsewhere: string; beforeEach(() => { - projectRoot = mkdtempSync(join(tmpdir(), "oop-project-")); - elsewhere = mkdtempSync(join(tmpdir(), "oop-elsewhere-")); + projectRoot = makeScratchDir("oop-project-"); + elsewhere = makeScratchDir("oop-elsewhere-"); }); afterEach(() => { - rmSync(projectRoot, { recursive: true, force: true }); - rmSync(elsewhere, { recursive: true, force: true }); + removeTree(projectRoot); + removeTree(elsewhere); }); async function genInto(outDir: string) { diff --git a/server/typescript/packages/codegen-ts/test/overwrite-policy.test.ts b/server/typescript/packages/codegen-ts/test/overwrite-policy.test.ts index c99e798229..b279a6c4a0 100644 --- a/server/typescript/packages/codegen-ts/test/overwrite-policy.test.ts +++ b/server/typescript/packages/codegen-ts/test/overwrite-policy.test.ts @@ -4,20 +4,20 @@ import { manifestEntries, seedLegacyManifest } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { writeFileSync, readFileSync, existsSync } from "node:fs"; import { join } from "node:path"; import { contentHash, decideAndWrite, forgetGeneratedPaths, readGeneratedHash } from "../src/overwrite-policy.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; let tmp: string; let state: string; beforeEach(() => { - tmp = mkdtempSync(join(tmpdir(), "codegen-policy-")); - state = mkdtempSync(join(tmpdir(), "codegen-state-")); + tmp = makeScratchDir("codegen-policy-"); + state = makeScratchDir("codegen-state-"); }); afterEach(() => { - rmSync(tmp, { recursive: true, force: true }); - rmSync(state, { recursive: true, force: true }); + removeTree(tmp); + removeTree(state); }); describe("decideAndWrite (three-way merge)", () => { diff --git a/server/typescript/packages/codegen-ts/test/overwrite-policy/clean-merge.test.ts b/server/typescript/packages/codegen-ts/test/overwrite-policy/clean-merge.test.ts index f52ce8704b..24032601ac 100644 --- a/server/typescript/packages/codegen-ts/test/overwrite-policy/clean-merge.test.ts +++ b/server/typescript/packages/codegen-ts/test/overwrite-policy/clean-merge.test.ts @@ -3,20 +3,20 @@ // keeps their edit. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, writeFileSync, readFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { writeFileSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { decideAndWrite } from "../../src/overwrite-policy.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; let tmp: string; let state: string; beforeEach(() => { - tmp = mkdtempSync(join(tmpdir(), "codegen-merge-")); - state = mkdtempSync(join(tmpdir(), "codegen-state-")); + tmp = makeScratchDir("codegen-merge-"); + state = makeScratchDir("codegen-state-"); }); afterEach(() => { - rmSync(tmp, { recursive: true, force: true }); - rmSync(state, { recursive: true, force: true }); + removeTree(tmp); + removeTree(state); }); describe("clean three-way merge", () => { diff --git a/server/typescript/packages/codegen-ts/test/overwrite-policy/conflict.test.ts b/server/typescript/packages/codegen-ts/test/overwrite-policy/conflict.test.ts index eac9aa61c5..17ca5bc74c 100644 --- a/server/typescript/packages/codegen-ts/test/overwrite-policy/conflict.test.ts +++ b/server/typescript/packages/codegen-ts/test/overwrite-policy/conflict.test.ts @@ -3,20 +3,20 @@ // status === "conflict". import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, writeFileSync, readFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { writeFileSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { decideAndWrite } from "../../src/overwrite-policy.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; let tmp: string; let state: string; beforeEach(() => { - tmp = mkdtempSync(join(tmpdir(), "codegen-conflict-")); - state = mkdtempSync(join(tmpdir(), "codegen-state-")); + tmp = makeScratchDir("codegen-conflict-"); + state = makeScratchDir("codegen-state-"); }); afterEach(() => { - rmSync(tmp, { recursive: true, force: true }); - rmSync(state, { recursive: true, force: true }); + removeTree(tmp); + removeTree(state); }); describe("three-way merge — conflict", () => { diff --git a/server/typescript/packages/codegen-ts/test/overwrite-policy/first-time-existing.test.ts b/server/typescript/packages/codegen-ts/test/overwrite-policy/first-time-existing.test.ts index f38458095a..2d4db5f402 100644 --- a/server/typescript/packages/codegen-ts/test/overwrite-policy/first-time-existing.test.ts +++ b/server/typescript/packages/codegen-ts/test/overwrite-policy/first-time-existing.test.ts @@ -16,20 +16,20 @@ // The pristine and no-record cases are covered in detail by pristine-hash.test.ts. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { writeFileSync, readFileSync, existsSync } from "node:fs"; import { join } from "node:path"; import { decideAndWrite } from "../../src/overwrite-policy.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; let tmp: string; let state: string; beforeEach(() => { - tmp = mkdtempSync(join(tmpdir(), "codegen-ftx-")); - state = mkdtempSync(join(tmpdir(), "codegen-state-")); + tmp = makeScratchDir("codegen-ftx-"); + state = makeScratchDir("codegen-state-"); }); afterEach(() => { - rmSync(tmp, { recursive: true, force: true }); - rmSync(state, { recursive: true, force: true }); + removeTree(tmp); + removeTree(state); }); describe("first-time-on-existing-file", () => { diff --git a/server/typescript/packages/codegen-ts/test/overwrite-policy/integrity.test.ts b/server/typescript/packages/codegen-ts/test/overwrite-policy/integrity.test.ts index 7bfd2bea1f..72ecfa0f4f 100644 --- a/server/typescript/packages/codegen-ts/test/overwrite-policy/integrity.test.ts +++ b/server/typescript/packages/codegen-ts/test/overwrite-policy/integrity.test.ts @@ -5,20 +5,20 @@ import { manifestEntries, manifestExists } from "../support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { writeFileSync, readFileSync, existsSync } from "node:fs"; import { join } from "node:path"; import { decideAndWrite } from "../../src/overwrite-policy.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; let tmp: string; let state: string; beforeEach(() => { - tmp = mkdtempSync(join(tmpdir(), "codegen-int-")); - state = mkdtempSync(join(tmpdir(), "codegen-state-")); + tmp = makeScratchDir("codegen-int-"); + state = makeScratchDir("codegen-state-"); }); afterEach(() => { - rmSync(tmp, { recursive: true, force: true }); - rmSync(state, { recursive: true, force: true }); + removeTree(tmp); + removeTree(state); }); describe(".gen-state integrity", () => { diff --git a/server/typescript/packages/codegen-ts/test/overwrite-policy/manifest-once.test.ts b/server/typescript/packages/codegen-ts/test/overwrite-policy/manifest-once.test.ts index 1a9711b388..eba83b8595 100644 --- a/server/typescript/packages/codegen-ts/test/overwrite-policy/manifest-once.test.ts +++ b/server/typescript/packages/codegen-ts/test/overwrite-policy/manifest-once.test.ts @@ -2,21 +2,21 @@ // entry changed; a file whose new bytes equal what is on disk is never rewritten. import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import * as fs from "node:fs"; -import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { readFileSync, statSync, writeFileSync } from "node:fs"; import { isManifestPath, manifestEntries, manifestFiles, manifestMtimes } from "../support/manifest.js"; -import { tmpdir } from "node:os"; import { join } from "node:path"; import { decideAndWrite, mergeTempDir, withManifestBatch } from "../../src/overwrite-policy.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; let out: string; let state: string; beforeEach(() => { - out = mkdtempSync(join(tmpdir(), "codegen-once-")); - state = mkdtempSync(join(tmpdir(), "codegen-once-state-")); + out = makeScratchDir("codegen-once-"); + state = makeScratchDir("codegen-once-state-"); }); afterEach(() => { - rmSync(out, { recursive: true, force: true }); - rmSync(state, { recursive: true, force: true }); + removeTree(out); + removeTree(state); }); function run(files: Record): void { @@ -80,13 +80,13 @@ describe("three-way merge temporaries", () => { let scratch: string; let saved: string | undefined; beforeEach(() => { - scratch = mkdtempSync(join(tmpdir(), "codegen-once-scratch-")); + scratch = makeScratchDir("codegen-once-scratch-"); saved = process.env.DEV_SCRATCH; process.env.DEV_SCRATCH = scratch; }); afterEach(() => { if (saved === undefined) delete process.env.DEV_SCRATCH; else process.env.DEV_SCRATCH = saved; - rmSync(scratch, { recursive: true, force: true }); + removeTree(scratch); }); const leftovers = () => { diff --git a/server/typescript/packages/codegen-ts/test/overwrite-policy/merge-fastpath.test.ts b/server/typescript/packages/codegen-ts/test/overwrite-policy/merge-fastpath.test.ts index bba4125805..e77c6a4784 100644 --- a/server/typescript/packages/codegen-ts/test/overwrite-policy/merge-fastpath.test.ts +++ b/server/typescript/packages/codegen-ts/test/overwrite-policy/merge-fastpath.test.ts @@ -10,8 +10,7 @@ // mergeTempDir(), pointed at a private directory through DEV_SCRATCH. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { contentHash, @@ -20,6 +19,7 @@ import { mergeTempDir, readGeneratedHash, } from "../../src/overwrite-policy.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; const NO_GIT = "/usr/bin/totally-not-a-real-binary-xyz123"; @@ -30,7 +30,7 @@ let prevGit: string | undefined; let prevScratch: string | undefined; beforeEach(() => { - root = mkdtempSync(join(process.env.DEV_SCRATCH || tmpdir(), "codegen-fastpath-")); + root = makeScratchDir("codegen-fastpath-"); out = join(root, "out"); state = join(root, "state"); prevGit = process.env.META_GEN_GIT; @@ -43,7 +43,7 @@ afterEach(() => { else process.env.META_GEN_GIT = prevGit; if (prevScratch === undefined) delete process.env.DEV_SCRATCH; else process.env.DEV_SCRATCH = prevScratch; - rmSync(root, { recursive: true, force: true }); + removeTree(root); }); const opts = () => ({ genStateDir: state, outputRelPath: "User.ts" }); diff --git a/server/typescript/packages/codegen-ts/test/overwrite-policy/missing-git.test.ts b/server/typescript/packages/codegen-ts/test/overwrite-policy/missing-git.test.ts index 6e89012997..b09d760bbc 100644 --- a/server/typescript/packages/codegen-ts/test/overwrite-policy/missing-git.test.ts +++ b/server/typescript/packages/codegen-ts/test/overwrite-policy/missing-git.test.ts @@ -7,22 +7,22 @@ // which Bun does not always honor for spawnSync resolution. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { writeFileSync } from "node:fs"; import { join } from "node:path"; import { decideAndWrite, GitMissingError } from "../../src/overwrite-policy.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; let tmp: string; let state: string; let prevGit: string | undefined; beforeEach(() => { - tmp = mkdtempSync(join(tmpdir(), "codegen-nogit-")); - state = mkdtempSync(join(tmpdir(), "codegen-state-")); + tmp = makeScratchDir("codegen-nogit-"); + state = makeScratchDir("codegen-state-"); prevGit = process.env.META_GEN_GIT; }); afterEach(() => { - rmSync(tmp, { recursive: true, force: true }); - rmSync(state, { recursive: true, force: true }); + removeTree(tmp); + removeTree(state); if (prevGit !== undefined) { process.env.META_GEN_GIT = prevGit; } else { diff --git a/server/typescript/packages/codegen-ts/test/overwrite-policy/pristine-hash.test.ts b/server/typescript/packages/codegen-ts/test/overwrite-policy/pristine-hash.test.ts index f3b54697b5..84a88dc7bf 100644 --- a/server/typescript/packages/codegen-ts/test/overwrite-policy/pristine-hash.test.ts +++ b/server/typescript/packages/codegen-ts/test/overwrite-policy/pristine-hash.test.ts @@ -23,8 +23,7 @@ import { manifestFiles } from "../support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { rmSync, writeFileSync, readFileSync, existsSync } from "node:fs"; import { join } from "node:path"; import { decideAndWrite, @@ -32,17 +31,18 @@ import { contentHash, listGeneratedPaths, } from "../../src/overwrite-policy.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; let tmp: string; let state: string; beforeEach(() => { - tmp = mkdtempSync(join(tmpdir(), "codegen-pristine-")); - state = mkdtempSync(join(tmpdir(), "codegen-pristine-state-")); + tmp = makeScratchDir("codegen-pristine-"); + state = makeScratchDir("codegen-pristine-state-"); }); afterEach(() => { - rmSync(tmp, { recursive: true, force: true }); - rmSync(state, { recursive: true, force: true }); + removeTree(tmp); + removeTree(state); }); /** Simulate the fresh-clone shape: the committed manifest survives, the diff --git a/server/typescript/packages/codegen-ts/test/owned-generator-skew-compile.test.ts b/server/typescript/packages/codegen-ts/test/owned-generator-skew-compile.test.ts index 73d850c2be..6fa2f8cf14 100644 --- a/server/typescript/packages/codegen-ts/test/owned-generator-skew-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/owned-generator-skew-compile.test.ts @@ -15,7 +15,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, rmSync, readdirSync } from "node:fs"; +import { mkdtempSync, readdirSync } from "node:fs"; import { join, resolve } from "node:path"; import ts from "typescript"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; @@ -26,6 +26,7 @@ import { entityFile as currentEntity } from "../src/reference/entity.js"; import { queriesFile as currentQueries } from "../src/reference/queries.js"; import { entityFile as ownedEntity108 } from "./fixtures/owned-1.0.8/entity.js"; import { queriesFile as ownedQueries108 } from "./fixtures/owned-1.0.8/queries.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -77,7 +78,7 @@ for (const dialect of ["sqlite", "postgres"] as const) { }); expect(compile(dir)).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }, 60_000); } diff --git a/server/typescript/packages/codegen-ts/test/ownership-seam.test.ts b/server/typescript/packages/codegen-ts/test/ownership-seam.test.ts index 4ac280a454..c2c03d7e3b 100644 --- a/server/typescript/packages/codegen-ts/test/ownership-seam.test.ts +++ b/server/typescript/packages/codegen-ts/test/ownership-seam.test.ts @@ -16,8 +16,7 @@ import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync, writeFileSync, readdirSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, writeFileSync, readdirSync } from "node:fs"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { runGen, defineConfig } from "../src/index.js"; @@ -27,10 +26,11 @@ import { barrel } from "../src/generators/barrel.js"; import { entityFile } from "../src/generators/entity-file.js"; import { renderRequirementTest } from "../src/templates/requirement-test.js"; import type { RequirementTestArgs } from "../src/templates/requirement-test.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; let tmp: string; -beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "codegen-ownership-seam-")); }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +beforeEach(() => { tmp = makeScratchDir("codegen-ownership-seam-"); }); +afterEach(() => { removeTree(tmp); }); const MODEL = { "metadata.root": { @@ -101,7 +101,7 @@ function dropSnapshotBodies(projectRoot: string): void { const genState = join(projectRoot, ".metaobjects", ".gen-state"); for (const entry of readdirSync(genState)) { if (entry !== ".hashes") { - rmSync(join(genState, entry), { recursive: true, force: true }); + removeTree(join(genState, entry)); } } expect(readdirSync(genState)).toEqual([".hashes"]); diff --git a/server/typescript/packages/codegen-ts/test/prisma/prisma-schema.test.ts b/server/typescript/packages/codegen-ts/test/prisma/prisma-schema.test.ts index b1d08db54b..ccdec00fd0 100644 --- a/server/typescript/packages/codegen-ts/test/prisma/prisma-schema.test.ts +++ b/server/typescript/packages/codegen-ts/test/prisma/prisma-schema.test.ts @@ -5,8 +5,7 @@ // tests. Refresh the goldens with UPDATE_GOLDEN=1. import { afterEach, beforeEach, describe, expect, test } from "bun:test"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { InMemoryStringSource, MetaDataLoader, type MetaRoot } from "@metaobjectsdev/metadata"; import { defineConfig, runGen, type Generator } from "../../src/index.js"; @@ -24,6 +23,7 @@ import { ERR_PRISMA_NO_PRIMARY_KEY, PrismaSchemaError, } from "../../src/prisma/prisma-errors.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; const UPDATE = process.env.UPDATE_GOLDEN === "1"; const SHOP = join(import.meta.dir, "fixtures", "shop", "metaobjects", "meta.shop.json"); @@ -33,10 +33,10 @@ type Json = Record; let tmp: string; beforeEach(() => { - tmp = mkdtempSync(join(tmpdir(), "prisma-schema-")); + tmp = makeScratchDir("prisma-schema-"); }); afterEach(() => { - rmSync(tmp, { recursive: true, force: true }); + removeTree(tmp); }); async function loadJson(text: string): Promise { diff --git a/server/typescript/packages/codegen-ts/test/projection/compile.test.ts b/server/typescript/packages/codegen-ts/test/projection/compile.test.ts index fbdfd832c0..f0de06bd3e 100644 --- a/server/typescript/packages/codegen-ts/test/projection/compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/compile.test.ts @@ -9,7 +9,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "../compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; @@ -19,6 +19,7 @@ import { makeRenderContext } from "../../src/render-context.js"; import { buildPkMap } from "../../src/pk-resolver.js"; import { buildRelationMap } from "../../src/relation-resolver.js"; import type { GenContext } from "../../src/generator.js"; +import { removeTree } from "../../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -134,7 +135,7 @@ describe("projection codegen compiles (TS2724 regression guard)", () => { const diagnostics = compile(dir, files.map((f) => f.path)); expect(diagnostics.map((d) => ts.flattenDiagnosticMessageText(d.messageText, "\n"))).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); }); diff --git a/server/typescript/packages/codegen-ts/test/projection/int-enum-replica-view-no-dup.test.ts b/server/typescript/packages/codegen-ts/test/projection/int-enum-replica-view-no-dup.test.ts index 59eb6401d7..5db9f09500 100644 --- a/server/typescript/packages/codegen-ts/test/projection/int-enum-replica-view-no-dup.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/int-enum-replica-view-no-dup.test.ts @@ -7,7 +7,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "../compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; @@ -16,6 +16,7 @@ import { makeRenderContext } from "../../src/render-context.js"; import { buildPkMap } from "../../src/pk-resolver.js"; import { buildRelationMap } from "../../src/relation-resolver.js"; import type { GenContext } from "../../src/generator.js"; +import { removeTree } from "../../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -103,7 +104,7 @@ describe("write-through entity: table + replica view in one module", () => { ), ).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); } diff --git a/server/typescript/packages/codegen-ts/test/projection/int-enum-view-compile.test.ts b/server/typescript/packages/codegen-ts/test/projection/int-enum-view-compile.test.ts index ec52a62163..96a5cbda60 100644 --- a/server/typescript/packages/codegen-ts/test/projection/int-enum-view-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/int-enum-view-compile.test.ts @@ -18,7 +18,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "../compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; @@ -27,6 +27,7 @@ import { makeRenderContext } from "../../src/render-context.js"; import { buildPkMap } from "../../src/pk-resolver.js"; import { buildRelationMap } from "../../src/relation-resolver.js"; import type { GenContext } from "../../src/generator.js"; +import { removeTree } from "../../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -148,7 +149,7 @@ describe("view-backed read model with an int-backed field.enum", () => { diagnostics.map((d) => ts.flattenDiagnosticMessageText(d.messageText, "\n")), ).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); } diff --git a/server/typescript/packages/codegen-ts/test/projection/issue-214-read-half-compile.test.ts b/server/typescript/packages/codegen-ts/test/projection/issue-214-read-half-compile.test.ts index d8eca4090e..55e012ce8a 100644 --- a/server/typescript/packages/codegen-ts/test/projection/issue-214-read-half-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/issue-214-read-half-compile.test.ts @@ -9,7 +9,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "../compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource, type MetaObject } from "@metaobjectsdev/metadata"; @@ -22,6 +22,7 @@ import { entityFile as refEntityFile } from "../../src/reference/entity.js"; import { queriesFile as refQueriesFile } from "../../src/reference/queries.js"; import type { GenContext } from "../../src/generator.js"; import type { Dialect } from "../../src/metaobjects-config.js"; +import { removeTree } from "../../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -170,7 +171,7 @@ describe("#214 — the generated read-half output type-checks (verbatimModuleSyn const messages = diagnostics.map((d) => ts.flattenDiagnosticMessageText(d.messageText, "\n")); expect(messages).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); } diff --git a/server/typescript/packages/codegen-ts/test/prompt-generator-gate.test.ts b/server/typescript/packages/codegen-ts/test/prompt-generator-gate.test.ts index 661f03610d..c5002b6b02 100644 --- a/server/typescript/packages/codegen-ts/test/prompt-generator-gate.test.ts +++ b/server/typescript/packages/codegen-ts/test/prompt-generator-gate.test.ts @@ -14,14 +14,13 @@ // warning only, and self-extinguishing so a deliberate choice is never nagged. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import type { Generator } from "../src/generator.js"; import { warnMissingPromptGenerators } from "../src/prompt-generator-gate.js"; import { runGen } from "../src/runner.js"; import { docsFile } from "../src/generators/index.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const MODEL = { "metadata.root": { @@ -168,8 +167,8 @@ describe("A3 — declared prompts with no prompt generator wired", () => { // named itself, because `docsFile()` emits documentation either way. describe("A3 — the runner reads a docs-only config as emitting no code", () => { let tmp: string; - beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "prompt-gate-docs-only-")); }); - afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); + beforeEach(() => { tmp = makeScratchDir("prompt-gate-docs-only-"); }); + afterEach(() => { removeTree(tmp); }); async function promptWarnings(generators: Generator[], targetName: string): Promise { const result = await runGen({ diff --git a/server/typescript/packages/codegen-ts/test/reference-binding-compile.test.ts b/server/typescript/packages/codegen-ts/test/reference-binding-compile.test.ts index 3aaa353af0..f540e6edaa 100644 --- a/server/typescript/packages/codegen-ts/test/reference-binding-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-binding-compile.test.ts @@ -14,7 +14,7 @@ import { describe, expect, test, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { InMemoryStringSource, MetaDataLoader, type MetaObject, type MetaRoot } from "@metaobjectsdev/metadata"; @@ -27,6 +27,7 @@ import { makeRenderContext } from "../src/render-context.js"; import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { EmittedFile, GenContext } from "../src/generator.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -126,7 +127,7 @@ describe("a reference whose other side is the entity's own table, or an ancestor `${d.file?.fileName.slice(dir.length + 1) ?? ""} ${ts.flattenDiagnosticMessageText(d.messageText, "\n")}`); expect(diagnostics).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); 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 fbb5ecab01..940687c421 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 @@ -4,8 +4,7 @@ // if this passes, a consumer can copy them out and own them with no behavior change. import { describe, test, expect, beforeEach, afterEach, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { existsSync, mkdirSync, mkdtempSync, rmSync, readdirSync, readFileSync, cpSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, mkdirSync, readdirSync, readFileSync, cpSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { runGen, defineConfig, REFERENCE_GENERATOR_NAMES, HTTP_RUNTIME_PACKAGE, OWNED_RUNTIME_DIR, @@ -80,6 +79,7 @@ import { import type { RequirementTestArgs, RequirementTestsOpts } from "../src/index.js"; import { MetaDataLoader, InMemoryStringSource, isMetaSource, isReadOnlySource, type MetaObject } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -117,8 +117,8 @@ const FIXTURES = [ const ROUTE_SHAPE_CORPORA = ["projection", "write-through", "m2m", "tph", "jsonb"] as const; let tmp: string; -beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "codegen-ref-")); }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +beforeEach(() => { tmp = makeScratchDir("codegen-ref-"); }); +afterEach(() => { removeTree(tmp); }); async function gen( dir: string, @@ -257,8 +257,8 @@ describe("ADR-0034 — reference templates are byte-identical to built-ins", () const result = await loader.load([new FileSource(join(FIXTURE_DIR, fixture))]); expect(result.errors).toEqual([]); - const aDir = mkdtempSync(join(tmpdir(), "codegen-builtin-")); - const bDir = mkdtempSync(join(tmpdir(), "codegen-reference-")); + const aDir = makeScratchDir("codegen-builtin-"); + const bDir = makeScratchDir("codegen-reference-"); try { // routes-hono emits `.routes.hono.ts`, so it does not collide with // routesFile()'s `.routes.ts` and both ride the same run. @@ -273,8 +273,8 @@ describe("ADR-0034 — reference templates are byte-identical to built-ins", () expect(`${k}:\n${b[k]}`).toBe(`${k}:\n${a[k]}`); } } finally { - rmSync(aDir, { recursive: true, force: true }); - rmSync(bDir, { recursive: true, force: true }); + removeTree(aDir); + removeTree(bDir); } }); } @@ -290,8 +290,8 @@ describe("ADR-0034 — the route composition, over every shape it dispatches on" for (const corpus of ROUTE_SHAPE_CORPORA) { test(`api-contract ${corpus} corpus`, async () => { const root = await loadFiles([join(REPO_FIXTURES, "api-contract-conformance", corpus, "meta.json")]); - const aDir = mkdtempSync(join(tmpdir(), "codegen-builtin-")); - const bDir = mkdtempSync(join(tmpdir(), "codegen-reference-")); + const aDir = makeScratchDir("codegen-builtin-"); + const bDir = makeScratchDir("codegen-reference-"); try { const names = ["entity", "routes", "routes-hono"] as const; const a = await gen(aDir, names.map((n) => PAIRS[n].builtin()), root); @@ -301,8 +301,8 @@ describe("ADR-0034 — the route composition, over every shape it dispatches on" expect(Object.keys(b).sort()).toEqual(aKeys); for (const k of aKeys) expect(`${k}:\n${b[k]}`).toBe(`${k}:\n${a[k]}`); } finally { - rmSync(aDir, { recursive: true, force: true }); - rmSync(bDir, { recursive: true, force: true }); + removeTree(aDir); + removeTree(bDir); } }); } @@ -312,8 +312,8 @@ describe("ADR-0034 — report-export and the routes it wires, over the report co for (const options of [undefined, { maxRows: 60, xmlNulls: "nil", csvBom: true }] as const) { test(`options ${JSON.stringify(options)}`, async () => { const root = await loadFiles([join(REPO_FIXTURES, "api-contract-conformance", "report", "meta.json")]); - const aDir = mkdtempSync(join(tmpdir(), "codegen-builtin-")); - const bDir = mkdtempSync(join(tmpdir(), "codegen-reference-")); + const aDir = makeScratchDir("codegen-builtin-"); + const bDir = makeScratchDir("codegen-reference-"); try { const a = await gen(aDir, [builtinEntity(), builtinRoutes(), builtinRoutesHono(), builtinReportExport(options)], root); const b = await gen(bDir, [refEntity(PKG), refRoutes(PKG), refRoutesHono(PKG), refReportExport(options)], root); @@ -325,22 +325,22 @@ describe("ADR-0034 — report-export and the routes it wires, over the report co expect(Object.keys(b).sort()).toEqual(aKeys); for (const k of aKeys) expect(`${k}:\n${b[k]}`).toBe(`${k}:\n${a[k]}`); } finally { - rmSync(aDir, { recursive: true, force: true }); - rmSync(bDir, { recursive: true, force: true }); + removeTree(aDir); + removeTree(bDir); } }); } test("with no report-export wired, a report's routes carry no export branch", async () => { const root = await loadFiles([join(REPO_FIXTURES, "api-contract-conformance", "report", "meta.json")]); - const dir = mkdtempSync(join(tmpdir(), "codegen-builtin-")); + const dir = makeScratchDir("codegen-builtin-"); try { const out = await gen(dir, [builtinEntity(), builtinRoutes(), builtinRoutesHono()], root); expect(out["ExportCells.routes.ts"]).not.toContain("ExportCellsExport"); expect(out["ExportCells.routes.hono.ts"]).not.toContain("ExportCellsExport"); expect(Object.keys(out).some((k) => k.includes(".export.") || k.startsWith("report-export"))).toBe(false); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); }); @@ -357,7 +357,7 @@ describe("ADR-0034 Amendment 3 — an ejected generator's output imports the OWN for (const corpus of ROUTE_SHAPE_CORPORA) { test(`api-contract ${corpus} corpus`, async () => { const root = await loadFiles([join(REPO_FIXTURES, "api-contract-conformance", corpus, "meta.json")]); - const projectRoot = mkdtempSync(join(tmpdir(), "codegen-owned-runtime-")); + const projectRoot = makeScratchDir("codegen-owned-runtime-"); const aDir = join(projectRoot, "builtin", "gen"); const bDir = join(projectRoot, "src", "gen"); try { @@ -395,7 +395,7 @@ describe("ADR-0034 Amendment 3 — an ejected generator's output imports the OWN // Vacuity guard: the corpus must actually exercise the moved import. expect(importing).toBeGreaterThan(0); } finally { - rmSync(projectRoot, { recursive: true, force: true }); + removeTree(projectRoot); } }); } @@ -410,9 +410,9 @@ describe("ADR-0034 — the prompt-tier reference templates over corpora that dec const result = await loader.load(corpus.files.map((f) => new FileSource(f))); expect(result.errors).toEqual([]); - const aDir = mkdtempSync(join(tmpdir(), "codegen-builtin-")); - const bDir = mkdtempSync(join(tmpdir(), "codegen-reference-")); - const projectRoot = mkdtempSync(join(tmpdir(), "codegen-project-")); + const aDir = makeScratchDir("codegen-builtin-"); + const bDir = makeScratchDir("codegen-reference-"); + const projectRoot = makeScratchDir("codegen-project-"); if (corpus.templatesDir !== undefined) { cpSync(corpus.templatesDir, join(projectRoot, "templates"), { recursive: true }); } @@ -434,9 +434,9 @@ describe("ADR-0034 — the prompt-tier reference templates over corpora that dec expect(`${k}:\n${b[k]}`).toBe(`${k}:\n${a[k]}`); } } finally { - rmSync(aDir, { recursive: true, force: true }); - rmSync(bDir, { recursive: true, force: true }); - rmSync(projectRoot, { recursive: true, force: true }); + removeTree(aDir); + removeTree(bDir); + removeTree(projectRoot); } }); } @@ -595,7 +595,7 @@ describe("ADR-0034 — the requirement-tests reference over a ledger that declar expect(loaded.errors).toEqual([]); const emit = async (generator: Generator) => { - const dir = mkdtempSync(join(tmpdir(), "codegen-req-")); + const dir = makeScratchDir("codegen-req-"); try { const result = await runGen({ config: defineConfig({ outputLayout: "flat", outDir: join(dir, "out"), extStyle: "none", dbImport: "~/server/db", dialect: "sqlite", generators: [generator] }), @@ -610,7 +610,7 @@ describe("ADR-0034 — the requirement-tests reference over a ledger that declar } return { files, warnings: result.warnings }; } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }; @@ -894,7 +894,7 @@ describe("ADR-0034 — the cube-model reference is byte-identical to the built-i const root = await loadModelFile(CANONICAL_MODEL); // The canonical corpus declares literal columns in its .metaobjects/config.json (ADR-0058). root.physicalNaming = { columns: "literal", tables: "snake_case" }; - const dir = mkdtempSync(join(tmpdir(), "cube-ref-run-")); + const dir = makeScratchDir("cube-ref-run-"); try { await runGen({ config: defineConfig({ outputLayout: "flat", outDir: join(dir, "out"), dialect: config.dialect, generators: [make()] }), @@ -904,7 +904,7 @@ describe("ADR-0034 — the cube-model reference is byte-identical to the built-i }); return [...readCubeTree(join(dir, "out")).entries()]; } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } @@ -1072,8 +1072,8 @@ describe("ADR-0034 — the callable and trace-helper reference templates over mo emitted: RegExp, expected: number, ) { - const aDir = mkdtempSync(join(tmpdir(), "codegen-builtin-")); - const bDir = mkdtempSync(join(tmpdir(), "codegen-reference-")); + const aDir = makeScratchDir("codegen-builtin-"); + const bDir = makeScratchDir("codegen-reference-"); try { const a = await gen(aDir, names.map((n) => PAIRS[n].builtin()), root); const b = await gen(bDir, names.map((n) => PAIRS[n].ref()), root); @@ -1083,8 +1083,8 @@ describe("ADR-0034 — the callable and trace-helper reference templates over mo expect(Object.keys(b).sort()).toEqual(aKeys); for (const k of aKeys) expect(`${k}:\n${b[k]}`).toBe(`${k}:\n${a[k]}`); } finally { - rmSync(aDir, { recursive: true, force: true }); - rmSync(bDir, { recursive: true, force: true }); + removeTree(aDir); + removeTree(bDir); } } @@ -1145,7 +1145,7 @@ describe("ADR-0034 Amendment 7 — the shared-model reference publishes the same opts: Opts, run: { model: string; sourceFiles?: readonly string[]; packageVersion?: string }, ): Promise { - const project = mkdtempSync(join(tmpdir(), "codegen-shared-")); + const project = makeScratchDir("codegen-shared-"); try { if (run.packageVersion !== undefined) { writeFileSync(join(project, "package.json"), JSON.stringify({ name: "p", version: run.packageVersion })); @@ -1163,7 +1163,7 @@ describe("ADR-0034 Amendment 7 — the shared-model reference publishes the same return readdirSync(outDir).sort().map((f): [string, string] => [f, readFileSync(join(outDir, f), "utf-8")]); }); } finally { - rmSync(project, { recursive: true, force: true }); + removeTree(project); } } @@ -1601,8 +1601,8 @@ describe("ADR-0034 — the prisma-schema reference is byte-identical to the buil for (const c of CASES) { test(c.label, async () => { const root = await loadFiles([SHOP]); - const aDir = mkdtempSync(join(tmpdir(), "prisma-builtin-")); - const bDir = mkdtempSync(join(tmpdir(), "prisma-reference-")); + const aDir = makeScratchDir("prisma-builtin-"); + const bDir = makeScratchDir("prisma-reference-"); try { const a = await gen(aDir, [builtinPrismaSchema(c.opts)], root); const b = await gen(bDir, [refPrismaSchema(c.opts)], root); @@ -1611,15 +1611,15 @@ describe("ADR-0034 — the prisma-schema reference is byte-identical to the buil expect(written(b)).toEqual(c.files); for (const k of c.files) expect(`${k}:\n${b[k]}`).toBe(`${k}:\n${a[k]}`); } finally { - rmSync(aDir, { recursive: true, force: true }); - rmSync(bDir, { recursive: true, force: true }); + removeTree(aDir); + removeTree(bDir); } }); } test("both refuse a CHECK on sqlite with the same message", async () => { const root = await loadFiles([SHOP]); - const dir = mkdtempSync(join(tmpdir(), "prisma-refuse-")); + const dir = makeScratchDir("prisma-refuse-"); try { const message = async (g: Generator): Promise => { try { @@ -1634,7 +1634,7 @@ describe("ADR-0034 — the prisma-schema reference is byte-identical to the buil expect(a).toContain("ERR_PRISMA_UNSUPPORTED_CHECK"); expect(b).toBe(a); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); }); diff --git a/server/typescript/packages/codegen-ts/test/reference-entity-scope-e2e.test.ts b/server/typescript/packages/codegen-ts/test/reference-entity-scope-e2e.test.ts index df61cfb6c2..595b3cdac5 100644 --- a/server/typescript/packages/codegen-ts/test/reference-entity-scope-e2e.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-entity-scope-e2e.test.ts @@ -21,12 +21,12 @@ // emitted. Without a `scope` predicate (undefined), nothing is excluded and // `enums.ts` must carry `Status` — proving the ternary's OTHER branch too. import { describe, test, expect, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, readdirSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readdirSync } from "node:fs"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { runGen, defineConfig } from "../src/index.js"; import { entityFile as refEntity } from "../src/reference/entity.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const LIB = { "metadata.root": { @@ -78,13 +78,13 @@ async function loadRoot() { let dirs: string[] = []; afterEach(() => { - for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); + for (const d of dirs.splice(0)) removeTree(d); }); describe("src/reference/entity.ts — ctx.select call site, end to end via runGen", () => { test("a scope excluding the enum's only consumer suppresses enums.ts entirely", async () => { const root = await loadRoot(); - const dir = mkdtempSync(join(tmpdir(), "ref-entity-scope-")); + const dir = makeScratchDir("ref-entity-scope-"); dirs.push(dir); await runGen({ @@ -107,7 +107,7 @@ describe("src/reference/entity.ts — ctx.select call site, end to end via runGe test("with no scope declared, the same shared enum still materializes", async () => { const root = await loadRoot(); - const dir = mkdtempSync(join(tmpdir(), "ref-entity-noscope-")); + const dir = makeScratchDir("ref-entity-noscope-"); dirs.push(dir); await runGen({ diff --git a/server/typescript/packages/codegen-ts/test/render-engine/framework-provider.test.ts b/server/typescript/packages/codegen-ts/test/render-engine/framework-provider.test.ts index 679bd46575..b89b97046d 100644 --- a/server/typescript/packages/codegen-ts/test/render-engine/framework-provider.test.ts +++ b/server/typescript/packages/codegen-ts/test/render-engine/framework-provider.test.ts @@ -5,8 +5,7 @@ // adopters' overrides would be ignored. import { describe, test, expect, afterEach } from "bun:test"; -import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { @@ -15,18 +14,19 @@ import { projectProvider, frameworkTemplatesDirForTests, } from "../../src/render-engine/framework-provider.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; const tmpDirs: string[] = []; afterEach(() => { while (tmpDirs.length > 0) { const dir = tmpDirs.pop()!; - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); function makeTempProject(): string { - const dir = mkdtempSync(join(tmpdir(), "mo-fwprov-")); + const dir = makeScratchDir("mo-fwprov-"); tmpDirs.push(dir); return dir; } diff --git a/server/typescript/packages/codegen-ts/test/render-helper-codegen.test.ts b/server/typescript/packages/codegen-ts/test/render-helper-codegen.test.ts index b9ada72cdb..19abe96e92 100644 --- a/server/typescript/packages/codegen-ts/test/render-helper-codegen.test.ts +++ b/server/typescript/packages/codegen-ts/test/render-helper-codegen.test.ts @@ -10,15 +10,16 @@ // ERR_VAR_NOT_ON_PAYLOAD naming the offending field. import { describe, test, expect, afterAll } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { InMemoryProvider, type EmailDocument } from "@metaobjectsdev/render"; import { renderRenderHelper } from "../src/templates/render-helper.js"; +import { removeTree } from "../src/scratch-dir.js"; const TEMP_DIRS: string[] = []; afterAll(() => { - for (const d of TEMP_DIRS) rmSync(d, { recursive: true, force: true }); + for (const d of TEMP_DIRS) removeTree(d); }); async function loadRoot(children: unknown[]) { diff --git a/server/typescript/packages/codegen-ts/test/render-helper-conformance.test.ts b/server/typescript/packages/codegen-ts/test/render-helper-conformance.test.ts index baa8ec8113..32acc14bc5 100644 --- a/server/typescript/packages/codegen-ts/test/render-helper-conformance.test.ts +++ b/server/typescript/packages/codegen-ts/test/render-helper-conformance.test.ts @@ -12,7 +12,7 @@ // Java half; both assert IDENTICAL strings). import { describe, test, expect, afterAll } from "bun:test"; -import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from "node:fs"; +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { type EmailDocument } from "@metaobjectsdev/render"; @@ -23,13 +23,14 @@ import { makeRenderContext } from "../src/render-context.js"; import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { GenContext } from "../src/generator.js"; +import { removeTree } from "../src/scratch-dir.js"; // test → codegen-ts → packages → typescript → server → repo-root/fixtures const CORPUS = resolve(import.meta.dir, "../../../../../fixtures/template-output-render-conformance"); const TEMP_DIRS: string[] = []; afterAll(() => { - for (const d of TEMP_DIRS) rmSync(d, { recursive: true, force: true }); + for (const d of TEMP_DIRS) removeTree(d); }); async function loadRootFromFile(metaJsonPath: string) { diff --git a/server/typescript/packages/codegen-ts/test/report-export.test.ts b/server/typescript/packages/codegen-ts/test/report-export.test.ts index f9e3d7dab9..38f3bf0af1 100644 --- a/server/typescript/packages/codegen-ts/test/report-export.test.ts +++ b/server/typescript/packages/codegen-ts/test/report-export.test.ts @@ -1,12 +1,12 @@ // The report-export shared writer module: emitted text is imported and exercised, so what is // tested is what an adopter's project would run. import { describe, expect, test } from "bun:test"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { writeFileSync } from "node:fs"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { renderExportWriters } from "../src/templates/report-export-file.js"; import { reportExport } from "../src/generators/report-export-file.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; interface Writers { EXPORT_CSV_BOM: boolean; @@ -19,13 +19,13 @@ interface Writers { } async function load(opts: { maxRows: number; xmlNulls: "empty" | "nil"; csvBom: boolean }): Promise { - const dir = mkdtempSync(join(tmpdir(), "report-export-writers-")); + const dir = makeScratchDir("report-export-writers-"); try { const file = join(dir, `w-${Math.random().toString(36).slice(2)}.ts`); writeFileSync(file, renderExportWriters(opts)); return (await import(pathToFileURL(file).href)) as Writers; } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } diff --git a/server/typescript/packages/codegen-ts/test/requirement-orphans-e2e.test.ts b/server/typescript/packages/codegen-ts/test/requirement-orphans-e2e.test.ts index cd67e25cbe..902ee733fa 100644 --- a/server/typescript/packages/codegen-ts/test/requirement-orphans-e2e.test.ts +++ b/server/typescript/packages/codegen-ts/test/requirement-orphans-e2e.test.ts @@ -10,12 +10,12 @@ // deleting a requirement between them, and asserts on the files left on disk. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource, type MetaRoot } from "@metaobjectsdev/metadata"; import { runGen } from "../src/runner.js"; import { requirementTests } from "../src/generators/requirement-tests.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const OUT_DIR = "tests"; @@ -63,11 +63,11 @@ const KEEP_STUB = join(OUT_DIR, "requirements", "keep.object.entity.test.ts"); const DROP_STUB = join(OUT_DIR, "requirements", "drop.object.entity.test.ts"); beforeEach(() => { - projectRoot = mkdtempSync(join(tmpdir(), "req-orphan-e2e-")); + projectRoot = makeScratchDir("req-orphan-e2e-"); }); afterEach(() => { - rmSync(projectRoot, { recursive: true, force: true }); + removeTree(projectRoot); }); interface GenOpts { diff --git a/server/typescript/packages/codegen-ts/test/requirement-stub-executes.test.ts b/server/typescript/packages/codegen-ts/test/requirement-stub-executes.test.ts index 574b85f578..5bb72651d4 100644 --- a/server/typescript/packages/codegen-ts/test/requirement-stub-executes.test.ts +++ b/server/typescript/packages/codegen-ts/test/requirement-stub-executes.test.ts @@ -6,11 +6,11 @@ // tests WRITE the generated stub to disk and RUN it, asserting on the exit code. import { describe, test, expect } from "bun:test"; -import { mkdtempSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { writeFileSync } from "node:fs"; import { join } from "node:path"; import { renderRequirementTest } from "../src/templates/requirement-test.js"; import type { RequirementTestArgs } from "../src/templates/requirement-test.js"; +import { makeScratchDir } from "../src/scratch-dir.js"; function args(status: string): RequirementTestArgs { return { @@ -36,7 +36,7 @@ function args(status: string): RequirementTestArgs { } function runStub(src: string): { code: number; out: string } { - const dir = mkdtempSync(join(tmpdir(), "req-stub-")); + const dir = makeScratchDir("req-stub-"); const file = join(dir, "stub.test.ts"); writeFileSync(file, src); const r = Bun.spawnSync(["bun", "test", file], { cwd: dir }); diff --git a/server/typescript/packages/codegen-ts/test/requirement-test-escaping.test.ts b/server/typescript/packages/codegen-ts/test/requirement-test-escaping.test.ts index 3ddeee42d7..77b3873579 100644 --- a/server/typescript/packages/codegen-ts/test/requirement-test-escaping.test.ts +++ b/server/typescript/packages/codegen-ts/test/requirement-test-escaping.test.ts @@ -15,10 +15,10 @@ import { REQUIREMENT_STATUSES_REQUIRING_LIVE_NODES, type RequirementStatus, } from "@metaobjectsdev/metadata"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { writeFileSync } from "node:fs"; import { join } from "node:path"; import { renderRequirementTest } from "../src/templates/requirement-test.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const view = { subType: "functional", @@ -52,14 +52,14 @@ function render(statement: string, counterexample: string): string { /** Write the stub and run it, returning bun's exit code and combined output. */ function runStub(src: string): { code: number; out: string } { - const dir = mkdtempSync(join(tmpdir(), "req-escape-")); + const dir = makeScratchDir("req-escape-"); try { const file = join(dir, "stub.test.ts"); writeFileSync(file, src); const r = Bun.spawnSync(["bun", "test", file], { cwd: dir }); return { code: r.exitCode, out: r.stdout.toString() + r.stderr.toString() }; } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } diff --git a/server/typescript/packages/codegen-ts/test/retired-codegen-attrs.test.ts b/server/typescript/packages/codegen-ts/test/retired-codegen-attrs.test.ts index 58a0413b00..d760449cee 100644 --- a/server/typescript/packages/codegen-ts/test/retired-codegen-attrs.test.ts +++ b/server/typescript/packages/codegen-ts/test/retired-codegen-attrs.test.ts @@ -12,8 +12,6 @@ // even wired. import { describe, test, expect } from "bun:test"; -import { mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource, retiredAttr, type MetaRoot } from "@metaobjectsdev/metadata"; import { runGen } from "../src/runner.js"; @@ -22,6 +20,7 @@ import { RETIRED_CODEGEN_ATTRS } from "../src/constants.js"; import { warnRetiredCodegenAttrs } from "../src/retired-codegen-attrs.js"; import { entityFile } from "../src/generators/entity-file.js"; import { routesFile } from "../src/generators/routes-file.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; /** An entity carrying `attrs` verbatim, source-backed so it reaches every generator. */ function entity(name: string, attrs: Record = {}): unknown { @@ -52,7 +51,7 @@ async function loadRoot(...children: unknown[]): Promise { /** Collect the warnings a real `runGen` produces, generating into a throwaway dir. */ async function warningsFrom(root: MetaRoot, generators = [entityFile()]): Promise { - const dir = mkdtempSync(join(tmpdir(), "retired-attrs-")); + const dir = makeScratchDir("retired-attrs-"); try { const res = await runGen({ config: defineConfig({ @@ -62,7 +61,7 @@ async function warningsFrom(root: MetaRoot, generators = [entityFile()]): Promis }); return res.warnings; } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } @@ -179,7 +178,7 @@ describe("retired @emit* codegen attributes — the `meta gen` warning", () => { // The behaviour half. `@emitRoutes: false` used to suppress this file; it must not // now, and the run must not turn red for saying so. const root = await loadRoot(entity("Subscriber", { "@emitRoutes": false })); - const dir = mkdtempSync(join(tmpdir(), "retired-attrs-emit-")); + const dir = makeScratchDir("retired-attrs-emit-"); try { const res = await runGen({ config: defineConfig({ @@ -192,7 +191,7 @@ describe("retired @emit* codegen attributes — the `meta gen` warning", () => { expect(res.conflicts).toEqual([]); expect(res.warnings.some((w) => w.includes("@emitRoutes"))).toBe(true); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); diff --git a/server/typescript/packages/codegen-ts/test/routes-known-fields.test.ts b/server/typescript/packages/codegen-ts/test/routes-known-fields.test.ts index 284124ea7a..ba33e07615 100644 --- a/server/typescript/packages/codegen-ts/test/routes-known-fields.test.ts +++ b/server/typescript/packages/codegen-ts/test/routes-known-fields.test.ts @@ -8,8 +8,7 @@ import { describe, test, expect } from "bun:test"; import { MetaDataLoader, InMemoryStringSource, type MetaRoot, type MetaObject } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; -import { mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, readdirSync, statSync } from "node:fs"; import { join, resolve } from "node:path"; import { runGen } from "../src/runner.js"; import { defineConfig } from "../src/metaobjects-config.js"; @@ -19,6 +18,7 @@ import { routesFileHono } from "../src/generators/routes-file-hono.js"; import { routesFile as referenceRoutes } from "../src/reference/routes.js"; import { routesFileHono as referenceRoutesHono } from "../src/reference/routes-hono.js"; import { knownFieldNames, tphHierarchy } from "../src/api-surface.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const MODEL = { "metadata.root": { @@ -58,14 +58,14 @@ function allFiles(dir: string): string[] { async function routesSource(generator: Generator, mode: "reject" | "drop" | undefined): Promise { const root = await loadRoot(); if (mode !== undefined) root.apiUnknownFields = mode; - const tmp = mkdtempSync(join(tmpdir(), "routes-known-fields-")); + const tmp = makeScratchDir("routes-known-fields-"); try { await runGen({ config: defineConfig({ outDir: join(tmp, "src"), extStyle: "none", dbImport: "../db", dialect: "sqlite", generators: [generator] }), metadata: root, projectRoot: tmp, }); return allFiles(join(tmp, "src")).filter((f) => /Product.*routes/i.test(f)).map((f) => readFileSync(f, "utf8")).join("\n"); - } finally { rmSync(tmp, { recursive: true, force: true }); } + } finally { removeTree(tmp); } } const GENERATORS: Array<[string, () => Generator]> = [ diff --git a/server/typescript/packages/codegen-ts/test/routes-pagination.test.ts b/server/typescript/packages/codegen-ts/test/routes-pagination.test.ts index 3799e19ff5..4e48128043 100644 --- a/server/typescript/packages/codegen-ts/test/routes-pagination.test.ts +++ b/server/typescript/packages/codegen-ts/test/routes-pagination.test.ts @@ -5,8 +5,7 @@ import { describe, test, expect } from "bun:test"; import { MetaDataLoader, InMemoryStringSource, type MetaRoot } from "@metaobjectsdev/metadata"; -import { mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, readdirSync, statSync } from "node:fs"; import { join } from "node:path"; import { runGen } from "../src/runner.js"; import { defineConfig } from "../src/metaobjects-config.js"; @@ -16,6 +15,7 @@ import { routesFileHono } from "../src/generators/routes-file-hono.js"; import { routesFile as referenceRoutes } from "../src/reference/routes.js"; import { routesFileHono as referenceRoutesHono } from "../src/reference/routes-hono.js"; import { paginationLine } from "../src/api-surface.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const MODEL = { "metadata.root": { @@ -54,14 +54,14 @@ function allFiles(dir: string): string[] { async function routesSource(generator: Generator, page: { defaultLimit: number; maxLimit: number } | undefined): Promise { const root = await loadRoot(); if (page !== undefined) root.apiPagination = page; - const tmp = mkdtempSync(join(tmpdir(), "routes-pagination-")); + const tmp = makeScratchDir("routes-pagination-"); try { await runGen({ config: defineConfig({ outDir: join(tmp, "src"), extStyle: "none", dbImport: "../db", dialect: "sqlite", generators: [generator] }), metadata: root, projectRoot: tmp, }); return allFiles(join(tmp, "src")).filter((f) => /Product.*routes/i.test(f)).map((f) => readFileSync(f, "utf8")).join("\n"); - } finally { rmSync(tmp, { recursive: true, force: true }); } + } finally { removeTree(tmp); } } const GENERATORS: Array<[string, () => Generator]> = [ diff --git a/server/typescript/packages/codegen-ts/test/run-output.test.ts b/server/typescript/packages/codegen-ts/test/run-output.test.ts index b76b1b610e..ca1cd98427 100644 --- a/server/typescript/packages/codegen-ts/test/run-output.test.ts +++ b/server/typescript/packages/codegen-ts/test/run-output.test.ts @@ -2,21 +2,21 @@ // model explorer) runs after every other generator and reads the files through `ctx.runOutput`, // keyed as the manifest keys them. `requirementLedger` is the caller's callback, called once. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, unlinkSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { unlinkSync } from "node:fs"; import { join, resolve } from "node:path"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; import { runGen } from "../src/runner.js"; import { defineConfig } from "../src/metaobjects-config.js"; import { perEntity, type Generator, type RunOutputFile } from "../src/generator.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const FIXTURE = resolve(import.meta.dir, "fixtures", "single-entity.json"); const TWO = resolve(import.meta.dir, "fixtures", "two-entities-fk.json"); let tmp: string; -beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "codegen-run-output-")); }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +beforeEach(() => { tmp = makeScratchDir("codegen-run-output-"); }); +afterEach(() => { removeTree(tmp); }); async function load(file = FIXTURE) { return (await new MetaDataLoader().load([new FileSource(file)])).root; diff --git a/server/typescript/packages/codegen-ts/test/run-wide-orphan-sweep.test.ts b/server/typescript/packages/codegen-ts/test/run-wide-orphan-sweep.test.ts index d7fd26cf8c..2fcacc469a 100644 --- a/server/typescript/packages/codegen-ts/test/run-wide-orphan-sweep.test.ts +++ b/server/typescript/packages/codegen-ts/test/run-wide-orphan-sweep.test.ts @@ -8,13 +8,13 @@ import { manifestFiles } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource, type MetaRoot } from "@metaobjectsdev/metadata"; import { runGen } from "../src/runner.js"; import { entityFile } from "../src/generators/entity-file.js"; import type { Generator } from "../src/generator.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const OUT = "gen"; const GEN_STATE = join(".metaobjects", ".gen-state"); @@ -35,10 +35,10 @@ async function model(...names: string[]): Promise { let projectRoot: string; beforeEach(() => { - projectRoot = mkdtempSync(join(tmpdir(), "run-wide-orphans-")); + projectRoot = makeScratchDir("run-wide-orphans-"); }); afterEach(() => { - rmSync(projectRoot, { recursive: true, force: true }); + removeTree(projectRoot); }); const abs = (rel: string): string => join(projectRoot, rel); diff --git a/server/typescript/packages/codegen-ts/test/runner-docs-generators.test.ts b/server/typescript/packages/codegen-ts/test/runner-docs-generators.test.ts index 9b22d9e78c..714cecce93 100644 --- a/server/typescript/packages/codegen-ts/test/runner-docs-generators.test.ts +++ b/server/typescript/packages/codegen-ts/test/runner-docs-generators.test.ts @@ -3,8 +3,7 @@ // a run that lists one with no `docs` target is refused by name; and the model and api pages // in one target link to each other from facts the runner reads off the declared list. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, readFileSync, readdirSync } from "node:fs"; import { join, relative, resolve } from "node:path"; import { runGen } from "../src/runner.js"; import { DEFAULT_DOCS_DIR, defineConfig, resolveGenerators } from "../src/metaobjects-config.js"; @@ -13,16 +12,17 @@ import { agentDocsFile, apiDocsFile, docsFile, metamodelDocsFile, requirementsFi import type { AgentSchemaInput } from "../src/generators/agent-schema-input.js"; import { MetaDataLoader, type MetaRoot } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const FIXTURE = resolve(import.meta.dir, "fixtures", "single-entity.json"); let tmp: string; let root: MetaRoot; beforeEach(async () => { - tmp = mkdtempSync(join(tmpdir(), "codegen-docs-gen-")); + tmp = makeScratchDir("codegen-docs-gen-"); root = (await new MetaDataLoader().load([new FileSource(FIXTURE)])).root; }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +afterEach(() => { removeTree(tmp); }); function filesUnder(dir: string): string[] { if (!existsSync(dir)) return []; @@ -71,7 +71,7 @@ describe("documentation generators under meta gen (ADR-0034 Amendment 9)", () => test("with only one of the two listed, neither links to pages nothing writes", async () => { await runGen({ config: base([docsFile()]), metadata: root, projectRoot: tmp }); expect(readFileSync(join(tmp, "docs", "demo", "Post.md"), "utf8")).not.toContain("api/demo/Post.md"); - rmSync(join(tmp, "docs"), { recursive: true, force: true }); + removeTree(join(tmp, "docs")); await runGen({ config: base([apiDocsFile()]), metadata: root, projectRoot: tmp }); expect(readFileSync(join(tmp, "docs", "api", "demo", "Post.md"), "utf8")).not.toContain("../../demo/Post.md"); }); diff --git a/server/typescript/packages/codegen-ts/test/runner.test.ts b/server/typescript/packages/codegen-ts/test/runner.test.ts index 3d52045886..3e20de7ed8 100644 --- a/server/typescript/packages/codegen-ts/test/runner.test.ts +++ b/server/typescript/packages/codegen-ts/test/runner.test.ts @@ -1,6 +1,5 @@ import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, readdirSync, readFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readdirSync, readFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { runGen } from "../src/runner.js"; import { defineConfig } from "../src/metaobjects-config.js"; @@ -9,12 +8,13 @@ import { entityModuleSpecifier } from "../src/import-path.js"; import { CodegenError } from "../src/errors.js"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const FIXTURE = resolve(import.meta.dir, "fixtures", "single-entity.json"); let tmp: string; -beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "codegen-runner-")); }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +beforeEach(() => { tmp = makeScratchDir("codegen-runner-"); }); +afterEach(() => { removeTree(tmp); }); describe("runGen — happy path", () => { test("runs each generator in order and writes their files", async () => { diff --git a/server/typescript/packages/codegen-ts/test/runtime-drift.test.ts b/server/typescript/packages/codegen-ts/test/runtime-drift.test.ts index 6efb719e37..e37c36de3d 100644 --- a/server/typescript/packages/codegen-ts/test/runtime-drift.test.ts +++ b/server/typescript/packages/codegen-ts/test/runtime-drift.test.ts @@ -7,17 +7,18 @@ // holds the drifted text; the clean text the helpers are generated from is the parent corpus's // `templates/`. import { describe, test, expect, afterAll } from "bun:test"; -import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from "node:fs"; +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { FileSystemProvider } from "../src/render-engine/framework-provider.js"; import { renderRenderHelper } from "../src/templates/render-helper.js"; import { promptRender } from "../src/generators/prompt-render-file.js"; +import { removeTree } from "../src/scratch-dir.js"; const CORPUS = resolve(import.meta.dir, "../../../../../fixtures/template-output-render-conformance"); const TEMP_DIRS: string[] = []; afterAll(() => { - for (const d of TEMP_DIRS) rmSync(d, { recursive: true, force: true }); + for (const d of TEMP_DIRS) removeTree(d); }); async function load() { diff --git a/server/typescript/packages/codegen-ts/test/secondary-index-name-parity.test.ts b/server/typescript/packages/codegen-ts/test/secondary-index-name-parity.test.ts index e17bcca6a1..6db0658a76 100644 --- a/server/typescript/packages/codegen-ts/test/secondary-index-name-parity.test.ts +++ b/server/typescript/packages/codegen-ts/test/secondary-index-name-parity.test.ts @@ -28,8 +28,7 @@ // column that agrees with the strategy, both spellings coincide and this test would pass // against the defect. import { describe, test, expect } from "bun:test"; -import { mkdtempSync, rmSync, writeFileSync, mkdirSync, readdirSync, readFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { writeFileSync, mkdirSync, readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { MetaDataLoader, resolveColumnName } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; @@ -37,6 +36,7 @@ import { buildExpectedSchema } from "@metaobjectsdev/migrate-ts"; import { runGen } from "../src/runner.js"; import { entityFile } from "../src/generators/entity-file.js"; import { defineConfig } from "../src/metaobjects-config.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; const META = JSON.stringify({ "metadata.root": { @@ -74,7 +74,7 @@ const META = JSON.stringify({ * other — which is the only way the two sides are talking about the same thing. */ async function bothNames(): Promise<{ codegen: string[]; migrate: string[] }> { - const repo = mkdtempSync(join(tmpdir(), "idx-parity-")); + const repo = makeScratchDir("idx-parity-"); try { mkdirSync(join(repo, "metaobjects"), { recursive: true }); const fixture = join(repo, "metaobjects", "meta.idx.json"); @@ -128,7 +128,7 @@ async function bothNames(): Promise<{ codegen: string[]; migrate: string[] }> { return { codegen, migrate }; } finally { - rmSync(repo, { recursive: true, force: true }); + removeTree(repo); } } diff --git a/server/typescript/packages/codegen-ts/test/shared-model-file.test.ts b/server/typescript/packages/codegen-ts/test/shared-model-file.test.ts index 1dd4a24477..0031dd31d1 100644 --- a/server/typescript/packages/codegen-ts/test/shared-model-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/shared-model-file.test.ts @@ -10,8 +10,7 @@ // see the report for why these use Secret rather than Customer (the pinned // artifact's actual Customer/Address pair carries no ref between them at all). import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync, existsSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdirSync, writeFileSync, readFileSync, existsSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { runGen } from "../src/runner.js"; import { defineConfig } from "../src/metaobjects-config.js"; @@ -22,6 +21,7 @@ import { type MetaDataTypeProvider, } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; function findRepoRoot(start: string): string { let dir = start; @@ -132,7 +132,7 @@ let fileA: string; let fileB: string; beforeEach(() => { - tmp = mkdtempSync(join(tmpdir(), "shared-model-file-")); + tmp = makeScratchDir("shared-model-file-"); mkdirSync(join(tmp, "metaobjects"), { recursive: true }); fileA = join(tmp, "metaobjects", "meta.common-base.json"); fileB = join(tmp, "metaobjects", "meta.common-customer.json"); @@ -141,7 +141,7 @@ beforeEach(() => { }); afterEach(() => { - rmSync(tmp, { recursive: true, force: true }); + removeTree(tmp); }); /** Loads the outer `opts.metadata` MetaRoot `runGen` requires (non-strict — the diff --git a/server/typescript/packages/codegen-ts/test/sourceless-entity-surface.test.ts b/server/typescript/packages/codegen-ts/test/sourceless-entity-surface.test.ts index 008439e3d5..f30c03e459 100644 --- a/server/typescript/packages/codegen-ts/test/sourceless-entity-surface.test.ts +++ b/server/typescript/packages/codegen-ts/test/sourceless-entity-surface.test.ts @@ -20,7 +20,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; @@ -30,6 +30,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import { isSourcelessEntity } from "../src/index.js"; import type { GenContext } from "../src/generator.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -172,7 +173,7 @@ describe("sourceless entity (identity, no source): the wire contract without a t expect(order).not.toContain("pgTable("); expect(order).not.toContain("$table"); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); @@ -184,7 +185,7 @@ describe("sourceless entity (identity, no source): the wire contract without a t expect(item).not.toContain("UpdateSchema"); expect(item).not.toContain("FilterAllowlist"); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); @@ -196,7 +197,7 @@ describe("sourceless entity (identity, no source): the wire contract without a t writeFileSync(join(dir, "order-repository.ts"), REPOSITORY); expect(compile(dir, [...files.keys(), "order-repository.ts"])).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); }); diff --git a/server/typescript/packages/codegen-ts/test/sourceless-objects.test.ts b/server/typescript/packages/codegen-ts/test/sourceless-objects.test.ts index 8476fa1ea1..383985c5c1 100644 --- a/server/typescript/packages/codegen-ts/test/sourceless-objects.test.ts +++ b/server/typescript/packages/codegen-ts/test/sourceless-objects.test.ts @@ -14,8 +14,7 @@ // zero-source object of ANY subtype gets neither. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync, readdirSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, readdirSync } from "node:fs"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { runGen, defineConfig } from "../src/index.js"; @@ -25,13 +24,14 @@ import { queriesFile } from "../src/generators/queries-file.js"; import { routesFile } from "../src/generators/routes-file.js"; import { queriesFile as refQueriesFile } from "../src/reference/queries.js"; import { routesFile as refRoutesFile } from "../src/reference/routes.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; let tmp: string; beforeEach(() => { - tmp = mkdtempSync(join(tmpdir(), "codegen-sourceless-")); + tmp = makeScratchDir("codegen-sourceless-"); }); afterEach(() => { - rmSync(tmp, { recursive: true, force: true }); + removeTree(tmp); }); async function loadRoot(children: unknown[]) { @@ -187,7 +187,7 @@ describe("#248 R2 — sourceless objects get no DB-bound artifacts", () => { const mixedOut = tmp; await runGen({ config: genConfig(mixedOut), metadata: mixedRoot }); - const soloDir = mkdtempSync(join(tmpdir(), "codegen-sourceless-solo-")); + const soloDir = makeScratchDir("codegen-sourceless-solo-"); try { const soloRoot = await loadRoot([ORDER]); await runGen({ config: genConfig(soloDir), metadata: soloRoot }); @@ -198,7 +198,7 @@ describe("#248 R2 — sourceless objects get no DB-bound artifacts", () => { expect(mixed).toBe(solo); } } finally { - rmSync(soloDir, { recursive: true, force: true }); + removeTree(soloDir); } }); diff --git a/server/typescript/packages/codegen-ts/test/support/manifest.ts b/server/typescript/packages/codegen-ts/test/support/manifest.ts index a6c0f50c8d..798fe13226 100644 --- a/server/typescript/packages/codegen-ts/test/support/manifest.ts +++ b/server/typescript/packages/codegen-ts/test/support/manifest.ts @@ -8,6 +8,7 @@ import { manifestExists, readManifestState, } from "../../src/hash-manifest-store.js"; +import { removeTree } from "../../src/scratch-dir.js"; export { HASHES_DIR, LEGACY_HASHES_FILE, manifestExists }; @@ -36,7 +37,7 @@ export function manifestMtimes(genStateDir: string): Record { /** Remove the whole manifest (per-package dir and legacy file). */ export function removeManifest(genStateDir: string): void { - rmSync(join(genStateDir, HASHES_DIR), { recursive: true, force: true }); + removeTree(join(genStateDir, HASHES_DIR)); rmSync(join(genStateDir, LEGACY_HASHES_FILE), { force: true }); } diff --git a/server/typescript/packages/codegen-ts/test/template-codegen/conformance.test.ts b/server/typescript/packages/codegen-ts/test/template-codegen/conformance.test.ts index b720803cac..41d5ed0b68 100644 --- a/server/typescript/packages/codegen-ts/test/template-codegen/conformance.test.ts +++ b/server/typescript/packages/codegen-ts/test/template-codegen/conformance.test.ts @@ -1,10 +1,10 @@ import { describe, test, expect } from "bun:test"; -import { mkdtempSync, rmSync, readdirSync, readFileSync, statSync, cpSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readdirSync, readFileSync, statSync, cpSync } from "node:fs"; import { join, resolve, relative } from "node:path"; import { runGen, defineConfig, parseTemplateSpec, templateSpecToGenerators } from "../../src/index.js"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; const CORPUS = resolve(import.meta.dir, "../../../../../../fixtures/template-codegen-conformance"); @@ -24,7 +24,7 @@ describe("template-codegen conformance (TS)", () => { // Hermetic: copy the corpus templates into a tmp projectRoot so runGen writes // its .gen-state merge base into the tmp tree, never into the committed corpus. - const projectRoot = mkdtempSync(join(tmpdir(), "tmpl-conf-")); + const projectRoot = makeScratchDir("tmpl-conf-"); const out = join(projectRoot, "out"); cpSync(join(CORPUS, "templates"), join(projectRoot, "templates"), { recursive: true }); try { @@ -45,7 +45,7 @@ describe("template-codegen conformance (TS)", () => { .toBe(`${rel}:\n${readFileSync(join(expectedDir, rel), "utf8")}`); } } finally { - rmSync(projectRoot, { recursive: true, force: true }); + removeTree(projectRoot); } }); }); diff --git a/server/typescript/packages/codegen-ts/test/template-codegen/scope-walk.test.ts b/server/typescript/packages/codegen-ts/test/template-codegen/scope-walk.test.ts index 5204bd5e5e..475ee35562 100644 --- a/server/typescript/packages/codegen-ts/test/template-codegen/scope-walk.test.ts +++ b/server/typescript/packages/codegen-ts/test/template-codegen/scope-walk.test.ts @@ -1,15 +1,15 @@ import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, writeFileSync, mkdirSync, readdirSync, readFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { writeFileSync, mkdirSync, readdirSync, readFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { runGen, defineConfig } from "../../src/index.js"; import { templateGenerator } from "../../src/generators/template-generator.js"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; let tmp: string; -beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "tmpl-scope-")); }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +beforeEach(() => { tmp = makeScratchDir("tmpl-scope-"); }); +afterEach(() => { removeTree(tmp); }); async function genPerEntity(outDir: string, projectRoot: string) { const loader = new MetaDataLoader(); diff --git a/server/typescript/packages/codegen-ts/test/templates/enum-shared-provided.test.ts b/server/typescript/packages/codegen-ts/test/templates/enum-shared-provided.test.ts index 33b78a4913..e164ae13e7 100644 --- a/server/typescript/packages/codegen-ts/test/templates/enum-shared-provided.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/enum-shared-provided.test.ts @@ -10,14 +10,14 @@ // • inline: a plain union is unchanged (no enums.ts, no import). import { describe, test, expect } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync, existsSync, readdirSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, existsSync, readdirSync } from "node:fs"; import { join } from "node:path"; import { runGen, defineConfig } from "../../src/index.js"; import { barrel } from "../../src/generators/barrel.js"; import { entityFile } from "../../src/generators/entity-file.js"; import { queriesFile } from "../../src/generators/queries-file.js"; import { MetaDataLoader, InMemoryStringSource, type MetaRoot } from "@metaobjectsdev/metadata"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; async function loadRoot(doc: unknown): Promise { const result = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); @@ -31,7 +31,7 @@ interface RunOut { } async function gen(root: MetaRoot, providedEnumModule?: string): Promise { - const tmp = mkdtempSync(join(tmpdir(), "enum-fr019-")); + const tmp = makeScratchDir("enum-fr019-"); try { const result = await runGen({ config: defineConfig({ @@ -50,7 +50,7 @@ async function gen(root: MetaRoot, providedEnumModule?: string): Promise } return { files, warnings: result.warnings }; } finally { - rmSync(tmp, { recursive: true, force: true }); + removeTree(tmp); } } @@ -128,7 +128,7 @@ describe("#266 shared enums across multiple entityFile() instances", () => { // collision — making a root-level abstract field.enum unusable in any such config. test("two filtered entityFile() instances in one target emit the shared enums module once", async () => { const root = await loadRoot(sharedModel()); - const tmp = mkdtempSync(join(tmpdir(), "enum-266-")); + const tmp = makeScratchDir("enum-266-"); try { const result = await runGen({ config: defineConfig({ @@ -159,7 +159,7 @@ describe("#266 shared enums across multiple entityFile() instances", () => { expect(readFileSync(join(tmp, name), "utf-8")).toContain('from "./enums"'); } } finally { - rmSync(tmp, { recursive: true, force: true }); + removeTree(tmp); } }); }); diff --git a/server/typescript/packages/codegen-ts/test/templates/m2m-cross-package-names.test.ts b/server/typescript/packages/codegen-ts/test/templates/m2m-cross-package-names.test.ts index 6ec17ee16d..76c4c63528 100644 --- a/server/typescript/packages/codegen-ts/test/templates/m2m-cross-package-names.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/m2m-cross-package-names.test.ts @@ -18,14 +18,14 @@ // import specifier resolves to. import { describe, test, expect } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync, existsSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, existsSync } from "node:fs"; import { join, dirname, resolve as resolvePath } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { runGen, defineConfig } from "../../src/index.js"; import { namesFile } from "../../src/generators/index.js"; import { entityFile } from "../../src/generators/entity-file.js"; import { routesFile } from "../../src/generators/routes-file.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; // Article (shop::blog) <—many:many—> Label (shop::tags), through ArticleLabel // (shop::tags) — junction AND target both in a DIFFERENT package from the source, so @@ -72,7 +72,7 @@ async function loadRoot() { describe("renderRoutesFile — cross-package M:N names imports resolve to the right directory (B1)", () => { test("Article.routes.ts's Names / Names imports point at files that actually exist on disk", async () => { const root = await loadRoot(); - const tmp = mkdtempSync(join(tmpdir(), "codegen-m2m-xpkg-")); + const tmp = makeScratchDir("codegen-m2m-xpkg-"); try { const result = await runGen({ config: defineConfig({ @@ -116,7 +116,7 @@ describe("renderRoutesFile — cross-package M:N names imports resolve to the ri expect(content).not.toContain('from "./ArticleLabel.names.js"'); expect(content).not.toContain('from "./Label.names.js"'); } finally { - rmSync(tmp, { recursive: true, force: true }); + removeTree(tmp); } }); }); diff --git a/server/typescript/packages/codegen-ts/test/templates/names-consumption.test.ts b/server/typescript/packages/codegen-ts/test/templates/names-consumption.test.ts index d8a0055456..d7dd910584 100644 --- a/server/typescript/packages/codegen-ts/test/templates/names-consumption.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/names-consumption.test.ts @@ -12,8 +12,7 @@ // ResolvedGenConfig.includeNames + RenderContext.includeNames → the template. import { describe, test, expect, beforeEach, afterEach, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "../compile-timeout.js"; -import { existsSync, mkdtempSync, rmSync, readFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, mkdtempSync, readFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; @@ -23,6 +22,7 @@ import { namesFile } from "../../src/generators/index.js"; import { entityFile } from "../../src/generators/entity-file.js"; import { queriesFile } from "../../src/generators/queries-file.js"; import type { ExtStyle } from "../../src/render-context.js"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -36,8 +36,8 @@ if (loadResult.errors.length > 0) { const metadataRoot = loadResult.root; let tmp: string; -beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "codegen-names-consume-")); }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +beforeEach(() => { tmp = makeScratchDir("codegen-names-consume-"); }); +afterEach(() => { removeTree(tmp); }); /** Generate `Subscriber.ts` with the names generator either wired in or absent. */ async function renderEntityWithGenerators(active: boolean, extStyle: ExtStyle = "js"): Promise { @@ -172,7 +172,7 @@ describe("§A6 — the entity file consumes the names artifact", () => { .map((d) => ts.flattenDiagnosticMessageText(d.messageText, "\n")); expect(diagnostics).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); diff --git a/server/typescript/packages/codegen-ts/test/templates/value-object-cross-package.test.ts b/server/typescript/packages/codegen-ts/test/templates/value-object-cross-package.test.ts index 9ae7cd1870..6022beb26e 100644 --- a/server/typescript/packages/codegen-ts/test/templates/value-object-cross-package.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/value-object-cross-package.test.ts @@ -8,13 +8,13 @@ // so every reference must be `../common/Triple` under package layout. import { describe, it, expect } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { runGen, defineConfig } from "../../src/index.js"; import { entityFile } from "../../src/generators/entity-file.js"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; +import { makeScratchDir, removeTree } from "../../src/scratch-dir.js"; const FIXTURE = resolve(import.meta.dir, "../fixtures/cross-package-vo.json"); @@ -26,7 +26,7 @@ if (loadResult.errors.length > 0) { const metadataRoot = loadResult.root; async function genFile(dialect: "postgres" | "sqlite", outputLayout: "flat" | "package"): Promise { - const tmp = mkdtempSync(join(tmpdir(), "codegen-vo-xpkg-")); + const tmp = makeScratchDir("codegen-vo-xpkg-"); try { const result = await runGen({ config: defineConfig({ @@ -43,7 +43,7 @@ async function genFile(dialect: "postgres" | "sqlite", outputLayout: "flat" | "p const rel = outputLayout === "package" ? "acme/ai/SemanticTrace.ts" : "SemanticTrace.ts"; return readFileSync(join(tmp, rel), "utf-8"); } finally { - rmSync(tmp, { recursive: true, force: true }); + removeTree(tmp); } } diff --git a/server/typescript/packages/codegen-ts/test/timestamp-instant-filter-e2e.test.ts b/server/typescript/packages/codegen-ts/test/timestamp-instant-filter-e2e.test.ts index 2928a2e586..d0b2da35a6 100644 --- a/server/typescript/packages/codegen-ts/test/timestamp-instant-filter-e2e.test.ts +++ b/server/typescript/packages/codegen-ts/test/timestamp-instant-filter-e2e.test.ts @@ -13,7 +13,7 @@ // rendered from metadata, mounted with runtime-ts's Hono helper over bun:sqlite. import { describe, test, expect, beforeAll, afterAll } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { Database } from "bun:sqlite"; @@ -24,6 +24,7 @@ import { MetaDataLoader, InMemoryStringSource, type MetaObject } from "@metaobje import { mountCrudRoutes } from "@metaobjectsdev/runtime-ts/hono"; import { renderZodValidators } from "../src/templates/zod-validators.js"; import { renderFilterAllowlist } from "../src/templates/filter-allowlist.js"; +import { removeTree } from "../src/scratch-dir.js"; const MODEL = { "metadata.root": { package: "rentals", children: [ @@ -46,7 +47,7 @@ const rentals = sqliteTable("rentals", { }); const dir = mkdtempSync(join(import.meta.dir, "tmp-ts-instant-")); -afterAll(() => rmSync(dir, { recursive: true, force: true })); +afterAll(() => removeTree(dir)); async function execute(name: string, source: string): Promise> { const file = join(dir, `${name}.ts`); diff --git a/server/typescript/packages/codegen-ts/test/timestamp-mode-execution.test.ts b/server/typescript/packages/codegen-ts/test/timestamp-mode-execution.test.ts index 6b04ec667c..07dc382f7c 100644 --- a/server/typescript/packages/codegen-ts/test/timestamp-mode-execution.test.ts +++ b/server/typescript/packages/codegen-ts/test/timestamp-mode-execution.test.ts @@ -31,8 +31,7 @@ // repo precedent: #226/#258 detect-and-refuse at gen time). import { describe, test, expect, afterEach } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { @@ -49,6 +48,7 @@ import { normalizeConfig, defineConfig } from "../src/metaobjects-config.js"; import { runGen } from "../src/runner.js"; import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; // biome-ignore lint/suspicious/noExplicitAny: dynamically imported generated module — no static shape type GeneratedModule = Record; @@ -56,7 +56,7 @@ type GeneratedModule = Record; const tmpDirs: string[] = []; afterEach(() => { while (tmpDirs.length > 0) { - rmSync(tmpDirs.pop()!, { recursive: true, force: true }); + removeTree(tmpDirs.pop()!); } }); @@ -257,7 +257,7 @@ describe('IMPORTANT 4: runGen warns (once) when timestampMode: "date" meets a @f async function runWithMetadata(json: string, dialect: "postgres" | "sqlite", timestampMode?: "date" | "string") { const result = await new MetaDataLoader().load([new InMemoryStringSource(json)]); expect(result.errors).toEqual([]); - const dir = mkdtempSync(join(tmpdir(), "codegen-runner-important4-")); + const dir = makeScratchDir("codegen-runner-important4-"); try { return await runGen({ config: defineConfig({ @@ -268,7 +268,7 @@ describe('IMPORTANT 4: runGen warns (once) when timestampMode: "date" meets a @f metadata: result.root, }); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } diff --git a/server/typescript/packages/codegen-ts/test/tph-cross-field.test.ts b/server/typescript/packages/codegen-ts/test/tph-cross-field.test.ts index c04a8a8146..9152c61645 100644 --- a/server/typescript/packages/codegen-ts/test/tph-cross-field.test.ts +++ b/server/typescript/packages/codegen-ts/test/tph-cross-field.test.ts @@ -12,7 +12,7 @@ // on the discriminator reads the subtype's pinned value, so it holds on a body that omits it. import { describe, test, expect, afterEach, setDefaultTimeout } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from "node:fs"; +import { mkdtempSync, writeFileSync, mkdirSync } from "node:fs"; import { join, dirname } from "node:path"; import { pathToFileURL } from "node:url"; import ts from "typescript"; @@ -26,6 +26,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { EmittedFile, GenContext } from "../src/generator.js"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -54,7 +55,7 @@ const MODEL = { const tmpDirs: string[] = []; afterEach(() => { - while (tmpDirs.length > 0) rmSync(tmpDirs.pop()!, { recursive: true, force: true }); + while (tmpDirs.length > 0) removeTree(tmpDirs.pop()!); }); function tmpDir(prefix: string): string { diff --git a/server/typescript/packages/codegen-ts/test/tph-read-schema-default.test.ts b/server/typescript/packages/codegen-ts/test/tph-read-schema-default.test.ts index 02792d1153..3dad7f5219 100644 --- a/server/typescript/packages/codegen-ts/test/tph-read-schema-default.test.ts +++ b/server/typescript/packages/codegen-ts/test/tph-read-schema-default.test.ts @@ -17,7 +17,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from "node:fs"; +import { mkdtempSync, writeFileSync, mkdirSync } from "node:fs"; import { join, dirname } from "node:path"; import { pathToFileURL } from "node:url"; import ts from "typescript"; @@ -32,6 +32,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { EmittedFile, GenContext } from "../src/generator.js"; import type { Dialect } from "../src/metaobjects-config.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -149,7 +150,7 @@ for (const dialect of ["postgres", "sqlite"] as const) { } expect(compile(dir, files.map((f) => f.path))).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); @@ -248,7 +249,7 @@ for (const dialect of ["postgres", "sqlite"] as const) { } expect(compile(dir, files.map((f) => f.path))).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); @@ -290,7 +291,7 @@ for (const dialect of ["postgres", "sqlite"] as const) { expect(parsed.success).toBe(true); expect(parsed.success && parsed.data.customerName).toBeUndefined(); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); }); diff --git a/server/typescript/packages/codegen-ts/test/tph-reference-target.test.ts b/server/typescript/packages/codegen-ts/test/tph-reference-target.test.ts index 8288f148cb..62487104e3 100644 --- a/server/typescript/packages/codegen-ts/test/tph-reference-target.test.ts +++ b/server/typescript/packages/codegen-ts/test/tph-reference-target.test.ts @@ -18,7 +18,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from "node:fs"; +import { mkdtempSync, writeFileSync, mkdirSync } from "node:fs"; import { join, dirname } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource, type MetaObject, type MetaRoot } from "@metaobjectsdev/metadata"; @@ -32,6 +32,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { EmittedFile, GenContext } from "../src/generator.js"; import type { Dialect } from "../src/metaobjects-config.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -173,7 +174,7 @@ for (const dialect of ["postgres", "sqlite"] as const) { } expect(compile(dir, files.map((f) => f.path))).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); diff --git a/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts b/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts index 8f28dd8117..a638328b9b 100644 --- a/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts @@ -12,7 +12,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource, type MetaObject, type MetaRoot } from "@metaobjectsdev/metadata"; @@ -23,6 +23,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { EmittedFile, GenContext } from "../src/generator.js"; import type { Dialect } from "../src/metaobjects-config.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -124,7 +125,7 @@ async function compileCaller(dialect: Dialect, body: string): Promise<{ all: str const all = compile(dir, [...files.map((f) => f.path), "caller.ts"]); return { all, caller: all.filter((d) => d.startsWith("caller.ts:")) }; } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } @@ -148,7 +149,7 @@ for (const dialect of ["postgres", "sqlite"] as const) { expect(queries).not.toContain("data: unknown"); expect(party).not.toContain("data: unknown"); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); diff --git a/server/typescript/packages/codegen-ts/test/verbatim-module-syntax-compile.test.ts b/server/typescript/packages/codegen-ts/test/verbatim-module-syntax-compile.test.ts index 490227b179..3f04bc6f84 100644 --- a/server/typescript/packages/codegen-ts/test/verbatim-module-syntax-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/verbatim-module-syntax-compile.test.ts @@ -16,7 +16,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; @@ -26,6 +26,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { GenContext } from "../src/generator.js"; import type { Dialect } from "../src/metaobjects-config.js"; +import { removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -146,7 +147,7 @@ async function genAndCompile(dialect: Dialect): Promise f.path)); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } diff --git a/server/typescript/packages/codegen-ts/test/wire-format-e2e.test.ts b/server/typescript/packages/codegen-ts/test/wire-format-e2e.test.ts index ef82032db6..41233aa54b 100644 --- a/server/typescript/packages/codegen-ts/test/wire-format-e2e.test.ts +++ b/server/typescript/packages/codegen-ts/test/wire-format-e2e.test.ts @@ -6,7 +6,7 @@ // back; `weight` is a NUMERIC column so a row holds the number SQLite or D1 would. import { describe, test, expect, beforeAll, afterAll } from "bun:test"; -import { mkdirSync, mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { pathToFileURL } from "node:url"; import { Database } from "bun:sqlite"; @@ -18,6 +18,7 @@ import { mountCrudRoutes } from "@metaobjectsdev/runtime-ts/hono"; import { renderZodValidators, renderInsertSchemaOnly } from "../src/templates/zod-validators.js"; import { renderFilterAllowlist } from "../src/templates/filter-allowlist.js"; import { decimalColumnsLine } from "../src/api-surface.js"; +import { removeTree } from "../src/scratch-dir.js"; const MODEL = { "metadata.root": { package: "ledger", children: [ @@ -51,7 +52,7 @@ const entries = sqliteTable("entries", { }); const dir = mkdtempSync(join(import.meta.dir, "tmp-wire-")); -afterAll(() => rmSync(dir, { recursive: true, force: true })); +afterAll(() => removeTree(dir)); async function execute(name: string, source: string): Promise> { const file = join(dir, `${name}.ts`); diff --git a/server/typescript/packages/codegen-ts/test/xpkg-value-object-refs-conformance.test.ts b/server/typescript/packages/codegen-ts/test/xpkg-value-object-refs-conformance.test.ts index d11bc1a892..cc4405410c 100644 --- a/server/typescript/packages/codegen-ts/test/xpkg-value-object-refs-conformance.test.ts +++ b/server/typescript/packages/codegen-ts/test/xpkg-value-object-refs-conformance.test.ts @@ -5,7 +5,7 @@ // binds the pair under package-qualified local aliases, and the whole output type-checks. import { describe, test, expect, afterAll } from "bun:test"; -import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs"; +import { mkdtempSync, readdirSync, readFileSync } from "node:fs"; import { join, relative, resolve } from "node:path"; import ts from "typescript"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; @@ -16,10 +16,11 @@ import { entityFile } from "../src/generators/entity-file.js"; import { routesFile } from "../src/generators/routes-file.js"; import { callableFile } from "../src/generators/callable-file.js"; import { ERR_NAME_COLLISION } from "../src/naming/name-claims.js"; +import { removeTree } from "../src/scratch-dir.js"; const CORPUS = resolve(import.meta.dir, "../../../../../fixtures/codegen-conformance/xpkg-value-object-refs/input"); const TEMP_DIRS: string[] = []; -afterAll(() => { for (const d of TEMP_DIRS) rmSync(d, { recursive: true, force: true }); }); +afterAll(() => { for (const d of TEMP_DIRS) removeTree(d); }); async function load() { const res = await new MetaDataLoader().load( diff --git a/server/typescript/packages/codegen-ts/test/zod-cross-field.test.ts b/server/typescript/packages/codegen-ts/test/zod-cross-field.test.ts index 20227b5d99..9bd8a58b70 100644 --- a/server/typescript/packages/codegen-ts/test/zod-cross-field.test.ts +++ b/server/typescript/packages/codegen-ts/test/zod-cross-field.test.ts @@ -3,7 +3,7 @@ // Execution pins (render -> import -> safeParse), plus the "update schema unchanged" pin. import { describe, test, expect, afterEach } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { @@ -19,13 +19,14 @@ import { import type { AttrValue, MetaField, MetaObject } from "@metaobjectsdev/metadata"; import { meta, metaObject, metaField } from "./_meta-build.js"; import { renderZodValidators, hasInsertRefinements } from "../src/templates/zod-validators.js"; +import { removeTree } from "../src/scratch-dir.js"; // biome-ignore lint/suspicious/noExplicitAny: dynamically imported generated module — no static shape type GeneratedModule = Record; const tmpDirs: string[] = []; afterEach(() => { - while (tmpDirs.length > 0) rmSync(tmpDirs.pop()!, { recursive: true, force: true }); + while (tmpDirs.length > 0) removeTree(tmpDirs.pop()!); }); async function executeGenerated(source: string): Promise { diff --git a/server/typescript/packages/codegen-ts/test/zod-validators-execution.test.ts b/server/typescript/packages/codegen-ts/test/zod-validators-execution.test.ts index 541d300524..1c04990180 100644 --- a/server/typescript/packages/codegen-ts/test/zod-validators-execution.test.ts +++ b/server/typescript/packages/codegen-ts/test/zod-validators-execution.test.ts @@ -30,7 +30,7 @@ // Sibling: `timestamp-mode-execution.test.ts` (same technique, timestampMode). import { describe, test, expect, afterEach } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { @@ -52,6 +52,7 @@ import { renderZodValidators } from "../src/templates/zod-validators.js"; import { makeRenderContext } from "../src/render-context.js"; import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; +import { removeTree } from "../src/scratch-dir.js"; // biome-ignore lint/suspicious/noExplicitAny: dynamically imported generated module — no static shape type GeneratedModule = Record; @@ -59,7 +60,7 @@ type GeneratedModule = Record; const tmpDirs: string[] = []; afterEach(() => { while (tmpDirs.length > 0) { - rmSync(tmpDirs.pop()!, { recursive: true, force: true }); + removeTree(tmpDirs.pop()!); } }); diff --git a/server/typescript/packages/integration-tests/src/api-contract-list-query-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-list-query-generated-server.ts new file mode 100644 index 0000000000..074c6b34e1 --- /dev/null +++ b/server/typescript/packages/integration-tests/src/api-contract-list-query-generated-server.ts @@ -0,0 +1,117 @@ +// api-contract-list-query-generated-server.ts — boots the GENERATED Part routes (the deployed +// artifact) over HTTP for the list-query sub-corpus: search, or/and, the nesting cap, bare +// fields, leading wildcards, value formats and the body/id/constraint refusals. +// +// Same shape as api-contract-api-settings-generated-server.ts: runGen over the corpus meta into +// a temp dir, provision the table the emitted Drizzle binding reads, mount the EMITTED routes. + +import Fastify, { type FastifyInstance } from "fastify"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; +import { entityFile, routesFile } from "@metaobjectsdev/test-generators"; +import type pg from "pg"; +import { executeSql } from "./postgres-sql.ts"; +import { loadMetadataFile } from "./load-metadata.ts"; + +export interface ListQuerySeed { + rows: Array<{ id: number; name: string; sku: string; category: string; stock: number; notes: string }>; +} + +export interface GeneratedListQueryServerHandle { + baseUrl: string; + applySeed(seed: ListQuerySeed): Promise; + close(): Promise; +} + +export async function startGeneratedListQueryServer( + connectionUri: string, + metaPath: string, +): Promise { + const here = dirname(fileURLToPath(import.meta.url)); + const genTmpRoot = join(here, "..", ".gen-tmp"); + mkdirSync(genTmpRoot, { recursive: true }); + const tmp = mkdtempSync(join(genTmpRoot, "api-contract-list-query-")); + + try { + const root = await loadMetadataFile(metaPath); + const lr = await runGen({ + config: defineConfig({ + outDir: tmp, + extStyle: "none", + dbImport: "./db", + dialect: "postgres", + apiPrefix: "/api", + generators: [entityFile(), routesFile()], + }), + metadata: root, + }); + if (lr.warnings.length > 0) { + throw new Error(`codegen produced warnings: ${lr.warnings.join("; ")}`); + } + + const bigintTypesImport = pathToFileURL(join(here, "pg-bigint-number-types.ts")).href; + writeFileSync( + join(tmp, "db.ts"), + ` +import { drizzle } from "drizzle-orm/node-postgres"; +import pg from "pg"; +import { bigintAsNumberTypes } from ${JSON.stringify(bigintTypesImport)}; +export const pool = new pg.Pool({ connectionString: ${JSON.stringify(connectionUri)}, types: bigintAsNumberTypes }); +export const db = drizzle(pool); +`, + "utf8", + ); + + await executeSql( + connectionUri, + `CREATE TABLE IF NOT EXISTS "parts" ( + "id" bigserial PRIMARY KEY, + "name" varchar(100) NOT NULL, + "sku" varchar(20) NOT NULL UNIQUE, + "category" varchar(4) NOT NULL CHECK ("category" IN ('tool', 'part', 'kit')), + "stock" integer NOT NULL, + "notes" varchar(200) + );`, + ); + + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; + + const fastify = Fastify(); + const mod = (await import(pathToFileURL(join(tmp, "Part.routes.ts")).href)) as Record< + string, + (f: FastifyInstance) => Promise + >; + await fastify.register(mod["partRoutes"]!); + await fastify.ready(); + const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + + return { + baseUrl, + applySeed: async (seed: ListQuerySeed) => { + const values = seed.rows + .map((r) => `(${r.id}, ${str(r.name)}, ${str(r.sku)}, ${str(r.category)}, ${r.stock}, ${str(r.notes)})`) + .join(",\n"); + await executeSql( + connectionUri, + `TRUNCATE TABLE "parts" RESTART IDENTITY; + INSERT INTO "parts" ("id","name","sku","category","stock","notes") VALUES ${values}; + SELECT setval(pg_get_serial_sequence('parts','id'), (SELECT MAX("id") FROM "parts"));`, + ); + }, + close: async () => { + await fastify.close(); + await dbMod.pool.end(); + rmSync(tmp, { recursive: true, force: true }); + }, + }; + } catch (err) { + rmSync(tmp, { recursive: true, force: true }); + throw err; + } +} + +function str(v: string): string { + return `'${v.replace(/'/g, "''")}'`; +} diff --git a/server/typescript/packages/integration-tests/src/api-contract-openapi-check.ts b/server/typescript/packages/integration-tests/src/api-contract-openapi-check.ts index b51029e2a2..d5dff54de2 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-openapi-check.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-openapi-check.ts @@ -19,11 +19,13 @@ const DOCUMENT_ID = "openapi"; const JSON_MEDIA_TYPE = "application/json"; /** - * The REST contract's TypeScript-only query extensions (docs/features/api-contract.md, "TS-only - * filter extensions"). The document states the cross-port contract, so it leaves these out, and a + * The list-query parameters the OpenAPI document does not describe yet: `?search` and the + * `filter[or]` / `filter[and]` combinators (docs/features/api-contract.md, "The list query: + * search, combinators and refusals"). They are part of the REST contract since 1.3.0, but the + * generated document still lists only the per-field `filter[][]` parameters, so a * scenario that sends one is outside what this check can hold. */ -const TS_ONLY_QUERY = /^(search|filter\[(or|and)\])/; +const UNDOCUMENTED_QUERY = /^(search|filter\[(or|and)\])/; type JsonObject = Record; @@ -103,7 +105,7 @@ export function openApiCheck(caseName: string): ContractCheck { if (status >= 200 && status < 300) { const declared = new Set([...(item?.parameters ?? []), ...(operation.parameters ?? [])].map((p) => p.name)); for (const name of queryNames(req.path)) { - if (!declared.has(name) && !TS_ONLY_QUERY.test(name)) fail(req, `query parameter '${name}' is not in the document`); + if (!declared.has(name) && !UNDOCUMENTED_QUERY.test(name)) fail(req, `query parameter '${name}' is not in the document`); } const request = operation.requestBody?.content?.[JSON_MEDIA_TYPE]?.schema; if (request !== undefined && req.body !== undefined) { diff --git a/server/typescript/packages/integration-tests/src/api-contract-scenario.ts b/server/typescript/packages/integration-tests/src/api-contract-scenario.ts index 7800cc80df..e003610311 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-scenario.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-scenario.ts @@ -71,6 +71,9 @@ export interface ApiRequest { method: HttpMethod; path: string; body?: unknown; + /** A body sent byte-for-byte as `application/json` instead of `body` serialized: how a + * scenario sends a body that is not JSON (the `invalid_json` refusal). */ + rawBody?: string; /** Headers sent with the request. */ headers?: Record; expect: ExpectBlock; @@ -109,6 +112,7 @@ function parseScenario(file: string): ApiScenario { method: String(r["method"]).toUpperCase() as HttpMethod, path: String(r["path"]), body: r["body"], + ...(r["rawBody"] !== undefined && { rawBody: String(r["rawBody"]) }), ...(r["headers"] !== undefined && { headers: r["headers"] as Record }), expect: r["expect"] as ExpectBlock, })), @@ -129,8 +133,8 @@ export async function runScenario( for (const req of scenario.requests) { const init: RequestInit = { method: req.method }; const headers: Record = { ...req.headers }; - if (req.body !== undefined) { - init.body = JSON.stringify(req.body); + if (req.body !== undefined || req.rawBody !== undefined) { + init.body = req.rawBody ?? JSON.stringify(req.body); headers["content-type"] = "application/json"; } if (Object.keys(headers).length > 0) init.headers = headers; diff --git a/server/typescript/packages/integration-tests/src/paths.ts b/server/typescript/packages/integration-tests/src/paths.ts index fef020638a..9164920c2b 100644 --- a/server/typescript/packages/integration-tests/src/paths.ts +++ b/server/typescript/packages/integration-tests/src/paths.ts @@ -58,6 +58,10 @@ export const API_CONTRACT_ENUM_DEFAULT_SCENARIOS_DIR = resolve(API_CONTRACT_ENUM // `api` settings subcorpus (GENERATED lane only): `api.pagination` and `api.unknownFields: drop`. export const API_CONTRACT_API_SETTINGS_DIR = resolve(API_CONTRACT_DIR, "api-settings"); export const API_CONTRACT_API_SETTINGS_SCENARIOS_DIR = resolve(API_CONTRACT_API_SETTINGS_DIR, "scenarios"); +export const API_CONTRACT_LIST_QUERY_DIR = resolve(API_CONTRACT_DIR, "list-query"); +export const API_CONTRACT_LIST_QUERY_SCENARIOS_DIR = resolve(API_CONTRACT_LIST_QUERY_DIR, "scenarios"); +/** The shared parse cases of the REST standard's list handling (plan R0). */ +export const LIST_QUERY_CONFORMANCE_DIR = resolve(repoRoot, "fixtures", "list-query-conformance"); export const API_CONTRACT_PROJECTION_DIR = resolve(API_CONTRACT_DIR, "projection"); export const API_CONTRACT_PROJECTION_SCENARIOS_DIR = resolve(API_CONTRACT_PROJECTION_DIR, "scenarios"); diff --git a/server/typescript/packages/integration-tests/test/api-contract-list-query.test.ts b/server/typescript/packages/integration-tests/test/api-contract-list-query.test.ts new file mode 100644 index 0000000000..8df27c8b5c --- /dev/null +++ b/server/typescript/packages/integration-tests/test/api-contract-list-query.test.ts @@ -0,0 +1,47 @@ +// list-query api-contract conformance (GENERATED lane). +// +// Drives fixtures/api-contract-conformance/list-query/ over HTTP against the GENERATED Part +// routes: what a parsed list query matches in a real store (search ignores case, `like` does +// not; or/and; the nesting cap; bare fields; leading wildcards; value formats; paging past 50) +// and the body, id and constraint refusals. The parse itself is pinned with no server by +// fixtures/list-query-conformance/. Generated lane only — see the corpus README. +// +// One Postgres testcontainer for the file, reseeded before every scenario: no scenario +// depends on another's writes, and a container per scenario is twenty container starts. + +import { afterAll, beforeAll, describe, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { API_CONTRACT_LIST_QUERY_DIR, API_CONTRACT_LIST_QUERY_SCENARIOS_DIR } from "../src/paths.ts"; +import { loadScenarios, runScenario } from "../src/api-contract-scenario.ts"; +import { startPostgres } from "../src/postgres-container.ts"; +import { + startGeneratedListQueryServer, + type GeneratedListQueryServerHandle, + type ListQuerySeed, +} from "../src/api-contract-list-query-generated-server.ts"; + +const SEED = JSON.parse(readFileSync(join(API_CONTRACT_LIST_QUERY_DIR, "seed.json"), "utf8")) as ListQuerySeed; +const META_PATH = join(API_CONTRACT_LIST_QUERY_DIR, "meta.json"); + +describe("api contract list-query — GENERATED routes lane", () => { + let pg: Awaited> | null = null; + let server: GeneratedListQueryServerHandle | null = null; + + beforeAll(async () => { + pg = await startPostgres(); + server = await startGeneratedListQueryServer(pg.connectionUri, META_PATH); + }, 120_000); + + afterAll(async () => { + if (server) await server.close(); + if (pg) await pg.stop(); + }); + + for (const scenario of loadScenarios(API_CONTRACT_LIST_QUERY_SCENARIOS_DIR)) { + test(scenario.name, async () => { + await server!.applySeed(SEED); + await runScenario(scenario, server!.baseUrl); + }, { timeout: 60_000 }); + } +}); diff --git a/server/typescript/packages/integration-tests/test/list-query-conformance.test.ts b/server/typescript/packages/integration-tests/test/list-query-conformance.test.ts new file mode 100644 index 0000000000..2c6c6e3869 --- /dev/null +++ b/server/typescript/packages/integration-tests/test/list-query-conformance.test.ts @@ -0,0 +1,90 @@ +// The TypeScript runner of `fixtures/list-query-conformance/` — the shared parse cases of the +// REST standard's list handling (plan R0): a query string and the corpus model's field list +// in, a filter tree (with search, sort and page) or the named 400 body out. No web server and +// no database: what is pinned is the parse, which every port's list route runs before its +// query library sees anything. +// +// TypeScript is the SOURCE of the expected answers. The field list is derived from the model +// the way each port's generator derives its allowlist (here `filterAllowlistRules` / +// `sortAllowlistRules`, the data the generated `FilterAllowlist` is printed from), so +// a port that derives a different allowlist fails here before any route runs. +// +// Regenerate after an intended change: `UPDATE_LIST_QUERY_FIXTURES=1 bun test +// test/list-query-conformance.test.ts`, then review every changed answer — it is the +// cross-port contract. + +import { describe, expect, test } from "bun:test"; +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { isMetaObject, type MetaObject } from "@metaobjectsdev/metadata"; +import { filterAllowlistRules, sortAllowlistRules } from "@metaobjectsdev/codegen-ts"; +import { FilterParseError, parseListQuery, parseListQueryString, type ListQuery } from "@metaobjectsdev/runtime-ts"; +import type { FilterAllowlist, SortAllowlist } from "@metaobjectsdev/runtime-ts"; +import { contractErrorCode } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; +import { LIST_QUERY_CONFORMANCE_DIR } from "../src/paths.ts"; +import { loadMetadataFile } from "../src/load-metadata.ts"; + +const CASES_PATH = join(LIST_QUERY_CONFORMANCE_DIR, "cases.json"); +const UPDATE = process.env.UPDATE_LIST_QUERY_FIXTURES === "1"; + +interface ParseCase { + group: string; + name: string; + query: string; + why: string; + /** `{ list }` — the parsed query, absent members omitted; `{ error }` — the 400 body. */ + expect?: { list: ListQuery } | { error: Record }; +} + +const corpus = JSON.parse(readFileSync(CASES_PATH, "utf8")) as { cases: ParseCase[] }; + +async function ticket(): Promise { + const root = await loadMetadataFile(join(LIST_QUERY_CONFORMANCE_DIR, "meta.json")); + const entity = root.children().find((c) => isMetaObject(c) && c.name === "Ticket"); + if (entity === undefined || !isMetaObject(entity)) throw new Error("list-query-conformance: no Ticket in meta.json"); + return entity; +} + +/** The answer a list route gives a case: the parsed query, or the 400 body it refuses with. */ +function answer(query: string, filter: FilterAllowlist, sort: SortAllowlist, fields: readonly string[]): NonNullable { + try { + const list = parseListQuery({ + query: parseListQueryString(query), + allowlist: filter, + sortAllowlist: sort, + isField: (name) => fields.includes(name), + }); + // Through JSON, so the pinned form is exactly what a port reads back (no undefined members). + return { list: JSON.parse(JSON.stringify(list)) as ListQuery }; + } catch (err) { + if (!(err instanceof FilterParseError)) throw err; + return { error: { error: contractErrorCode(err.code), ...(err.details ?? {}) } }; + } +} + +describe("list-query-conformance", async () => { + const entity = await ticket(); + const filter = Object.fromEntries(filterAllowlistRules(entity)) as unknown as FilterAllowlist; + const sort = Object.fromEntries(sortAllowlistRules(entity)) as SortAllowlist; + const fields = entity.fields().map((f) => f.name); + + test("the corpus is not empty and every name is unique", () => { + expect(corpus.cases.length).toBeGreaterThan(0); + expect(new Set(corpus.cases.map((c) => c.name)).size).toBe(corpus.cases.length); + }); + + if (UPDATE) { + test("regenerate expected answers", () => { + for (const c of corpus.cases) c.expect = answer(c.query, filter, sort, fields); + writeFileSync(CASES_PATH, `${JSON.stringify(corpus, null, 2)}\n`); + }); + return; + } + + for (const c of corpus.cases) { + test(`${c.group}/${c.name}`, () => { + expect(c.expect).toBeDefined(); + expect(answer(c.query, filter, sort, fields)).toEqual(c.expect as NonNullable); + }); + } +}); diff --git a/server/typescript/packages/migrate-ts/src/verify/replay-engine.ts b/server/typescript/packages/migrate-ts/src/verify/replay-engine.ts index 5762d6867a..a61a03dfa3 100644 --- a/server/typescript/packages/migrate-ts/src/verify/replay-engine.ts +++ b/server/typescript/packages/migrate-ts/src/verify/replay-engine.ts @@ -13,8 +13,9 @@ // // Both drivers are OPTIONAL peers imported lazily. PGlite is ~22 MB of WASM and must // not land in the node_modules of every adopter who only ever runs `meta gen`; the -// install hints mirror `buildKyselyFromUrl`'s. `cli` already depends on -// `@libsql/kysely-libsql` outright, so only a direct embedder can miss that one. +// install hints mirror `buildKyselyFromUrl`'s. `@libsql/kysely-libsql` is an optional +// peer of `cli` too (it left the default install; `meta init` adds the driver), so any +// project that never added it gets the install hint below rather than a crash. import { Kysely } from "kysely"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; diff --git a/server/typescript/packages/runtime-ts/README.md b/server/typescript/packages/runtime-ts/README.md index bcd616a9f3..531be8a9a8 100644 --- a/server/typescript/packages/runtime-ts/README.md +++ b/server/typescript/packages/runtime-ts/README.md @@ -83,11 +83,13 @@ type Filter = | { field: value } // equality | { field: null } // IS NULL | { field: [v1, v2] } // IN (...) - | { field: { $eq | $ne | $gt | $gte | $lt | $lte | $like | $in | $isNull: ... } } - | { $and: [...] }; // explicit AND + | { field: { $eq | $ne | $gt | $gte | $lt | $lte | $like | $ilike | $in | $isNull: ... } } + | { $and: [...] } // explicit AND + | { $or: [...] }; // explicit OR ``` -`$or` and nested operators are not yet shipped. +`$ilike` is a case-insensitive LIKE; it is not a wire operator (the REST `like` stays +case-sensitive). Nested operators are not yet shipped. ## What is core here, and what `meta eject` hands you diff --git a/server/typescript/packages/runtime-ts/src/drivers/drizzle-driver.ts b/server/typescript/packages/runtime-ts/src/drivers/drizzle-driver.ts index f69fb5ffda..ca005dba26 100644 --- a/server/typescript/packages/runtime-ts/src/drivers/drizzle-driver.ts +++ b/server/typescript/packages/runtime-ts/src/drivers/drizzle-driver.ts @@ -33,6 +33,7 @@ import { type SQL, } from "drizzle-orm"; import { extractRowCount } from "../drizzle-fastify/util.js"; +import { likePatternToGlob } from "../drizzle-fastify/list-query.js"; import type { PersistenceDriver, SelectSpec, @@ -197,7 +198,7 @@ function makeDrizzleDriver( function applyWhere(qb: AnyTable, where: WhereClause | undefined, table: AnyTable): unknown { if (!where) return undefined; - return buildExpression(where, columnMap(table)); + return buildExpression(where, columnMap(table), dialect); } function applyOrder(qb: AnyDrizzleDB, orderBy: SelectSpec["orderBy"], table: AnyTable): AnyDrizzleDB { @@ -428,7 +429,7 @@ function jsKeyedFromSelect(row: Row, _selectMap: Record): Row } -function buildExpression(w: WhereClause, cols: Map): unknown { +function buildExpression(w: WhereClause, cols: Map, dialect: "sqlite" | "postgres" | "mysql"): unknown { switch (w.kind) { case "eq": { const c = cols.get(w.column); @@ -442,17 +443,32 @@ function buildExpression(w: WhereClause, cols: Map): unknown case "gte": return drzGte(cols.get(w.column), w.value); case "lt": return drzLt(cols.get(w.column), w.value); case "lte": return drzLte(cols.get(w.column), w.value); - case "like": return drzLike(cols.get(w.column), w.pattern); + // `like` is case-SENSITIVE SQL LIKE on every engine (ADR-0049): SQLite's LIKE folds ASCII + // case, so it is GLOB over the translated pattern; MySQL's follows the column's collation, + // so the pattern carries a binary one. + case "like": { + const c = cols.get(w.column); + if (dialect === "sqlite") return sql`${c} GLOB ${likePatternToGlob(w.pattern)}`; + if (dialect === "mysql") return sql`${c} LIKE ${w.pattern} COLLATE utf8mb4_bin`; + return drzLike(c, w.pattern); + } + // Case-insensitive: Postgres ILIKE, SQLite's native LIKE, MySQL with both sides folded. + case "ilike": { + const c = cols.get(w.column); + if (dialect === "postgres") return sql`${c} ILIKE ${w.pattern}`; + if (dialect === "mysql") return sql`LOWER(${c}) LIKE LOWER(${w.pattern})`; + return drzLike(c, w.pattern); + } case "in": return drzInArray(cols.get(w.column), w.values); case "isNull": return w.not ? drzIsNotNull(cols.get(w.column)) : drzIsNull(cols.get(w.column)); case "and": { // drzAnd is typed as accepting SQLWrapper; our recursive return is // structurally compatible but typed as unknown. Cast at the boundary. - const parts = w.clauses.map((c) => buildExpression(c, cols)) as SQL[]; + const parts = w.clauses.map((c) => buildExpression(c, cols, dialect)) as SQL[]; return drzAnd(...parts); } case "or": { - const parts = w.clauses.map((c) => buildExpression(c, cols)) as SQL[]; + const parts = w.clauses.map((c) => buildExpression(c, cols, dialect)) as SQL[]; return drzOr(...parts); } default: { diff --git a/server/typescript/packages/runtime-ts/src/drivers/in-memory-driver.ts b/server/typescript/packages/runtime-ts/src/drivers/in-memory-driver.ts index 9c1d4ac35a..e07f20efb1 100644 --- a/server/typescript/packages/runtime-ts/src/drivers/in-memory-driver.ts +++ b/server/typescript/packages/runtime-ts/src/drivers/in-memory-driver.ts @@ -213,6 +213,11 @@ function matchesWhere(row: Row, where?: WhereClause): boolean { return where.values.some((v) => sameValue(row[where.column], v)); case "like": return likeMatch(row[where.column], where.pattern); + case "ilike": { + // ASCII case folding, as SQLite's LIKE does. + const v = row[where.column]; + return typeof v === "string" && likeMatch(foldAscii(v), foldAscii(where.pattern)); + } case "isNull": { const isNull = row[where.column] === null || row[where.column] === undefined; return where.not ? !isNull : isNull; @@ -265,6 +270,10 @@ function compareValues(left: unknown, right: unknown): number { return String(a).localeCompare(String(b)); } +function foldAscii(s: string): string { + return s.replace(/[A-Z]/g, (c) => c.toLowerCase()); +} + // SQL LIKE: % → .*, _ → ., case-sensitive. Other regex metacharacters in `pattern` are escaped first. function likeMatch(value: unknown, pattern: string): boolean { if (typeof value !== "string") return false; diff --git a/server/typescript/packages/runtime-ts/src/drivers/kysely-driver.ts b/server/typescript/packages/runtime-ts/src/drivers/kysely-driver.ts index 94fe64c3ec..2ab55c95be 100644 --- a/server/typescript/packages/runtime-ts/src/drivers/kysely-driver.ts +++ b/server/typescript/packages/runtime-ts/src/drivers/kysely-driver.ts @@ -4,6 +4,7 @@ import type { UpdateSpec, UpdateManySpec, DeleteSpec, DeleteManySpec, WhereClause, Row, } from "../persistence-driver.js"; import { ConstraintViolationError } from "../errors.js"; +import { likePatternToGlob } from "../drizzle-fastify/list-query.js"; import { arraysAsJsonText, insertedKey, mysqlConstraintKind } from "./mysql-support.js"; // Kysely's fluent builder is heavily generic on the database schema, but this driver @@ -62,7 +63,7 @@ function makeKyselyDriver( async selectOne(spec: SelectSpec): Promise { let q = on(spec.schema).selectFrom(spec.table).select(spec.columns); - q = applyWhere(q, spec.where); + q = applyWhere(q, spec.where, dialect); q = applyOrderLimit(q, spec.orderBy, 1, undefined); const rows = await q.execute(); return (rows[0] as Row | undefined) ?? null; @@ -70,14 +71,14 @@ function makeKyselyDriver( async selectMany(spec: SelectSpec): Promise { let q = on(spec.schema).selectFrom(spec.table).select(spec.columns); - q = applyWhere(q, spec.where); + q = applyWhere(q, spec.where, dialect); q = applyOrderLimit(q, spec.orderBy, spec.limit, spec.offset); return (await q.execute()) as Row[]; }, async count(spec: CountSpec): Promise { let q = on(spec.schema).selectFrom(spec.table).select((eb: AnyExprBuilder) => eb.fn.countAll().as("c")); - q = applyWhere(q, spec.where); + q = applyWhere(q, spec.where, dialect); const rows = (await q.execute()) as Array<{ c: number | string | bigint }>; const v = rows[0]?.c; return typeof v === "number" ? v : Number(v ?? 0); @@ -118,11 +119,11 @@ function makeKyselyDriver( async update(spec: UpdateSpec): Promise { try { let q = on(spec.schema).updateTable(spec.table).set(bindable(spec.values)); - q = applyWhere(q, spec.where); + q = applyWhere(q, spec.where, dialect); if (dialect === "mysql") { await q.execute(); let s = on(spec.schema).selectFrom(spec.table).select(spec.returning); - s = applyWhere(s, spec.where); + s = applyWhere(s, spec.where, dialect); return ((await s.executeTakeFirst()) as Row | undefined) ?? null; } const rows = await q.returning(spec.returning).execute(); @@ -135,7 +136,7 @@ function makeKyselyDriver( async updateMany(spec: UpdateManySpec): Promise { try { let q = on(spec.schema).updateTable(spec.table).set(bindable(spec.values)); - q = applyWhere(q, spec.where); + q = applyWhere(q, spec.where, dialect); const result = await q.executeTakeFirst() as { numUpdatedRows?: bigint | number } | undefined; return Number(result?.numUpdatedRows ?? 0); } catch (err) { @@ -146,7 +147,7 @@ function makeKyselyDriver( async delete(spec: DeleteSpec): Promise { try { let q = on(spec.schema).deleteFrom(spec.table); - q = applyWhere(q, spec.where); + q = applyWhere(q, spec.where, dialect); const result = await q.executeTakeFirst() as { numDeletedRows?: bigint | number } | undefined; return Number(result?.numDeletedRows ?? 0); } catch (err) { @@ -157,7 +158,7 @@ function makeKyselyDriver( async deleteMany(spec: DeleteManySpec): Promise { try { let q = on(spec.schema).deleteFrom(spec.table); - q = applyWhere(q, spec.where); + q = applyWhere(q, spec.where, dialect); const result = await q.executeTakeFirst() as { numDeletedRows?: bigint | number } | undefined; return Number(result?.numDeletedRows ?? 0); } catch (err) { @@ -178,12 +179,36 @@ interface HasWhere { where(cb: (eb: AnyExprBuilder) => Expression): Q; } -function applyWhere>(q: Q, where: WhereClause | undefined): Q { +function applyWhere>(q: Q, where: WhereClause | undefined, dialect: KyselyDialect): Q { if (!where) return q; - return q.where((eb: AnyExprBuilder) => buildExpression(eb, where)); + return q.where((eb: AnyExprBuilder) => buildExpression(eb, where, dialect)); } -function buildExpression(eb: AnyExprBuilder, w: WhereClause): Expression { +type KyselyDialect = "sqlite" | "postgres" | "mysql"; + +/** + * `like` is case-SENSITIVE SQL LIKE on every engine (ADR-0049). Postgres LIKE already is. + * SQLite's is not, so it is the core `glob(pattern, value)` function over the translated + * pattern. MySQL's follows the column's collation (case-insensitive by default), so both + * sides are compared as binary strings. (Kysely, an optional peer, is only TYPE-imported + * here, so there is no `sql` tag for a `COLLATE` clause; binary matching differs from it only + * in `_` matching one byte, not one character, of a multi-byte character.) + */ +function caseSensitiveLike(eb: AnyExprBuilder, column: string, pattern: string, dialect: KyselyDialect): Expression { + if (dialect === "sqlite") return eb(eb.fn("glob", [eb.val(likePatternToGlob(pattern)), eb.ref(column)]), "=", 1); + if (dialect === "mysql") return eb(eb.cast(eb.ref(column), "binary"), "like", eb.cast(eb.val(pattern), "binary")); + return eb(column, "like", pattern); +} + +/** Case-insensitive LIKE: Postgres ILIKE; SQLite's native LIKE (it folds ASCII case); MySQL + * folds both sides, because its LIKE follows the column's collation. */ +function caseInsensitiveLike(eb: AnyExprBuilder, column: string, pattern: string, dialect: KyselyDialect): Expression { + if (dialect === "postgres") return eb(column, "ilike", pattern); + if (dialect === "mysql") return eb(eb.fn("lower", [eb.ref(column)]), "like", eb.fn("lower", [eb.val(pattern)])); + return eb(column, "like", pattern); +} + +function buildExpression(eb: AnyExprBuilder, w: WhereClause, dialect: KyselyDialect): Expression { switch (w.kind) { case "eq": return w.value === null ? eb(w.column, "is", null) : eb(w.column, "=", w.value); case "ne": return w.value === null ? eb(w.column, "is not", null) : eb(w.column, "<>", w.value); @@ -191,11 +216,12 @@ function buildExpression(eb: AnyExprBuilder, w: WhereClause): Expression=", w.value); case "lt": return eb(w.column, "<", w.value); case "lte": return eb(w.column, "<=", w.value); - case "like": return eb(w.column, "like", w.pattern); + case "like": return caseSensitiveLike(eb, w.column, w.pattern, dialect); + case "ilike": return caseInsensitiveLike(eb, w.column, w.pattern, dialect); case "in": return eb(w.column, "in", w.values); case "isNull": return w.not ? eb(w.column, "is not", null) : eb(w.column, "is", null); - case "and": return eb.and(w.clauses.map((c: WhereClause) => buildExpression(eb, c))); - case "or": return eb.or(w.clauses.map((c: WhereClause) => buildExpression(eb, c))); + case "and": return eb.and(w.clauses.map((c: WhereClause) => buildExpression(eb, c, dialect))); + case "or": return eb.or(w.clauses.map((c: WhereClause) => buildExpression(eb, c, dialect))); default: { const exhaustive: never = w; throw new Error(`Unhandled WhereClause kind: ${JSON.stringify(exhaustive)}`); diff --git a/server/typescript/packages/runtime-ts/src/drizzle-fastify/filter-allowlist.ts b/server/typescript/packages/runtime-ts/src/drizzle-fastify/filter-allowlist.ts index e349d9cf03..53003a16de 100644 --- a/server/typescript/packages/runtime-ts/src/drizzle-fastify/filter-allowlist.ts +++ b/server/typescript/packages/runtime-ts/src/drizzle-fastify/filter-allowlist.ts @@ -124,5 +124,5 @@ export function sortOrderSpec( // The `?? "asc"` here is the ONLY place TypeScript's runtime spells the fallback. An // allowlist artifact carries declarations and nothing else — baking the default into // it would put the answer in two places per port, which is how a port drifts. - return supplied ?? allowlist[field]?.defaultOrder ?? "asc"; + return supplied ?? (Object.hasOwn(allowlist, field) ? allowlist[field]?.defaultOrder : undefined) ?? "asc"; } diff --git a/server/typescript/packages/runtime-ts/src/drizzle-fastify/filter-parser.ts b/server/typescript/packages/runtime-ts/src/drizzle-fastify/filter-parser.ts index 534c2f7c3e..d8befb4565 100644 --- a/server/typescript/packages/runtime-ts/src/drizzle-fastify/filter-parser.ts +++ b/server/typescript/packages/runtime-ts/src/drizzle-fastify/filter-parser.ts @@ -1,25 +1,23 @@ import { is, Column, SQL as DrizzleSQL, - eq, ne, gt, gte, lt, lte, inArray, like, ilike, isNull, not, and, or, asc, desc, sql, + eq, ne, gt, gte, lt, lte, inArray, like, ilike, isNull, not, and, or, sql, + asc, desc, type SQL, type SQLWrapper, } from "drizzle-orm"; import type { SqlDialect } from "../sql-dialect.js"; -import type { FilterAllowlist, FilterOp, FilterFieldRule, SortAllowlist } from "./filter-allowlist.js"; -import { sortOrderSpec } from "./filter-allowlist.js"; -import { FilterParseError, parsePageBound, SORT_EXPECTED } from "./list-params.js"; +import type { FilterAllowlist, FilterFieldRule, SortAllowlist } from "./filter-allowlist.js"; +import { FilterParseError } from "./list-params.js"; +import { likePatternToGlob, parseListQuery, type FilterLeaf, type FilterNode, type FilterScalar, type ListSearch } from "./list-query.js"; // Re-exported so existing importers keep one door; the definitions live in the -// drizzle-free list-params module, which the ObjectManager Fastify mount also uses. +// drizzle-free list-params and list-query modules, which the ObjectManager Fastify mount also uses. export { FilterParseError, parsePageBound, pageLimit, ERROR_CODE_LIMIT_TOO_LARGE, type PageSize, PAGINATION_EXPECTED, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, parseReportPage, SORT_EXPECTED } from "./list-params.js"; -import { - ANY_TEMPORAL_EXPECTED, FORMAT_EXPECTED, PLUS_OFFSET_HINT, - looksLikeUnencodedPlusOffset, matchesAnyTemporal, matchesFormat, utcIsoIfZoned, utcIsoInstant, -} from "./filter-value-format.js"; -import { FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_TIMESTAMP } from "@metaobjectsdev/metadata"; -import { canonicalDecimal } from "../decimal-wire.js"; -import { - DURATION_MICROS_MAX, DURATION_MICROS_MIN, durationToStoredMicros, formatPostgresInterval, parseDurationLiteral, -} from "../duration-wire.js"; +export { + likePatternToGlob, parseListQuery, parseListQueryString, rawQueryOf, searchFields, DEFAULT_MAX_IN_LIST, DEFAULT_MAX_NESTING, + type FilterLeaf, type FilterNode, type FilterScalar, type ListQuery, type ListSearch, type ListSort, type ParseListQueryOpts, +} from "./list-query.js"; +import { FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_DURATION } from "@metaobjectsdev/metadata"; +import { durationToStoredMicros, formatPostgresInterval, parseDurationLiteral } from "../duration-wire.js"; // biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user's Drizzle table type AnyTable = any; @@ -39,56 +37,10 @@ export interface ParseFilterResult { orderBy?: SQLWrapper[]; limit?: number; offset?: number; - /** Search predicate — OR(like('%term%')) across @filterable string fields. */ + /** Search predicate — OR(case-insensitive '%term%') across @filterable text fields. */ searchWhere?: SQL; } - -const DEFAULT_MAX_NESTING = 5; -const DEFAULT_MAX_IN_LIST = 100; - -/** Top-level list-query parameters this parser (or the mount around it) reads. A - * filterable field that happens to share one of these names is addressed only through - * `filter[]`, so the bare-field check below never claims them. */ -const RESERVED_LIST_PARAMS: ReadonlySet = new Set([ - "filter", "sort", "limit", "offset", "search", "withCount", -]); - -/** - * `?priority=low` on a list whose allowlist has `priority` is almost always a caller who - * meant `?filter[priority][eq]=low` — and silently ignoring it returns EVERY row, which - * reads as "the filter matched everything". Refuse it, naming the syntax that works. - * - * A bare name that is a field of the entity but NOT on the filter allowlist is refused - * too — the caller plainly meant that field — saying it is not filterable and listing - * the fields that are. Any other unknown parameter — a cache-buster, a tracking tag, a - * param some proxy appends — is left alone, as before. - * TS-only (the other ports ignore unknown parameters): see docs/features/api-contract.md, - * "TS-only filter extensions". - */ -function rejectBareFieldParams(query: Record, allowlist: FilterAllowlist, table: AnyTable): void { - for (const [key, value] of Object.entries(query)) { - if (RESERVED_LIST_PARAMS.has(key)) continue; - if (Object.hasOwn(allowlist, key)) { - const shown = typeof value === "string" ? value : ""; - throw new FilterParseError( - "filter.bare_field", - `"${key}" is a filterable field, but a bare ?${key}= parameter is not a filter. Use filter[${key}][eq]=${shown}.`, - { field: key, expected: `filter[${key}][eq]=${shown}` }, - ); - } - if (isEntityColumn(table, key)) { - const allowed = Object.keys(allowlist); - throw new FilterParseError( - "filter.bare_field", - `"${key}" is a field of this entity, but it is not @filterable, so it cannot be filtered on` + - (allowed.length > 0 ? ` (filterable: ${allowed.join(", ")}).` : " (no field is filterable)."), - { field: key, filterable: false, expected: `a filterable field — "${key}" is not @filterable`, allowed }, - ); - } - } -} - /** Is `key` one of the table's (or view's) own columns? A Drizzle table exposes each * column as a property keyed by its field name; anything else found there (a function, * a symbol-backed config, a proxy that throws on an unknown key) is not a field. */ @@ -102,382 +54,122 @@ function isEntityColumn(table: AnyTable, key: string): boolean { } } +/** A Drizzle column's own enum members (`text(..., { enum })`, `pgEnum`), if it has them. */ +function columnEnumValues(col: unknown): readonly string[] | undefined { + const v = (col as { enumValues?: unknown } | null | undefined)?.enumValues; + return Array.isArray(v) && v.length > 0 && v.every((m) => typeof m === "string") ? (v as string[]) : undefined; +} +/** + * Parse a list query (`parseListQuery`, which raises every refusal) and compile it to + * Drizzle for `opts.table` on `opts.dialect`. + */ export function parseFilterParams(opts: ParseFilterOpts): ParseFilterResult { - rejectBareFieldParams(opts.query, opts.allowlist, opts.table); + const table = opts.table; + const parsed = parseListQuery({ + query: opts.query, + allowlist: opts.allowlist, + sortAllowlist: opts.sortAllowlist, + isField: (name) => isEntityColumn(table, name), + hasColumn: (name) => table[name] !== undefined, + enumValuesOf: (name) => columnEnumValues(table[name]), + ...(opts.maxNesting !== undefined ? { maxNesting: opts.maxNesting } : {}), + ...(opts.maxInListSize !== undefined ? { maxInListSize: opts.maxInListSize } : {}), + }); const result: ParseFilterResult = {}; - - const limit = parsePageBound(opts.query, "limit"); - if (limit !== undefined) result.limit = limit; - const offset = parsePageBound(opts.query, "offset"); - if (offset !== undefined) result.offset = offset; - - if (opts.query.filter && typeof opts.query.filter === "object") { - const where = parseNode( - opts.query.filter as Record, - opts.table, opts.allowlist, opts.dialect, - opts.maxNesting ?? DEFAULT_MAX_NESTING, - opts.maxInListSize ?? DEFAULT_MAX_IN_LIST, - 0, - ); - if (where) result.where = where; - } - - if (typeof opts.query.sort === "string") { - result.orderBy = parseSort(opts.query.sort, opts.table, opts.sortAllowlist, opts.dialect); - } - - if (typeof opts.query.search === "string" && opts.query.search !== "") { - const term = `%${opts.query.search}%`; - const stringCols = Object.entries(opts.allowlist) - // A rule with a `format` (uuid, …) is a typed column on the wire as a string, not - // text: ILIKE on a Postgres uuid column is "operator does not exist" (a 500). - .filter(([, rule]) => { - const r = rule as FilterFieldRule; - return r.subType === "string" && r.format === undefined; - }) - .map(([field]) => opts.table[field]); - if (stringCols.length > 0) { - // `?search` is a TS-only extension (docs/features/api-contract.md) and is - // deliberately case-INSENSITIVE — it is a human search box, not the - // contract's `like` operator (which is case-sensitive SQL LIKE, ADR-0049). - // Postgres uses ILIKE; SQLite's native LIKE folds ASCII case by default, - // which is the intended behavior here. MySQL's LIKE follows the column's - // collation, which is case-insensitive by default and case-sensitive on a - // `_bin` column, so it folds both sides explicitly. - const parts = stringCols.map((col) => - opts.dialect === "postgres" ? ilike(col, term) - : opts.dialect === "mysql" ? sql`LOWER(${col}) LIKE LOWER(${term})` - : like(col, term)); - // or() is defined as returning SQL | undefined but will always return - // SQL when given a non-empty array. parts[0] is always defined here - // because stringCols.length > 0 guarantees at least one element. - // biome-ignore lint/style/noNonNullAssertion: parts is guaranteed non-empty - result.searchWhere = (parts.length === 1 ? parts[0] : or(...parts)) as SQL; - } - } - + if (parsed.limit !== undefined) result.limit = parsed.limit; + if (parsed.offset !== undefined) result.offset = parsed.offset; + if (parsed.filter !== undefined) result.where = compileFilterNode(parsed.filter, table, opts.allowlist, opts.dialect); + if (parsed.sort !== undefined) result.orderBy = nullsAsLargest(table[parsed.sort.field], parsed.sort.order, opts.dialect); + if (parsed.search !== undefined) result.searchWhere = compileSearch(parsed.search, table, opts.dialect); return result; } -function parseNode( - node: Record, - table: AnyTable, - allowlist: FilterAllowlist, - dialect: SqlDialect, - maxNesting: number, - maxInList: number, - depth: number, -): SQL | undefined { - if (depth > maxNesting) { - throw new FilterParseError("filter.nesting_too_deep", `Filter nesting depth exceeds limit (${maxNesting}).`, { limit: maxNesting }); - } - const parts: SQL[] = []; - for (const [key, value] of Object.entries(node)) { - if (key === "or") { - const subs = ensureArray(value, "or").map((sub) => - parseNode(sub as Record, table, allowlist, dialect, maxNesting, maxInList, depth + 1) - ).filter((s): s is SQL => !!s); - if (subs.length > 0) parts.push(or(...subs)!); - } else if (key === "and") { - const subs = ensureArray(value, "and").map((sub) => - parseNode(sub as Record, table, allowlist, dialect, maxNesting, maxInList, depth + 1) - ).filter((s): s is SQL => !!s); - if (subs.length > 0) parts.push(and(...subs)!); - } else { - // key is a field name - const rule = allowlist[key]; - if (!rule) { - throw new FilterParseError("filter.unknown_field", `Unknown filter field "${key}".`, { field: key, allowed: Object.keys(allowlist) }); - } - const col = table[key]; - if (col === undefined) { - throw new FilterParseError("filter.unknown_field", `Table has no column for field "${key}".`, { field: key }); - } - if (typeof value === "object" && value !== null && !Array.isArray(value)) { - for (const [opKey, opValue] of Object.entries(value)) { - const expr = compileOp(col, rule, key, opKey, opValue, dialect, maxInList); - if (expr) parts.push(expr); - } - } else { - // Bare value = eq sugar - const expr = compileOp(col, rule, key, "eq", value, dialect, maxInList); - if (expr) parts.push(expr); - } - } - } - if (parts.length === 0) return undefined; - if (parts.length === 1) return parts[0]; - return and(...parts); +/** Compile a parsed filter tree to a Drizzle condition over `table`. */ +export function compileFilterNode(node: FilterNode, table: AnyTable, allowlist: FilterAllowlist, dialect: SqlDialect): SQL { + if ("and" in node) return and(...node.and.map((n) => compileFilterNode(n, table, allowlist, dialect))) as SQL; + if ("or" in node) return or(...node.or.map((n) => compileFilterNode(n, table, allowlist, dialect))) as SQL; + return compileLeaf(node, table[node.field], allowlist[node.field] as FilterFieldRule, dialect); } -function compileOp( - col: unknown, - rule: FilterFieldRule, - field: string, - op: string, - value: unknown, - dialect: SqlDialect, - maxInList: number, -): SQL | undefined { - if (!rule.ops.includes(op as FilterOp)) { - throw new FilterParseError("filter.unsupported_op", `Op "${op}" not supported for field "${field}".`, { field, op, allowed: rule.ops }); - } - switch (op as FilterOp) { - case "eq": return eq(col as any, coerce(value, rule, col, field, op, dialect)); - case "ne": return ne(col as any, coerce(value, rule, col, field, op, dialect)); - case "gt": return gt(col as any, coerce(value, rule, col, field, op, dialect)); - case "gte": return gte(col as any, coerce(value, rule, col, field, op, dialect)); - case "lt": return lt(col as any, coerce(value, rule, col, field, op, dialect)); - case "lte": return lte(col as any, coerce(value, rule, col, field, op, dialect)); - case "in": { - const list = String(value).split(",").map((v) => coerce(v.trim(), rule, col, field, op, dialect)); - if (list.length > maxInList) { - throw new FilterParseError("filter.in_too_large", `In-list size ${list.length} exceeds limit ${maxInList}.`, { field, limit: maxInList }); - } - return inArray(col as any, list); - } +/** + * `?search` is deliberately case-INSENSITIVE — a human search box, not the contract's `like` + * operator (case-sensitive SQL LIKE, ADR-0049). Postgres uses ILIKE; SQLite's native LIKE + * folds ASCII case, which is the intended behavior here. MySQL's LIKE follows the column's + * collation (case-insensitive by default, case-sensitive on a `_bin` column), so it folds + * both sides explicitly. + */ +function compileSearch(search: ListSearch, table: AnyTable, dialect: SqlDialect): SQL { + const term = `%${search.term}%`; + const parts = search.fields.map((field) => { + const col = table[field]; + return dialect === "postgres" ? ilike(col, term) + : dialect === "mysql" ? sql`LOWER(${col}) LIKE LOWER(${term})` + : like(col, term); + }); + return (parts.length === 1 ? parts[0] : or(...parts)) as SQL; +} + +function compileLeaf(leaf: FilterLeaf, col: unknown, rule: FilterFieldRule, dialect: SqlDialect): SQL { + // biome-ignore lint/suspicious/noExplicitAny: a column of the adopter's Drizzle table + const c = col as any; + const bind = (v: FilterScalar): unknown => bindOperand(v, rule, leaf, dialect); + switch (leaf.op) { + case "eq": return eq(c, bind(leaf.value as FilterScalar)); + case "ne": return ne(c, bind(leaf.value as FilterScalar)); + case "gt": return gt(c, bind(leaf.value as FilterScalar)); + case "gte": return gte(c, bind(leaf.value as FilterScalar)); + case "lt": return lt(c, bind(leaf.value as FilterScalar)); + case "lte": return lte(c, bind(leaf.value as FilterScalar)); + case "in": return inArray(c, (leaf.value as readonly FilterScalar[]).map(bind)); case "like": { - const s = String(value); - if (s.startsWith("%") && !rule.leadingWildcard) { - throw new FilterParseError("filter.leading_wildcard_disallowed", `Leading wildcard not allowed for field "${field}".`, { field }); - } - // Cross-port contract (ADR-0049): `like` is case-SENSITIVE SQL LIKE — - // verbatim author-supplied pattern, `%`/`_` wildcards. Postgres LIKE is - // already case-sensitive. SQLite's built-in LIKE folds ASCII case by - // default (and `PRAGMA case_sensitive_like` is connection-global on a - // consumer-owned connection), so the sqlite branch lowers to GLOB with - // an exactly-translated pattern instead. - // MySQL's LIKE follows the column's collation, which is case-INSENSITIVE by - // default, so the pattern carries an explicit binary collation. + const s = leaf.value as string; + // Cross-port contract (ADR-0049): `like` is case-SENSITIVE SQL LIKE — verbatim + // pattern, `%`/`_` wildcards. Postgres LIKE already is. SQLite's built-in LIKE folds + // ASCII case by default (and `PRAGMA case_sensitive_like` is connection-global on a + // consumer-owned connection), so sqlite lowers to GLOB with an exactly-translated + // pattern. MySQL's LIKE follows the column's collation, so the pattern carries an + // explicit binary collation. return dialect === "postgres" - ? like(col as any, s) + ? like(c, s) : dialect === "mysql" - ? sql`${col} LIKE ${s} COLLATE utf8mb4_bin` - : sql`${col} GLOB ${likePatternToGlob(s)}`; - } - case "isNull": { - // isNull's value is always coerced as boolean (true/false), regardless of the - // field's declared subType — the operator is "is the value null?", not "is X - // equal to null?". Field subtype is irrelevant. - const b = coerceAs(value, "boolean", field, op) as boolean; - return b ? isNull(col as any) : not(isNull(col as any)); + ? sql`${c} LIKE ${s} COLLATE utf8mb4_bin` + : sql`${c} GLOB ${likePatternToGlob(s)}`; } + case "isNull": + return leaf.value === true ? isNull(c) : not(isNull(c)); } } /** - * Translate a SQL LIKE pattern into an equivalent SQLite GLOB pattern: - * `%` → `*`, `_` → `?`, and GLOB's own metacharacters (`*`, `?`, `[`) are - * wrapped in single-character classes so they match literally. `]` is only - * special inside a class, so it passes through. GLOB is case-sensitive, - * which is why the sqlite `like` branch uses it (ADR-0049) — SQLite's - * native LIKE folds ASCII case by default. + * Spell a checked operand the way the column binds it. A decimal operand is exact text + * (ADR-0019 Amendment 1, W2); MySQL compares a DECIMAL column with a string operand as + * DOUBLES, so there it is cast to a wide DECIMAL, and SQLite / D1 hold a decimal as a double + * (W4) and order every number before any text, so there it is bound as the number it is. A + * duration is the microsecond integer on SQLite / D1 / MySQL and the interval spelling on + * Postgres (which refuses a signed ISO-8601 duration). A timestamp on a column emitted under + * `timestampMode: "date"` (`dateValues`) binds a real `Date`: Drizzle calls `toISOString()` + * on it. */ -export function likePatternToGlob(pattern: string): string { - let out = ""; - for (const ch of pattern) { - if (ch === "%") out += "*"; - else if (ch === "_") out += "?"; - else if (ch === "*") out += "[*]"; - else if (ch === "?") out += "[?]"; - else if (ch === "[") out += "[[]"; - else out += ch; - } - return out; -} - -function invalidValue( - field: string, - op: string, - s: string, - expected: string, - extra: Record = {}, -): FilterParseError { - const hint = typeof extra["hint"] === "string" ? ` Hint: ${extra["hint"]}.` : ""; - return new FilterParseError( - "filter.invalid_value", - `Field "${field}" op "${op}" requires ${expected}, got "${s}".${hint}`, - { field, op, expected, ...extra }, - ); -} - -/** A Drizzle column's own enum members (`text(..., { enum })`, `pgEnum`), if it has them. */ -function columnEnumValues(col: unknown): readonly string[] | undefined { - const v = (col as { enumValues?: unknown } | null | undefined)?.enumValues; - return Array.isArray(v) && v.length > 0 && v.every((m) => typeof m === "string") ? (v as string[]) : undefined; -} - -/** - * Refuse a value that cannot be the field's type BEFORE it is bound. Without this a - * malformed date on SQLite compared as text and silently matched nothing (200 `[]`), - * and on Postgres the driver refused the cast (a 500) — either way the caller could not - * tell a typo from an empty result. The envelope is the cross-port `invalid_filter_value`, - * carrying `op` and `expected` as the number/boolean checks already did. - */ -function assertWellFormed(s: string, rule: FilterFieldRule, col: unknown, field: string, op: string): void { - const members = rule.enumValues ?? columnEnumValues(col); - if (members !== undefined && !members.includes(s)) { - throw invalidValue(field, op, s, `one of: ${members.join(", ")}`, { allowed: [...members] }); - } - if (rule.format !== undefined) { - if (!matchesFormat(rule.format, s)) { - // `filter[dueAt][lt]=2026-10-06T00:00:00+00:00` sent unencoded arrives with a space - // where the `+` was; "expected timestamp" alone does not say why a valid-looking - // value failed, so the answer names the fix. - const hint = rule.format === FIELD_SUBTYPE_TIMESTAMP && looksLikeUnencodedPlusOffset(s) - ? { hint: PLUS_OFFSET_HINT } - : {}; - throw invalidValue(field, op, s, FORMAT_EXPECTED[rule.format], hint); - } - } else if (rule.subType === "datetime" && !matchesAnyTemporal(s)) { - throw invalidValue(field, op, s, ANY_TEMPORAL_EXPECTED); - } -} - -/** Check a comparison value against the field's rule, then coerce it for binding. */ -function coerce(value: unknown, rule: FilterFieldRule, col: unknown, field: string, op: string, dialect: SqlDialect): unknown { - if (value === null || value === undefined) return null; - const s = typeof value === "string" ? value : String(value); - assertWellFormed(s, rule, col, field, op); - // A decimal operand is exact text, never a number (ADR-0019 Amendment 1, W2): parsed with - // the JSON-number grammar and bound as its canonical string. MySQL compares a DECIMAL column - // with a string operand as DOUBLES, so there the operand is cast to a wide DECIMAL first. - // SQLite and D1 hold a decimal as a double (W4) and order every number before any text, so a - // text operand against a computed column (a view's sum or average has no NUMERIC affinity) - // would compare false in the wrong direction: the operand is bound as the number it is, exact - // to the 15 digits W4 promises. +function bindOperand(v: FilterScalar, rule: FilterFieldRule, leaf: FilterLeaf, dialect: SqlDialect): unknown { if (rule.format === FIELD_SUBTYPE_DECIMAL) { - const canonical = canonicalDecimal(s) as string; - if (dialect === "mysql") return sql`CAST(${canonical} AS DECIMAL(65,30))`; - return dialect === "sqlite" ? Number(canonical) : canonical; + if (dialect === "mysql") return sql`CAST(${v} AS DECIMAL(65,30))`; + return dialect === "sqlite" ? Number(v) : v; } - // A duration bound is spelled the way the column stores it: the microsecond integer on SQLite / - // D1 / MySQL, the interval spelling on Postgres (which refuses a signed ISO-8601 duration). Both - // compare and order as the span does. if (rule.format === FIELD_SUBTYPE_DURATION) { - const micros = parseDurationLiteral(s) as bigint; - // A well-formed span past 64 bits of microseconds is no stored value on any database, so it is - // a bad operand (400), not an error out of the binder. - if (micros > DURATION_MICROS_MAX || micros < DURATION_MICROS_MIN) throw invalidValue(field, op, s, DURATION_IN_RANGE); + const micros = parseDurationLiteral(String(v)) as bigint; return dialect === "sqlite" || dialect === "mysql" ? durationToStoredMicros(micros) : formatPostgresInterval(micros); } - // A timestamp bound is compared in the same UTC spelling the generated schemas store: - // on SQLite/D1 the column is TEXT and compares as text. An instant field (`instant`, i.e. - // not @localTime) reads a zoneless or date-only bound as UTC, as its write schema does — - // also before a Date-bound (`dateValues`) column's `new Date(...)`, which would otherwise - // read a zoneless string in the SERVER's local zone. Without `instant`, only a zoned - // bound is rewritten, and a Date-bound column parses the value itself. - if (rule.format === FIELD_SUBTYPE_TIMESTAMP) { - const bound = rule.instant === true ? utcIsoInstant(s) : rule.dateValues === true ? s : utcIsoIfZoned(s); - return coerceAs(bound, rule.subType, field, op, rule.dateValues); - } - const coerced = coerceAs(s, rule.subType, field, op, rule.dateValues); - // field.int / field.long / field.currency: a fractional bound is not a value of the field. - if (rule.integer === true && typeof coerced === "number" && !Number.isInteger(coerced)) { - throw invalidValue(field, op, s, INTEGER_EXPECTED); - } - return coerced; -} - -/** `expected` for a non-whole bound on an integer-valued field (`integer: true`). */ -const INTEGER_EXPECTED = "integer (a whole number)"; -const DURATION_IN_RANGE = "duration within the 64-bit microsecond range"; - -function coerceAs(value: unknown, subType: string, field: string, op: string, dateValues?: boolean): unknown { - if (value === null || value === undefined) return null; - const s = typeof value === "string" ? value : String(value); - switch (subType) { - case "string": return s; - case "boolean": { - if (s === "true" || s === "1") return true; - if (s === "false" || s === "0") return false; - throw new FilterParseError("filter.invalid_value", `Field "${field}" op "${op}" requires boolean, got "${s}".`, { field, op, expected: "boolean" }); - } - case "number": { - // `Number("")` and `Number(" ")` are 0 — an empty bound is not the number zero. - const n = s.trim() === "" ? Number.NaN : Number(s); - if (!Number.isFinite(n)) { - throw new FilterParseError("filter.invalid_value", `Field "${field}" op "${op}" requires number, got "${s}".`, { field, op, expected: "number" }); - } - return n; + if (rule.subType === "datetime" && rule.dateValues === true) { + const d = new Date(String(v)); + // `new Date("garbage")` is an Invalid Date rather than a throw; binding one would emit + // `NaN`-shaped SQL. + if (Number.isNaN(d.getTime())) { + throw new FilterParseError("filter.invalid_value", `Field "${leaf.field}" op "${leaf.op}" requires a date, got "${String(v)}".`, { field: leaf.field, op: leaf.op, expected: "date" }); } - // Under codegen's Postgres-only `timestampMode: "date"` the Drizzle column is - // Date-typed and calls `value.toISOString()` on any bound value, so passing the - // raw qs string through threw `TypeError: value.toISOString is not a function` - // for every op except isNull. The generated allowlist now carries `dateValues` - // for exactly those columns (see FilterFieldRule), so the value is bound as a - // real Date. In the default "string" mode — and for field.date / field.time, - // which Drizzle types as strings under every dialect — the flag is absent and - // the value stays a string, unchanged. - case "datetime": { - if (dateValues !== true) return s; - const d = new Date(s); - // `new Date("garbage")` yields an Invalid Date rather than throwing; binding - // one would emit `NaN`-shaped SQL. Reject at the boundary, matching how the - // number and boolean cases report a malformed value. - if (Number.isNaN(d.getTime())) { - throw new FilterParseError("filter.invalid_value", `Field "${field}" op "${op}" requires a date, got "${s}".`, { field, op, expected: "date" }); - } - return d; - } - default: return s; - } -} - -function ensureArray(v: unknown, key: string): unknown[] { - if (Array.isArray(v)) return v; - if (v && typeof v === "object") { - // qs.parse may produce { "0": ..., "1": ... } shape for filter[or][0]... - return Object.values(v); - } - // Defensive — qs.parse normally produces an object/array; this branch is - // only reachable if a caller hand-constructs a malformed query object. - // - // `field` (not `key`) because this maps to the cross-port `invalid_filter_value` - // envelope, which REQUIRES `field` naming the offending filter key — here the - // `or`/`and` connector that was handed a non-array. - throw new FilterParseError("filter.invalid_value", `Expected array for "${key}".`, { field: key }); -} - -function parseSort(spec: string, table: AnyTable, sortAllowlist: SortAllowlist, dialect: SqlDialect | undefined): SQLWrapper[] { - const colonIdx = spec.indexOf(":"); - const field = colonIdx === -1 ? spec : spec.slice(0, colonIdx); - if (!sortAllowlist[field]) { - throw new FilterParseError( - "sort.unknown_field", - `Unknown sort field "${field}". The syntax is ${SORT_EXPECTED}.`, - { field, expected: SORT_EXPECTED, allowed: Object.keys(sortAllowlist) }, - ); - } - // `?sort=field` with no `:order` takes the field's DECLARED default order. - // - // This is the read side of `@sortableDefaultOrder`, and until now there was none. - // The attribute was authored by an adopter, carried through the loader, and emitted - // into the generated `SortAllowlist` as `{ defaultOrder: "desc" }` — and then - // nothing read it back. One door in, no door out: the adopter authored a promise the - // product never kept, and every unqualified sort came back ascending regardless. - // - // Scoped deliberately to "field named, order omitted". Applying it when `?sort` is - // ABSENT ENTIRELY would give every endpoint a default ordering it does not have - // today — a behaviour change for every consumer, to honour an attribute about how a - // FIELD sorts. The declaration says which way this column runs when you do not say; - // it does not say which column to sort by. - const orderRaw = sortOrderSpec( - sortAllowlist, - field, - colonIdx === -1 ? undefined : spec.slice(colonIdx + 1), - ); - const order = orderRaw.toLowerCase(); - if (order !== "asc" && order !== "desc") { - throw new FilterParseError( - "sort.invalid_order", - `Sort order must be asc|desc, got "${orderRaw}". The syntax is ${SORT_EXPECTED}.`, - { field, expected: SORT_EXPECTED, allowed: Object.keys(sortAllowlist) }, - ); + return d; } - const col = table[field]; - return nullsAsLargest(col as any, order, dialect); + return v; } /** diff --git a/server/typescript/packages/runtime-ts/src/drizzle-fastify/index.ts b/server/typescript/packages/runtime-ts/src/drizzle-fastify/index.ts index 9eb84fd2a9..225721b86a 100644 --- a/server/typescript/packages/runtime-ts/src/drizzle-fastify/index.ts +++ b/server/typescript/packages/runtime-ts/src/drizzle-fastify/index.ts @@ -23,7 +23,7 @@ import type { FastifyInstance, RouteShorthandOptions } from "fastify"; import { classifyConstraintError, RedactedDatabaseError, logAndRedact } from "../constraint-errors.js"; import type { ZodTypeAny } from "zod"; import { eq, count, and, asc } from "drizzle-orm"; -import qs from "qs"; +import { parseListQueryString } from "./list-query.js"; import type { FilterAllowlist, SortAllowlist } from "./filter-allowlist.js"; export type { FilterAllowlist, SortAllowlist } from "./filter-allowlist.js"; import { parseFilterParams, parsePageBound, pageLimit, FilterParseError, type PageSize } from "./filter-parser.js"; @@ -35,6 +35,10 @@ import { withContractErrorHandler } from "./route-error-handler.js"; import { validationErrorBody } from "../route-errors.js"; export { isTruthyFlag, contractErrorCode, parseId, coerceIdForColumn } from "./util.js"; export { pageLimit, ERROR_CODE_LIMIT_TOO_LARGE, type PageSize } from "./list-params.js"; +export { + parseListQuery, parseListQueryString, rawQueryOf, FilterParseError, + type FilterNode, type ListQuery, type ParseListQueryOpts, +} from "./filter-parser.js"; export { ERROR_CODE_UNKNOWN_FIELDS, unknownBodyKeys } from "../wire-format.js"; export { timestampWire, canonicalTimestamp } from "../timestamp-wire.js"; export { decimalWire, withDecimals, decimalToNative, canonicalDecimal, parseDecimalInput, parseDecimalOperand } from "../decimal-wire.js"; @@ -210,7 +214,7 @@ export function mountListRoute(opts: VerbOptions): void { const rawSearch = req.raw.url?.includes("?") ? req.raw.url.slice(req.raw.url.indexOf("?") + 1) : ""; - const qsParsed = qs.parse(rawSearch) as Record; + const qsParsed = parseListQueryString(rawSearch); const withCount = isTruthyFlag(qsParsed.withCount); // FR-017 TPH: when subtype-scoped, AND the discriminator predicate into diff --git a/server/typescript/packages/runtime-ts/src/drizzle-fastify/list-params.ts b/server/typescript/packages/runtime-ts/src/drizzle-fastify/list-params.ts index f8499489b1..1a1bdc3412 100644 --- a/server/typescript/packages/runtime-ts/src/drizzle-fastify/list-params.ts +++ b/server/typescript/packages/runtime-ts/src/drizzle-fastify/list-params.ts @@ -27,9 +27,9 @@ export const PAGINATION_EXPECTED = "a non-negative integer (0 or more)"; * Read `?limit=` / `?offset=` as a non-negative integer, or refuse it. Before, a value * that was not a finite number (`?limit=abc`) was dropped — every row came back — and a * negative or fractional one reached SQL. `max` is the ceiling a mount clamps to, when it - * has one: a bound above it is refused rather than silently lowered. TS-only (no corpus - * scenario sends a malformed page bound): see docs/features/api-contract.md, "TS-only - * error responses". + * has one: a bound above it is refused rather than silently lowered. Part of the REST + * contract (docs/features/api-contract.md, "Error responses for a bad request or a failed + * write"), pinned by `list-query/pagination-invalid-value` and `report/bad-page-bound`. */ export function parsePageBound( query: Record, diff --git a/server/typescript/packages/runtime-ts/src/drizzle-fastify/list-query.ts b/server/typescript/packages/runtime-ts/src/drizzle-fastify/list-query.ts new file mode 100644 index 0000000000..05c4fd2c20 --- /dev/null +++ b/server/typescript/packages/runtime-ts/src/drizzle-fastify/list-query.ts @@ -0,0 +1,385 @@ +/** + * The list query a REST list route reads, parsed into a port-neutral form BEFORE any query + * library sees it: a filter tree, a search, a sort, a page. Every refusal of the REST standard + * is raised here (`docs/features/api-contract.md`, "List handling"), so the Drizzle mounts and + * the ObjectManager mount refuse a request identically and differ only in how they run the + * tree. Deliberately free of drizzle-orm (an OPTIONAL peer), like `list-params.ts`. + * + * `fixtures/list-query-conformance/` pins this function's answers — a query string and a + * field list in, a tree or a named error out — for every port. + */ + +import qs from "qs"; +import { FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_TIMESTAMP } from "@metaobjectsdev/metadata"; +import type { FilterAllowlist, FilterFieldRule, FilterOp, SortAllowlist } from "./filter-allowlist.js"; +import { sortOrderSpec } from "./filter-allowlist.js"; +import { FilterParseError, parsePageBound, SORT_EXPECTED } from "./list-params.js"; +import { + ANY_TEMPORAL_EXPECTED, FORMAT_EXPECTED, PLUS_OFFSET_HINT, + looksLikeUnencodedPlusOffset, matchesAnyTemporal, matchesFormat, utcIsoIfZoned, utcIsoInstant, +} from "./filter-value-format.js"; +import { canonicalDecimal } from "../decimal-wire.js"; +import { DURATION_MICROS_MAX, DURATION_MICROS_MIN, parseDurationLiteral } from "../duration-wire.js"; + +/** A scalar operand after its checks: a number or boolean as that type, everything else text. */ +export type FilterScalar = string | number | boolean; + +/** One comparison. `in` carries a list; `isNull` a boolean; every other op one scalar. */ +export interface FilterLeaf { + readonly field: string; + readonly op: FilterOp; + readonly value: FilterScalar | readonly FilterScalar[]; +} + +/** A filter tree: a comparison, or an AND / OR of subtrees (never empty). */ +export type FilterNode = FilterLeaf | { readonly and: readonly FilterNode[] } | { readonly or: readonly FilterNode[] }; + +export interface ListSearch { + /** The term as sent; matched case-insensitively as a substring. */ + readonly term: string; + /** The `@filterable` text fields it is matched against (OR), in allowlist order. */ + readonly fields: readonly string[]; +} + +export interface ListSort { + readonly field: string; + readonly order: "asc" | "desc"; +} + +export interface ListQuery { + readonly filter?: FilterNode; + readonly search?: ListSearch; + readonly sort?: ListSort; + readonly limit?: number; + readonly offset?: number; +} + +export interface ParseListQueryOpts { + /** The bracketed query, as `parseListQueryString` returns it. */ + readonly query: Record; + readonly allowlist: FilterAllowlist; + readonly sortAllowlist: SortAllowlist; + /** + * Is `name` a field of the entity (a column of the table or view the list reads)? A bare + * `?name=` naming one that is not filterable is refused as `filter.bare_field`; absent, only + * a bare FILTERABLE field is refused. + */ + readonly isField?: (name: string) => boolean; + /** A field on the allowlist the read source has no column for (an allowlist out of step + * with its table) is `invalid_filter_field`. Absent, every allowlisted field has one. */ + readonly hasColumn?: (name: string) => boolean; + /** The enum members of a field whose rule carries none (an allowlist generated before + * `enumValues` existed: the Drizzle column's own members). */ + readonly enumValuesOf?: (name: string) => readonly string[] | undefined; + readonly maxNesting?: number; + readonly maxInListSize?: number; +} + +/** The deepest `or` / `and` nesting a filter may use; one level deeper is `filter.nesting_too_deep`. */ +export const DEFAULT_MAX_NESTING = 5; +/** The most elements an `in` list may carry; one more is `filter.in_too_large`. */ +export const DEFAULT_MAX_IN_LIST = 100; + +/** + * Parse a raw query string (no leading `?`) into the bracketed tree the list routes read. + * + * qs's defaults would cut the tree short: past 5 brackets it keeps the rest of a key as one + * literal string (`filter[or][0][or][0][or][0][a][eq]` became a field named `[0][a][eq]`, an + * `invalid_filter_field` naming a field nobody sent), so the nesting cap could never be reached + * and a three-level filter was refused for the wrong reason. The depth here admits one level + * past the cap — two brackets per level plus the field and the op — so a too-deep filter is + * answered as one, and an index above 20 stays an index rather than becoming an object key. + */ +export function parseListQueryString(raw: string, maxNesting: number = DEFAULT_MAX_NESTING): Record { + return qs.parse(raw, { depth: 2 * (maxNesting + 1) + 3, arrayLimit: DEFAULT_MAX_IN_LIST }) as Record; +} + +/** The query string of a request URL (`/x?a=1` → `a=1`; no `?` → ""). */ +export function rawQueryOf(url: string | undefined): string { + if (url === undefined) return ""; + const i = url.indexOf("?"); + return i === -1 ? "" : url.slice(i + 1); +} + +/** Top-level list-query parameters this parser (or the mount around it) reads. A + * filterable field that happens to share one of these names is addressed only through + * `filter[]`, so the bare-field check below never claims them. */ +const RESERVED_LIST_PARAMS: ReadonlySet = new Set([ + "filter", "sort", "limit", "offset", "search", "withCount", +]); + +/** + * Parse and check a list query. The checks run in a fixed order, which is part of the + * contract when a request carries more than one fault: bare field parameters, `limit`, + * `offset`, the filter (depth-first, in the order its keys were sent), `sort`, `search`. + */ +export function parseListQuery(opts: ParseListQueryOpts): ListQuery { + rejectBareFieldParams(opts.query, opts.allowlist, opts.isField); + const out: { -readonly [K in keyof ListQuery]: ListQuery[K] } = {}; + + const limit = parsePageBound(opts.query, "limit"); + if (limit !== undefined) out.limit = limit; + const offset = parsePageBound(opts.query, "offset"); + if (offset !== undefined) out.offset = offset; + + if (opts.query.filter && typeof opts.query.filter === "object") { + const filter = parseNode(opts.query.filter as Record, opts, 0); + if (filter) out.filter = filter; + } + + if (typeof opts.query.sort === "string") out.sort = parseSort(opts.query.sort, opts.sortAllowlist); + + if (typeof opts.query.search === "string" && opts.query.search !== "") { + const fields = searchFields(opts.allowlist); + if (fields.length > 0) out.search = { term: opts.query.search, fields }; + } + return out; +} + +/** + * The fields `?search` matches: `@filterable` text fields. A rule with a `format` (uuid, …) + * is a typed column that is a string on the wire, not text — a case-insensitive LIKE on a + * Postgres uuid column is "operator does not exist" (a 500). + */ +export function searchFields(allowlist: FilterAllowlist): string[] { + return Object.entries(allowlist) + // A search term is a `like` pattern, so only a field whose band has `like` takes part: a + // typed column spelled as a string (uuid, a `format`) and an int-backed enum (an integer + // column, no `like` in its band) would make Postgres answer "operator does not exist". + .filter(([, rule]) => rule.subType === "string" && rule.format === undefined && rule.ops.includes("like")) + .map(([field]) => field); +} + +/** + * `?priority=low` on a list whose allowlist has `priority` is almost always a caller who + * meant `?filter[priority][eq]=low` — and silently ignoring it returns EVERY row, which + * reads as "the filter matched everything". Refuse it, naming the syntax that works. + * + * A bare name that is a field of the entity but NOT on the filter allowlist is refused + * too — the caller plainly meant that field — saying it is not filterable and listing + * the fields that are. Any other unknown parameter — a cache-buster, a tracking tag, a + * param some proxy appends — is left alone. + */ +function rejectBareFieldParams( + query: Record, + allowlist: FilterAllowlist, + isField: ((name: string) => boolean) | undefined, +): void { + for (const [key, value] of Object.entries(query)) { + if (RESERVED_LIST_PARAMS.has(key)) continue; + if (Object.hasOwn(allowlist, key)) { + const shown = typeof value === "string" ? value : ""; + throw new FilterParseError( + "filter.bare_field", + `"${key}" is a filterable field, but a bare ?${key}= parameter is not a filter. Use filter[${key}][eq]=${shown}.`, + { field: key, expected: `filter[${key}][eq]=${shown}` }, + ); + } + if (isField?.(key) === true) { + const allowed = Object.keys(allowlist); + throw new FilterParseError( + "filter.bare_field", + `"${key}" is a field of this entity, but it is not @filterable, so it cannot be filtered on` + + (allowed.length > 0 ? ` (filterable: ${allowed.join(", ")}).` : " (no field is filterable)."), + { field: key, filterable: false, expected: `a filterable field — "${key}" is not @filterable`, allowed }, + ); + } + } +} + +function parseNode(node: Record, opts: ParseListQueryOpts, depth: number): FilterNode | undefined { + const maxNesting = opts.maxNesting ?? DEFAULT_MAX_NESTING; + if (depth > maxNesting) { + throw new FilterParseError("filter.nesting_too_deep", `Filter nesting depth exceeds limit (${maxNesting}).`, { limit: maxNesting }); + } + const parts: FilterNode[] = []; + for (const [key, value] of Object.entries(node)) { + if (key === "or" || key === "and") { + const subs = ensureArray(value, key) + .map((sub) => parseNode(asNode(sub, key), opts, depth + 1)) + .filter((s): s is FilterNode => s !== undefined); + if (subs.length === 0) continue; + // One branch is that branch: `or` of one condition is the condition. + parts.push(subs.length === 1 ? (subs[0] as FilterNode) : key === "or" ? { or: subs } : { and: subs }); + continue; + } + const rule = Object.hasOwn(opts.allowlist, key) ? opts.allowlist[key] : undefined; + if (!rule) { + throw new FilterParseError("filter.unknown_field", `Unknown filter field "${key}".`, { field: key, allowed: Object.keys(opts.allowlist) }); + } + if (opts.hasColumn !== undefined && !opts.hasColumn(key)) { + throw new FilterParseError("filter.unknown_field", `Table has no column for field "${key}".`, { field: key }); + } + if (typeof value === "object" && value !== null && !Array.isArray(value)) { + for (const [op, operand] of Object.entries(value)) parts.push(leaf(key, rule, op, operand, opts)); + } else { + // A bare value is `eq` sugar. + parts.push(leaf(key, rule, "eq", value, opts)); + } + } + if (parts.length === 0) return undefined; + return parts.length === 1 ? parts[0] : { and: parts }; +} + +/** A combinator's branch must itself be a filter object; a scalar there (`filter[or][0]=x`) + * names no field. */ +function asNode(sub: unknown, key: string): Record { + if (sub !== null && typeof sub === "object" && !Array.isArray(sub)) return sub as Record; + throw new FilterParseError("filter.invalid_value", `Each "${key}" branch must be a filter object.`, { field: key }); +} + +function ensureArray(v: unknown, key: string): unknown[] { + if (Array.isArray(v)) return v; + // qs gives `{ "0": …, "1": … }` for sparse or very large indexes; integer keys iterate + // in ascending order, so the branches keep their numeric order. + if (v && typeof v === "object") return Object.values(v); + // `field` (not `key`) because this is the cross-port `invalid_filter_value` envelope, + // which REQUIRES `field` naming the offending filter key — here the connector. + throw new FilterParseError("filter.invalid_value", `Expected array for "${key}".`, { field: key }); +} + +function leaf(field: string, rule: FilterFieldRule, op: string, operand: unknown, opts: ParseListQueryOpts): FilterLeaf { + if (!rule.ops.includes(op as FilterOp)) { + throw new FilterParseError("filter.unsupported_op", `Op "${op}" not supported for field "${field}".`, { field, op, allowed: rule.ops }); + } + const filterOp = op as FilterOp; + switch (filterOp) { + case "in": { + const maxInList = opts.maxInListSize ?? DEFAULT_MAX_IN_LIST; + const list = String(operand).split(",").map((v) => operandOf(v.trim(), rule, field, op, opts)); + if (list.length > maxInList) { + throw new FilterParseError("filter.in_too_large", `In-list size ${list.length} exceeds limit ${maxInList}.`, { field, limit: maxInList }); + } + return { field, op: filterOp, value: list }; + } + case "like": { + const s = String(operand); + if (s.startsWith("%") && !rule.leadingWildcard) { + throw new FilterParseError("filter.leading_wildcard_disallowed", `Leading wildcard not allowed for field "${field}".`, { field }); + } + // `like` is case-SENSITIVE SQL LIKE (ADR-0049): the pattern is kept verbatim. + return { field, op: filterOp, value: s }; + } + case "isNull": + // The operand is "is the value null?" — a boolean whatever the field's type. + return { field, op: filterOp, value: asBoolean(operand, field, op) }; + default: + return { field, op: filterOp, value: operandOf(operand, rule, field, op, opts) }; + } +} + +/** `expected` for a non-whole bound on an integer-valued field (`integer: true`). */ +const INTEGER_EXPECTED = "integer (a whole number)"; +const DURATION_IN_RANGE = "duration within the 64-bit microsecond range"; + +function invalidValue(field: string, op: string, s: string, expected: string, extra: Record = {}): FilterParseError { + const hint = typeof extra["hint"] === "string" ? ` Hint: ${extra["hint"]}.` : ""; + return new FilterParseError( + "filter.invalid_value", + `Field "${field}" op "${op}" requires ${expected}, got "${s}".${hint}`, + { field, op, expected, ...extra }, + ); +} + +/** + * Check a comparison operand against the field's rule and give it its neutral form: a + * number or boolean as that type; a decimal as its canonical text (never through a double, + * ADR-0019 Amendment 1); an instant timestamp in the stored UTC spelling (a zoneless or + * date-only bound read as UTC), any other timestamp with only a zoned bound rewritten to + * UTC; everything else as sent. Refusing a malformed operand here is what keeps SQLite from + * comparing it as text (a silent `[]`) and Postgres from failing the cast (a 500). + */ +function operandOf(value: unknown, rule: FilterFieldRule, field: string, op: string, opts: ParseListQueryOpts): FilterScalar { + const s = typeof value === "string" ? value : String(value); + const members = rule.enumValues ?? opts.enumValuesOf?.(field); + if (members !== undefined && !members.includes(s)) { + throw invalidValue(field, op, s, `one of: ${members.join(", ")}`, { allowed: [...members] }); + } + if (rule.format !== undefined) { + if (!matchesFormat(rule.format, s)) { + // `filter[dueAt][lt]=2026-10-06T00:00:00+00:00` sent unencoded arrives with a space + // where the `+` was; the answer names the fix. + const hint = rule.format === FIELD_SUBTYPE_TIMESTAMP && looksLikeUnencodedPlusOffset(s) ? { hint: PLUS_OFFSET_HINT } : {}; + throw invalidValue(field, op, s, FORMAT_EXPECTED[rule.format], hint); + } + } else if (rule.subType === "datetime" && !matchesAnyTemporal(s)) { + throw invalidValue(field, op, s, ANY_TEMPORAL_EXPECTED); + } + if (rule.format === FIELD_SUBTYPE_DECIMAL) return canonicalDecimal(s) as string; + if (rule.format === FIELD_SUBTYPE_DURATION) { + // A well-formed span past 64 bits of microseconds is no stored value on any database. + const micros = parseDurationLiteral(s) as bigint; + if (micros > DURATION_MICROS_MAX || micros < DURATION_MICROS_MIN) throw invalidValue(field, op, s, DURATION_IN_RANGE); + return s; + } + if (rule.format === FIELD_SUBTYPE_TIMESTAMP) return rule.instant === true ? utcIsoInstant(s) : utcIsoIfZoned(s); + switch (rule.subType) { + case "boolean": + return asBoolean(s, field, op); + case "number": { + // `Number("")` and `Number(" ")` are 0 — an empty bound is not the number zero. + const n = s.trim() === "" ? Number.NaN : Number(s); + if (!Number.isFinite(n)) { + throw new FilterParseError("filter.invalid_value", `Field "${field}" op "${op}" requires number, got "${s}".`, { field, op, expected: "number" }); + } + // field.int / field.long / field.currency: a fractional bound is not a value of the field. + if (rule.integer === true && !Number.isInteger(n)) throw invalidValue(field, op, s, INTEGER_EXPECTED); + return n; + } + default: + return s; + } +} + +function asBoolean(value: unknown, field: string, op: string): boolean { + const s = typeof value === "string" ? value : String(value); + if (s === "true" || s === "1") return true; + if (s === "false" || s === "0") return false; + throw new FilterParseError("filter.invalid_value", `Field "${field}" op "${op}" requires boolean, got "${s}".`, { field, op, expected: "boolean" }); +} + +function parseSort(spec: string, sortAllowlist: SortAllowlist): ListSort { + const colonIdx = spec.indexOf(":"); + const field = colonIdx === -1 ? spec : spec.slice(0, colonIdx); + if (!Object.hasOwn(sortAllowlist, field)) { + throw new FilterParseError( + "sort.unknown_field", + `Unknown sort field "${field}". The syntax is ${SORT_EXPECTED}.`, + { field, expected: SORT_EXPECTED, allowed: Object.keys(sortAllowlist) }, + ); + } + // `?sort=field` with no `:order` takes the field's DECLARED `@sortableDefaultOrder`. + // Applying it when `?sort` is absent entirely would give every endpoint an ordering it + // does not have: the declaration says which way a column runs, not which column to sort by. + const orderRaw = sortOrderSpec(sortAllowlist, field, colonIdx === -1 ? undefined : spec.slice(colonIdx + 1)); + const order = orderRaw.toLowerCase(); + if (order !== "asc" && order !== "desc") { + throw new FilterParseError( + "sort.invalid_order", + `Sort order must be asc|desc, got "${orderRaw}". The syntax is ${SORT_EXPECTED}.`, + { field, expected: SORT_EXPECTED, allowed: Object.keys(sortAllowlist) }, + ); + } + return { field, order }; +} + +/** + * Translate a SQL LIKE pattern into an equivalent SQLite GLOB pattern: + * `%` → `*`, `_` → `?`, and GLOB's own metacharacters (`*`, `?`, `[`) are + * wrapped in single-character classes so they match literally. `]` is only + * special inside a class, so it passes through. GLOB is case-sensitive, + * which is why the sqlite `like` branch uses it (ADR-0049) — SQLite's + * native LIKE folds ASCII case by default. + */ +export function likePatternToGlob(pattern: string): string { + let out = ""; + for (const ch of pattern) { + if (ch === "%") out += "*"; + else if (ch === "_") out += "?"; + else if (ch === "*") out += "[*]"; + else if (ch === "?") out += "[?]"; + else if (ch === "[") out += "[[]"; + else out += ch; + } + return out; +} diff --git a/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-read-only.ts b/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-read-only.ts index 93e97cffde..c06f5fdaec 100644 --- a/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-read-only.ts +++ b/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-read-only.ts @@ -1,7 +1,7 @@ import type { FastifyInstance, RouteShorthandOptions } from "fastify"; import { quoteIdent, type SqlDialect } from "../sql-dialect.js"; import { sql, eq, and, count } from "drizzle-orm"; -import qs from "qs"; +import { parseListQueryString } from "./list-query.js"; import { parseFilterParams, parsePageBound, pageLimit, parseReportPage, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, FilterParseError, type PageSize } from "./filter-parser.js"; import { ReportExportError, assertExportWithinCap, exportContentDisposition, exportWithCountError, isExportCountFlag, @@ -194,7 +194,7 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const url = req.raw.url ?? ""; const qIdx = url.indexOf("?"); const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = qs.parse(queryString) as Record; + const parsed = parseListQueryString(queryString); // A bound that is not an integer in range is a 400, not silently clamped. const reportPage = isReport ? parseReportPage(parsed, reportMaxRows) : undefined; const limitVal = reportPage?.limit ?? parsePageBound(parsed, "limit", RAW_VIEW_MAX_LIMIT) ?? RAW_VIEW_MAX_LIMIT; @@ -214,7 +214,7 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const url = req.raw.url ?? ""; const qIdx = url.indexOf("?"); const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = qs.parse(queryString) as Record; + const parsed = parseListQueryString(queryString); const withCount = isTruthyFlag(parsed["withCount"]); // Export mode: the selector is validated before any query runs, and the export cap governs. const format = exportSpec ? readExportFormat(parsed, exportSpec) : undefined; diff --git a/server/typescript/packages/runtime-ts/src/fastify/index.ts b/server/typescript/packages/runtime-ts/src/fastify/index.ts index 991fccab67..1ca92c64b9 100644 --- a/server/typescript/packages/runtime-ts/src/fastify/index.ts +++ b/server/typescript/packages/runtime-ts/src/fastify/index.ts @@ -20,14 +20,14 @@ import type { FastifyInstance } from "fastify"; import { withConstraintMapping } from "../constraint-errors.js"; import type { ZodTypeAny } from "zod"; import { validationErrorBody } from "../route-errors.js"; -import qs from "qs"; +import { parseListQuery, parseListQueryString, rawQueryOf, type FilterNode, type ListQuery } from "../drizzle-fastify/list-query.js"; import type { ObjectManager } from "../object-manager.js"; import type { Row } from "../persistence-driver.js"; import type { RouteShorthandOptions } from "fastify"; -import type { SortAllowlist } from "../drizzle-fastify/filter-allowlist.js"; -import { sortOrderSpec } from "../drizzle-fastify/filter-allowlist.js"; +import type { FilterAllowlist, SortAllowlist } from "../drizzle-fastify/filter-allowlist.js"; import { isTruthyFlag, contractErrorCode } from "../drizzle-fastify/util.js"; -import { parsePageBound, FilterParseError, SORT_EXPECTED } from "../drizzle-fastify/list-params.js"; +import { FilterParseError, pageLimit, type PageSize } from "../drizzle-fastify/list-params.js"; +import type { Filter } from "../query-builder.js"; import { withContractErrorHandler } from "../drizzle-fastify/route-error-handler.js"; // --------------------------------------------------------------------------- @@ -80,6 +80,20 @@ export interface CrudRoutesOptions { * is ignored (legacy back-compat: limit/offset only). */ sortAllowlist?: SortAllowlist; + /** + * Per-entity filter allowlist (`FilterAllowlist` from codegen). When set, the list + * reads `filter[...]`, `filter[or]` / `filter[and]` and `?search`, and refuses what the + * REST standard refuses (a bare field parameter, a leading `%`, a malformed value, a + * filter nested too deep) with the same bodies as the Drizzle mounts: both parse through + * `parseListQuery`. Absent, `?filter` and `?search` are ignored, as before. + */ + filterAllowlist?: FilterAllowlist; + /** + * The list page size (`api.pagination` in `.metaobjects/config.json`): a list with no + * `limit` returns `defaultLimit` rows, and a `limit` above `maxLimit` answers + * `400 { "error": "limit_too_large", "maxLimit": N }`. Absent: no default and no ceiling. + */ + pagination?: PageSize; } const ALL_VERBS: readonly CrudVerb[] = ["list", "get", "create", "update", "delete"]; @@ -122,70 +136,83 @@ function routeOpts(opts: SingleVerbOptions): RouteShorthandOptions { export function mountListRoute(opts: SingleVerbOptions): void { opts.fastify.get(opts.path, routeOpts(opts), async (req, reply) => { - // Re-parse the raw URL with qs so the top-level withCount flag and the - // sort=field:dir param are available regardless of Fastify's query parser. - const rawSearch = req.raw.url?.includes("?") - ? req.raw.url.slice(req.raw.url.indexOf("?") + 1) - : ""; - const parsed = qs.parse(rawSearch) as Record; + // Re-parse the raw URL so bracketed filter notation, the top-level withCount flag and + // the sort=field:dir param are available regardless of Fastify's query parser. + const parsed = parseListQueryString(rawQueryOf(req.raw.url)); const withCount = isTruthyFlag(parsed["withCount"]); - const readOpts: { limit?: number; offset?: number; orderBy?: [string, "asc" | "desc"] } = {}; + const om = await opts.om(); + let query: ListQuery; + let limit: number | undefined; try { - const limit = parsePageBound(parsed, "limit"); - const offset = parsePageBound(parsed, "offset"); - if (limit !== undefined) readOpts.limit = limit; - if (offset !== undefined) readOpts.offset = offset; + query = opts.filterAllowlist !== undefined + ? parseListQuery({ + query: opts.sortAllowlist !== undefined ? parsed : withoutSort(parsed), + allowlist: opts.filterAllowlist, + sortAllowlist: opts.sortAllowlist ?? {}, + isField: (name) => om.fieldNames(opts.entity).includes(name), + }) + : parseListQuery({ query: pageAndSortOnly(parsed, opts.sortAllowlist !== undefined), allowlist: {}, sortAllowlist: opts.sortAllowlist ?? {} }); + limit = pageLimit(query.limit, opts.pagination); } catch (err) { - if (err instanceof FilterParseError) return reply.code(400).send({ error: err.code, ...(err.details ?? {}) }); + if (err instanceof FilterParseError) return reply.code(400).send({ error: contractErrorCode(err.code), ...(err.details ?? {}) }); throw err; } - // Sort allowlist gate (cross-port REST contract). Only enforced when a - // sortAllowlist is configured; absent → ?sort is ignored (back-compat). - if (opts.sortAllowlist && typeof parsed["sort"] === "string") { - const sortParse = parseSort(parsed["sort"], opts.sortAllowlist); - if (sortParse.error) { - // `field` is REQUIRED on the invalid_sort envelope cross-port (F20 ruling) — - // it names the offending sort field instead of making the caller guess. - return reply.code(400).send({ - error: contractErrorCode(sortParse.error), - field: sortParse.field, - expected: SORT_EXPECTED, - allowed: Object.keys(opts.sortAllowlist), - }); - } - if (sortParse.orderBy) readOpts.orderBy = sortParse.orderBy; + const readOpts: { limit?: number; offset?: number; orderBy?: [string, "asc" | "desc"] | [string, "asc" | "desc"][] } = {}; + if (limit !== undefined) readOpts.limit = limit; + if (query.offset !== undefined) readOpts.offset = query.offset; + // No `?sort`: the key, ascending, so a page holds the same rows on every engine, as the + // Drizzle mounts order by `id`. + if (query.sort !== undefined) readOpts.orderBy = [query.sort.field, query.sort.order]; + else { + const key = om.keyFields(opts.entity); + if (key.length === 1) readOpts.orderBy = [key[0] as string, "asc"]; + else if (key.length > 1) readOpts.orderBy = key.map((f): [string, "asc" | "desc"] => [f, "asc"]); } - const om = await opts.om(); - const rows = await om.findMany(opts.entity, undefined, readOpts); + const filter = listFilter(query); + const rows = await om.findMany(opts.entity, filter, readOpts); if (!withCount) return rows; - // total is the UNPAGINATED count (no limit/offset). - const total = await om.count(opts.entity); + // total is the UNPAGINATED count of the same filter (no limit/offset). + const total = await om.count(opts.entity, filter); return { rows, total }; }); } /** - * Validate a `sort=field:dir` spec against the allowlist. Mirrors the - * drizzle-fastify filter-parser's sort semantics + internal error codes - * (`sort.unknown_field` / `sort.invalid_order`) so both mounts emit the same - * `invalid_sort` envelope at the HTTP boundary. + * With no filter allowlist the mount reads only the page and (when a sort allowlist is set) + * the sort, as it always has: `?filter` and `?search` are ignored and no bare parameter is + * refused, because there is no list of filterable fields to check them against. */ -function parseSort( - spec: string, - sortAllowlist: SortAllowlist, -): { orderBy?: [string, "asc" | "desc"]; error?: string; field?: string } { - const [field, orderRaw] = spec.split(":"); - if (!field || !sortAllowlist[field]) return { error: "sort.unknown_field", field: field ?? "" }; - // Precedence (caller order > declared @sortableDefaultOrder > asc) comes from the - // shared sortOrderSpec, so this mount cannot answer one declaration differently from - // the drizzle mount again. Validation stays here because this mount reports a bad - // order as an error CODE rather than a thrown FilterParseError. - const order = sortOrderSpec(sortAllowlist, field, orderRaw).toLowerCase(); - if (order !== "asc" && order !== "desc") return { error: "sort.invalid_order", field }; - return { orderBy: [field, order] }; +function pageAndSortOnly(parsed: Record, withSort: boolean): Record { + const out: Record = {}; + for (const k of ["limit", "offset", ...(withSort ? ["sort"] : [])]) if (k in parsed) out[k] = parsed[k]; + return out; +} + +function withoutSort(parsed: Record): Record { + const { sort: _sort, ...rest } = parsed; + return rest; +} + +/** The parsed filter tree and search as one ObjectManager filter (the AND of the two). */ +function listFilter(query: ListQuery): Filter | undefined { + const parts: Filter[] = []; + if (query.filter !== undefined) parts.push(toOmFilter(query.filter)); + if (query.search !== undefined) { + const pattern = `%${query.search.term}%`; + const branches = query.search.fields.map((f): Filter => ({ [f]: { $ilike: pattern } })); + parts.push(branches.length === 1 ? (branches[0] as Filter) : { $or: branches }); + } + if (parts.length === 0) return undefined; + return parts.length === 1 ? parts[0] : { $and: parts }; +} + +function toOmFilter(node: FilterNode): Filter { + if ("and" in node) return { $and: node.and.map(toOmFilter) }; + if ("or" in node) return { $or: node.or.map(toOmFilter) }; + return { [node.field]: { [`$${node.op}`]: node.value } } as Filter; } export function mountGetRoute(opts: SingleVerbOptions): void { diff --git a/server/typescript/packages/runtime-ts/src/hono/index.ts b/server/typescript/packages/runtime-ts/src/hono/index.ts index d81346a75e..77bb958ea7 100644 --- a/server/typescript/packages/runtime-ts/src/hono/index.ts +++ b/server/typescript/packages/runtime-ts/src/hono/index.ts @@ -26,7 +26,7 @@ import { classifyConstraintError, RedactedDatabaseError, logAndRedact } from ".. import type { ZodTypeAny } from "zod"; import { validationErrorBody } from "../route-errors.js"; import { eq, count, and } from "drizzle-orm"; -import qs from "qs"; +import { parseListQueryString } from "../drizzle-fastify/list-query.js"; import { contractErrorCode } from "../drizzle-fastify/util.js"; import { parseFilterParams, @@ -151,7 +151,7 @@ export function mountCrudRoutes(opts: CrudRoutesOptions): void { type VerbOptions = Omit; // --------------------------------------------------------------------------- -// Hono-flavored qs.parse — analogue of Fastify's qs.parse(req.raw.url ...). +// Hono-flavored query parse — analogue of the Fastify mounts' parseListQueryString(req.raw.url ...). // // Hono exposes the raw URL via c.req.url; we strip the prefix and feed the // raw query string to qs so the bracketed filter notation (filter[a][eq]=...) @@ -163,7 +163,7 @@ export function parseHonoFilterParams(c: Context): Record { const url = c.req.url; const qIdx = url.indexOf("?"); const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - return qs.parse(queryString) as Record; + return parseListQueryString(queryString); } /** READ source: the replica view when the entity is write-through, else the table. diff --git a/server/typescript/packages/runtime-ts/src/hono/mount-read-only.ts b/server/typescript/packages/runtime-ts/src/hono/mount-read-only.ts index 63519061a8..527e462c1f 100644 --- a/server/typescript/packages/runtime-ts/src/hono/mount-read-only.ts +++ b/server/typescript/packages/runtime-ts/src/hono/mount-read-only.ts @@ -5,7 +5,7 @@ import { quoteIdent, type SqlDialect } from "../sql-dialect.js"; import type { Hono } from "hono"; import { sql, eq, and, count } from "drizzle-orm"; -import qs from "qs"; +import { parseListQueryString } from "../drizzle-fastify/list-query.js"; import { parseFilterParams, parsePageBound, pageLimit, parseReportPage, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, FilterParseError, type PageSize } from "../drizzle-fastify/filter-parser.js"; import { ReportExportError, assertExportWithinCap, exportContentDisposition, exportWithCountError, isExportCountFlag, @@ -164,7 +164,7 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const url = c.req.url; const qIdx = url.indexOf("?"); const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = qs.parse(queryString) as Record; + const parsed = parseListQueryString(queryString); // A bound that is not an integer in range is a 400, not silently clamped. const reportPage = isReport ? parseReportPage(parsed, reportMaxRows) : undefined; const limitVal = reportPage?.limit ?? parsePageBound(parsed, "limit", RAW_VIEW_MAX_LIMIT) ?? RAW_VIEW_MAX_LIMIT; @@ -184,7 +184,7 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const url = c.req.url; const qIdx = url.indexOf("?"); const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = qs.parse(queryString) as Record; + const parsed = parseListQueryString(queryString); const withCount = isTruthyFlag(parsed["withCount"]); const format = exportSpec ? readExportFormat(parsed, exportSpec) : undefined; if (format !== undefined && format !== "json" && isExportCountFlag(parsed["withCount"])) throw exportWithCountError(); diff --git a/server/typescript/packages/runtime-ts/src/index.ts b/server/typescript/packages/runtime-ts/src/index.ts index e10610d004..19dc0b9eb7 100644 --- a/server/typescript/packages/runtime-ts/src/index.ts +++ b/server/typescript/packages/runtime-ts/src/index.ts @@ -53,3 +53,13 @@ export { // UI-1 — metadata API contract for the browser read-model. export { META_ROUTE_PATH, META_CONTENT_TYPE, metaJson } from "./meta-endpoint.js"; + +// The REST standard's list handling, parsed into a port-neutral form before any query library +// sees it (fixtures/list-query-conformance/): every mount and a hand-written transport share it. +export { + parseListQuery, parseListQueryString, rawQueryOf, searchFields, likePatternToGlob, + DEFAULT_MAX_IN_LIST, DEFAULT_MAX_NESTING, + type FilterLeaf, type FilterNode, type FilterScalar, type ListQuery, type ListSearch, type ListSort, type ParseListQueryOpts, +} from "./drizzle-fastify/list-query.js"; +export { FilterParseError, parsePageBound, pageLimit, type PageSize } from "./drizzle-fastify/list-params.js"; +export type { FilterAllowlist, FilterFieldRule, FilterSubType, FilterValueFormat, SortAllowlist, SortFieldRule } from "./drizzle-fastify/filter-allowlist.js"; diff --git a/server/typescript/packages/runtime-ts/src/object-manager.ts b/server/typescript/packages/runtime-ts/src/object-manager.ts index ed3249b63a..6e7f7d974b 100644 --- a/server/typescript/packages/runtime-ts/src/object-manager.ts +++ b/server/typescript/packages/runtime-ts/src/object-manager.ts @@ -155,6 +155,21 @@ export class ObjectManager { return driver.count(buildCountSpec(entity, scoped, this.columnNamingStrategy, driver.dialect)); } + /** + * The primary-key fields of an object, in declared order; empty for a report (FR-044), + * which has no identity. A REST list with no `?sort` orders by these, so its pages are + * stable on every engine. + */ + keyFields(entityName: string): readonly string[] { + const entity = this.requireObject(entityName); + return entity.subType === OBJECT_SUBTYPE_REPORT ? [] : resolvePkFields(entity); + } + + /** The fields of an object (effective: inherited ones included), as `findMany` returns them. */ + fieldNames(entityName: string): readonly string[] { + return this.requireEntity(entityName).children().filter((c) => c.type === TYPE_FIELD).map((c) => c.name); + } + async load(refString: string): Promise { const { entity: entityName, pkValues } = decodeRef(refString); const entity = this.requireIdentified(entityName, "load"); diff --git a/server/typescript/packages/runtime-ts/src/persistence-driver.ts b/server/typescript/packages/runtime-ts/src/persistence-driver.ts index 4a8bbf1bd9..ad8ef08dc0 100644 --- a/server/typescript/packages/runtime-ts/src/persistence-driver.ts +++ b/server/typescript/packages/runtime-ts/src/persistence-driver.ts @@ -11,6 +11,9 @@ export type WhereClause = | { kind: "gt" | "gte" | "lt" | "lte"; column: string; value: number | string } | { kind: "in"; column: string; values: PrimitiveValue[] } | { kind: "like"; column: string; pattern: string } + /** A case-INSENSITIVE LIKE (`%`/`_` wildcards). Not a wire operator: a REST list's + * `?search` compiles to an OR of these over its text fields. */ + | { kind: "ilike"; column: string; pattern: string } | { kind: "isNull"; column: string; not: boolean } | { kind: "and"; clauses: WhereClause[] } | { kind: "or"; clauses: WhereClause[] }; diff --git a/server/typescript/packages/runtime-ts/src/query-builder.ts b/server/typescript/packages/runtime-ts/src/query-builder.ts index d05d6239de..7d412183d5 100644 --- a/server/typescript/packages/runtime-ts/src/query-builder.ts +++ b/server/typescript/packages/runtime-ts/src/query-builder.ts @@ -25,7 +25,7 @@ export function tableTarget(entity: MetaData): TableTarget { return schema === undefined ? { table: resolveTableName(entity) } : { table: resolveTableName(entity), schema }; } -export type Filter = Record | { $and: Filter[] }; +export type Filter = Record | { $and: Filter[] } | { $or: Filter[] }; export type FilterValue = | string | number | boolean | null @@ -38,6 +38,8 @@ export type FilterValue = $lt?: string | number; $lte?: string | number; $like?: string; + /** Case-INSENSITIVE LIKE (`%`/`_` wildcards), as a REST list's `?search` matches. */ + $ilike?: string; $in?: (string | number)[]; $isNull?: boolean; }; @@ -113,6 +115,15 @@ export function compileFilter( if (clauses.length === 0) return null; return clauses.length === 1 ? clauses[0]! : { kind: "and", clauses }; } + if ("$or" in filter && Array.isArray(filter.$or)) { + // An OR with no branch matches nothing, but `{ $or: [] }` reads as "no condition" the way + // `{ $and: [] }` does, so it is treated as one (null — match all) rather than as `false`. + const clauses = (filter.$or as Filter[]) + .map((f) => compileFilter(entity, f, strategy, dialect)) + .filter((c): c is WhereClause => c !== null); + if (clauses.length === 0) return null; + return clauses.length === 1 ? clauses[0]! : { kind: "or", clauses }; + } const entries = Object.entries(filter); if (entries.length === 0) return null; if (entries.length === 1) { @@ -162,6 +173,7 @@ function compileEntry( if ("$lt" in op && op.$lt !== undefined) return { kind: "lt", column, value: enc(op.$lt) }; if ("$lte" in op && op.$lte !== undefined) return { kind: "lte", column, value: enc(op.$lte) }; if ("$like" in op && op.$like !== undefined) return { kind: "like", column, pattern: op.$like }; + if ("$ilike" in op && op.$ilike !== undefined) return { kind: "ilike", column, pattern: op.$ilike }; if ("$in" in op && op.$in !== undefined) return { kind: "in", column, values: op.$in.map(enc) }; if ("$isNull" in op && op.$isNull !== undefined) { return { kind: "isNull", column, not: !op.$isNull }; diff --git a/server/typescript/packages/runtime-ts/src/route-errors.ts b/server/typescript/packages/runtime-ts/src/route-errors.ts index 0a1a0e187c..b01d7a9f45 100644 --- a/server/typescript/packages/runtime-ts/src/route-errors.ts +++ b/server/typescript/packages/runtime-ts/src/route-errors.ts @@ -18,9 +18,9 @@ * mount folded it into a Zod `validation` error. Both now answer * `400 { "error": "invalid_json" }`. * - * The api-contract corpus pins neither response (5xx is implementation-defined there, and - * no scenario sends a malformed body), so both are TS-helper extensions — documented in - * docs/features/api-contract.md, "TS-only error responses". + * Both are in the REST contract (docs/features/api-contract.md, "Error responses for a bad + * request or a failed write"); `api-contract-conformance/list-query/invalid-json` sends a + * malformed body. A 5xx body is otherwise implementation-defined there. */ import { RedactedDatabaseError, logAndRedact } from "./constraint-errors.js"; diff --git a/server/typescript/packages/runtime-ts/test/bodyless-empty-json.test.ts b/server/typescript/packages/runtime-ts/test/bodyless-empty-json.test.ts index 13c1b626ba..68b3047d42 100644 --- a/server/typescript/packages/runtime-ts/test/bodyless-empty-json.test.ts +++ b/server/typescript/packages/runtime-ts/test/bodyless-empty-json.test.ts @@ -59,7 +59,7 @@ beforeAll(async () => { const row = { id: 1, displayName: "Ann" }; const om = { - findMany: async () => [row], findById: async () => row, create: async () => row, + keyFields: () => ["id"], findMany: async () => [row], findById: async () => row, create: async () => row, update: async () => row, delete: async () => 1, count: async () => 1, } as unknown as ObjectManager; omFastify = Fastify(); diff --git a/server/typescript/packages/runtime-ts/test/drizzle-fastify/list-query-inherited-names.test.ts b/server/typescript/packages/runtime-ts/test/drizzle-fastify/list-query-inherited-names.test.ts new file mode 100644 index 0000000000..84ddbc2fbe --- /dev/null +++ b/server/typescript/packages/runtime-ts/test/drizzle-fastify/list-query-inherited-names.test.ts @@ -0,0 +1,49 @@ +// A name every object inherits (`constructor`, `toString`, `__proto__`) is not a field. The +// allowlists are plain objects, so a truthiness lookup answered "allowed" for them and the +// mounts then ordered or filtered by a column that does not exist. The shared contract says +// an unknown sort field is `400 invalid_sort` and an unknown filter field is +// `400 invalid_filter_field`, whatever the name. + +import { describe, test, expect } from "bun:test"; +import { parseListQuery, parseListQueryString } from "../../src/drizzle-fastify/list-query.js"; +import { FilterParseError } from "../../src/drizzle-fastify/filter-parser.js"; +import { sortOrderSpec, type FilterAllowlist, type SortAllowlist } from "../../src/drizzle-fastify/filter-allowlist.js"; +import { contractErrorCode } from "../../src/drizzle-fastify/util.js"; + +const allowlist = { title: { type: "string", ops: ["eq"] } } as unknown as FilterAllowlist; +const sortAllowlist: SortAllowlist = { title: { defaultOrder: "desc" } }; + +function failure(fn: () => unknown): FilterParseError { + try { + fn(); + } catch (err) { + if (err instanceof FilterParseError) return err; + throw err; + } + throw new Error("expected a FilterParseError"); +} + +describe("inherited Object property names are not allowlisted fields", () => { + for (const name of ["constructor", "toString", "__proto__"]) { + test(`?sort=${name} is invalid_sort`, () => { + const err = failure(() => parseListQuery({ query: { sort: name }, allowlist, sortAllowlist })); + expect(contractErrorCode(err.code)).toBe("invalid_sort"); + expect(err.details?.field).toBe(name); + }); + + test(`filter[${name}] on a hand-built query is an unknown filter field`, () => { + const filter = JSON.parse(`{ "${name}": { "eq": "x" } }`) as Record; + const err = failure(() => parseListQuery({ query: { filter }, allowlist, sortAllowlist })); + expect(contractErrorCode(err.code)).toBe("invalid_filter_field"); + }); + + test(`a ${name} order lookup falls back to asc`, () => { + expect(sortOrderSpec(sortAllowlist, name, undefined)).toBe("asc"); + }); + } + + test("a declared field still parses, with its declared default order", () => { + const q = parseListQuery({ query: parseListQueryString("sort=title"), allowlist, sortAllowlist }); + expect(q.sort).toEqual({ field: "title", order: "desc" }); + }); +}); diff --git a/server/typescript/packages/runtime-ts/test/fastify/mount-list-parity.test.ts b/server/typescript/packages/runtime-ts/test/fastify/mount-list-parity.test.ts new file mode 100644 index 0000000000..af7bd55b50 --- /dev/null +++ b/server/typescript/packages/runtime-ts/test/fastify/mount-list-parity.test.ts @@ -0,0 +1,180 @@ +// The ObjectManager Fastify mount answers a list query the way the Drizzle and Hono mounts do +// (plan R0): `filter[or]` / `filter[and]`, `?search` that ignores case, a `like` that does not, +// and the same refusals with the same bodies. A real ObjectManager over two drivers (the +// in-memory driver and Kysely on libSQL), no fakes: the parse is shared (`parseListQuery`), so +// what this pins is the OM half, which turns the parsed tree into the ObjectManager's `Filter`. +// +// The expected answers are the ones the generated (Drizzle) routes give for the same model and +// seed in fixtures/api-contract-conformance/list-query/: the rows of this seed whose name +// matches, computed by hand below. + +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import Fastify, { type FastifyInstance } from "fastify"; +import { Kysely, sql } from "kysely"; +import { LibsqlDialect } from "@libsql/kysely-libsql"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { z } from "zod"; +import { InMemoryStringSource, MetaDataLoader, type MetaRoot } from "@metaobjectsdev/metadata"; +import { ObjectManager } from "../../src/object-manager.js"; +import { inMemoryDriver, kyselyDriver } from "../../src/drivers/index.js"; +import type { PersistenceDriver, Row } from "../../src/persistence-driver.js"; +import { mountCrudRoutes } from "../../src/fastify/index.js"; +import type { FilterAllowlist, SortAllowlist } from "../../src/drizzle-fastify/filter-allowlist.js"; + +const META = JSON.stringify({ + "metadata.root": { + package: "acme::stockroom", + children: [{ + "object.entity": { + name: "Part", + children: [ + { "source.rdb": { "@table": "parts" } }, + { "field.long": { name: "id", "@filterable": true } }, + { "field.string": { name: "name", "@filterable": true } }, + { "field.enum": { name: "category", "@values": ["tool", "part", "kit"], "@filterable": true } }, + { "field.int": { name: "stock", "@filterable": true } }, + { "field.string": { name: "notes" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + ], + }, + }], + }, +}); + +// The allowlists codegen emits for this model (`FilterAllowlist` / `SortAllowlist`). +const FILTERS = { + id: { ops: ["eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"], subType: "number", leadingWildcard: false, integer: true }, + name: { ops: ["eq", "ne", "in", "like", "isNull"], subType: "string", leadingWildcard: false }, + category: { ops: ["eq", "ne", "in", "like", "isNull"], subType: "string", leadingWildcard: false, enumValues: ["tool", "part", "kit"] }, + stock: { ops: ["eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"], subType: "number", leadingWildcard: false, integer: true }, +} as const satisfies FilterAllowlist; +const SORTS = { id: {}, name: {}, category: {}, stock: {} } as const satisfies SortAllowlist; + +const NAMES: Record = { 1: "Pump Housing", 2: "pump seal", 3: "Bilge PUMP", 4: "Sump Pump", 5: "Anvil", 6: "Bracket" }; +const ROWS: Row[] = Object.entries(NAMES).map(([id, name]) => { + const n = Number(id); + return { id: n, name, category: ["tool", "part", "kit"][n % 3]!, stock: n % 4, notes: `bin ${n}` }; +}); + +interface DriverCase { + name: string; + build: () => Promise<{ driver: PersistenceDriver; teardown: () => Promise }>; +} + +const DRIVERS: DriverCase[] = [ + { + name: "inMemoryDriver", + build: async () => ({ + driver: inMemoryDriver({ seed: { parts: ROWS.map((r) => ({ ...r })) }, pkFields: { parts: ["id"] } }), + teardown: async () => {}, + }), + }, + { + name: "kyselyDriver/libsql-sqlite", + build: async () => { + const dir = mkdtempSync(join(process.env["DEV_SCRATCH"] ?? tmpdir(), "om-list-parity-")); + const db = new Kysely>({ dialect: new LibsqlDialect({ url: `file:${join(dir, "t.db")}` }) }); + await sql.raw(`CREATE TABLE parts (id INTEGER PRIMARY KEY, name TEXT NOT NULL, category TEXT NOT NULL, stock INTEGER NOT NULL, notes TEXT)`).execute(db); + await db.insertInto("parts").values(ROWS).execute(); + return { + driver: kyselyDriver({ db, dialect: "sqlite" }), + teardown: async () => { + await db.destroy(); + rmSync(dir, { recursive: true, force: true }); + }, + }; + }, + }, +]; + +async function load(): Promise { + const result = await new MetaDataLoader().load([new InMemoryStringSource(META)]); + expect(result.errors).toEqual([]); + return result.root as MetaRoot; +} + +for (const d of DRIVERS) { + describe(`ObjectManager Fastify list mount — ${d.name}`, () => { + let app: FastifyInstance; + let bare: FastifyInstance; + let teardown: () => Promise = async () => {}; + + beforeAll(async () => { + const built = await d.build(); + teardown = built.teardown; + const om = new ObjectManager({ metadata: await load(), driver: built.driver }); + const base = { path: "/parts", entity: "Part", insertSchema: z.object({}), updateSchema: z.object({}), om: async () => om, expose: ["list"] as const }; + app = Fastify(); + mountCrudRoutes({ fastify: app, ...base, filterAllowlist: FILTERS, sortAllowlist: SORTS }); + await app.ready(); + bare = Fastify(); + mountCrudRoutes({ fastify: bare, ...base }); + await bare.ready(); + }); + + afterAll(async () => { + await app.close(); + await bare.close(); + await teardown(); + }); + + async function get(url: string, on: FastifyInstance = app): Promise<{ status: number; body: unknown }> { + const res = await on.inject({ method: "GET", url }); + return { status: res.statusCode, body: res.json() }; + } + const ids = (body: unknown) => (body as Array<{ id: number }>).map((r) => r.id); + + test("search ignores case and matches anywhere in the text", async () => { + const r = await get("/parts?search=pump&sort=id:asc"); + expect(r.status).toBe(200); + expect(ids(r.body)).toEqual([1, 2, 3, 4]); + }); + + test("like is case-sensitive (ADR-0049)", async () => { + expect(ids((await get("/parts?filter[name][like]=Pump%25&sort=id:asc")).body)).toEqual([1]); + expect(ids((await get("/parts?filter[name][like]=pump%25&sort=id:asc")).body)).toEqual([2]); + }); + + test("filter[or] matches any branch, ANDed with a sibling condition", async () => { + const r = await get("/parts?filter[stock][gte]=1&filter[or][0][id][eq]=4&filter[or][1][category][eq]=tool&sort=id:asc"); + expect(r.status).toBe(200); + // stock >= 1 AND (id = 4 OR category = tool): 3 and 6 are tools in stock; 4 has stock 0. + expect(ids(r.body)).toEqual([3, 6]); + }); + + test("search and filter are both applied, and withCount counts what they match", async () => { + const r = await get("/parts?search=PUMP&filter[category][eq]=part&withCount=1&limit=1"); + expect(r.status).toBe(200); + expect(r.body).toMatchObject({ total: 2 }); + expect((r.body as { rows: unknown[] }).rows).toHaveLength(1); + }); + + test("with no sort the rows come back in key order", async () => { + expect(ids((await get("/parts")).body)).toEqual([1, 2, 3, 4, 5, 6]); + }); + + test("a bare field parameter is refused, not ignored", async () => { + expect(await get("/parts?name=Anvil")).toEqual({ status: 400, body: { error: "filter.bare_field", field: "name", expected: "filter[name][eq]=Anvil" } }); + const notFilterable = await get("/parts?notes=x"); + expect(notFilterable.status).toBe(400); + expect(notFilterable.body).toMatchObject({ error: "filter.bare_field", field: "notes", filterable: false }); + }); + + test("the parse refusals answer the Drizzle mount's bodies", async () => { + expect(await get("/parts?filter[name][like]=%25pump")).toEqual({ status: 400, body: { error: "filter.leading_wildcard_disallowed", field: "name" } }); + expect(await get("/parts?filter[or][0][or][0][or][0][or][0][or][0][or][0][id][eq]=1")).toEqual({ status: 400, body: { error: "filter.nesting_too_deep", limit: 5 } }); + expect(await get("/parts?filter[stock][gt]=2.5")).toEqual({ status: 400, body: { error: "invalid_filter_value", field: "stock", op: "gt", expected: "integer (a whole number)" } }); + expect((await get("/parts?filter[nope][eq]=1")).body).toMatchObject({ error: "invalid_filter_field", field: "nope" }); + expect(await get("/parts?limit=abc")).toEqual({ + status: 400, + body: { error: "pagination.invalid_value", param: "limit", value: "abc", expected: "a non-negative integer (0 or more)" }, + }); + }); + + test("without a filter allowlist, filter and search are ignored as before", async () => { + expect(ids((await get("/parts?filter[id][eq]=2&search=zzz&sort=id:asc", bare)).body)).toEqual([1, 2, 3, 4, 5, 6]); + }); + }); +} diff --git a/server/typescript/packages/runtime-ts/test/fastify/mount-list.test.ts b/server/typescript/packages/runtime-ts/test/fastify/mount-list.test.ts index cbc48d85e9..abc98d68de 100644 --- a/server/typescript/packages/runtime-ts/test/fastify/mount-list.test.ts +++ b/server/typescript/packages/runtime-ts/test/fastify/mount-list.test.ts @@ -3,7 +3,7 @@ import Fastify, { type FastifyInstance } from "fastify"; import { z } from "zod"; import { mountCrudRoutes } from "../../src/fastify/index.js"; import type { ObjectManager } from "../../src/object-manager.js"; -import type { SortAllowlist } from "../../src/drizzle-fastify/filter-allowlist.js"; +import type { FilterAllowlist, SortAllowlist } from "../../src/drizzle-fastify/filter-allowlist.js"; // In-memory fake ObjectManager — exercises only the surface the plain fastify // mount calls (findMany + count). Keeps the test off a real DB so it stays a @@ -21,6 +21,8 @@ const SEED: Author[] = [ function fakeOm(): ObjectManager { return { + keyFields: () => ["id"], + fieldNames: () => ["id", "name", "createdAt"], async findMany( _entity: string, _filter: unknown, @@ -159,3 +161,25 @@ describe("plain fastify mount — page bounds and the sort hint", () => { }); }); }); + +describe("plain fastify mount — filterAllowlist without sortAllowlist", () => { + test("?sort is ignored (key order), as with no filterAllowlist", async () => { + const filtered = Fastify(); + const om = fakeOm(); + const filterAllowlist: FilterAllowlist = { name: { ops: ["eq"], subType: "string", leadingWildcard: false } }; + mountCrudRoutes({ + fastify: filtered, + path: "/authors", + entity: "Author", + insertSchema: InsertSchema, + updateSchema: UpdateSchema, + om: async () => om, + filterAllowlist, + }); + await filtered.ready(); + const r = await filtered.inject({ method: "GET", url: "/authors?sort=name:desc" }); + expect(r.statusCode).toBe(200); + expect((JSON.parse(r.body) as Author[]).map((a) => a.name)).toEqual(["Alice", "Bob", "Carol"]); + await filtered.close(); + }); +}); diff --git a/server/typescript/packages/runtime-ts/test/fastify/route-errors.test.ts b/server/typescript/packages/runtime-ts/test/fastify/route-errors.test.ts index 2c5e8c3bcd..8fdb8a3206 100644 --- a/server/typescript/packages/runtime-ts/test/fastify/route-errors.test.ts +++ b/server/typescript/packages/runtime-ts/test/fastify/route-errors.test.ts @@ -14,7 +14,7 @@ const DRIVER_TEXT = 'Failed query: select "id", "display_name" from "readers"\np // Every method the mount calls fails the way a driver does when the schema drifted. function brokenOm(): ObjectManager { const fail = async () => { throw new Error(DRIVER_TEXT); }; - return { findMany: fail, findById: fail, create: fail, update: fail, delete: fail, count: fail } as unknown as ObjectManager; + return { keyFields: () => ["id"], findMany: fail, findById: fail, create: fail, update: fail, delete: fail, count: fail } as unknown as ObjectManager; } const InsertSchema = z.object({ displayName: z.string() }); diff --git a/server/typescript/packages/sdk/src/agent-context/scaffold.ts b/server/typescript/packages/sdk/src/agent-context/scaffold.ts index 5d24a6bccb..2a5c5eff14 100644 --- a/server/typescript/packages/sdk/src/agent-context/scaffold.ts +++ b/server/typescript/packages/sdk/src/agent-context/scaffold.ts @@ -126,6 +126,12 @@ export function planScaffold(opts: { writes.push({ path: f.path, contents: f.contents }); continue; } + // The file already holds exactly these bytes: nothing to write, and the hash we record + // is the true one whatever wrote it. Rewriting identical bytes only churns timestamps. + if (current === f.contents) { + files[f.path] = hashContents(f.contents); + continue; + } const priorHash = prior?.files[f.path]; if (priorHash !== undefined && hashContents(current) === priorHash) { files[f.path] = hashContents(f.contents); diff --git a/server/typescript/packages/sdk/test/agent-context/scaffold.test.ts b/server/typescript/packages/sdk/test/agent-context/scaffold.test.ts index 4ae5e2bdff..a125c7a98d 100644 --- a/server/typescript/packages/sdk/test/agent-context/scaffold.test.ts +++ b/server/typescript/packages/sdk/test/agent-context/scaffold.test.ts @@ -37,6 +37,21 @@ describe("planScaffold", () => { expect(d.conflicts).toEqual([]); }); + test("a file already holding the assembled bytes is recorded, never rewritten", () => { + const prior: Manifest = { version: 1, servers: ["typescript"], clients: ["react"], files: { ".metaobjects/AGENTS.md": hashContents("always-on v2") } }; + const d = planScaffold({ stack, assembled: [files[0]!], prior, readCurrent: () => "always-on v2", generatedBy: "0.9.0" }); + expect(d.writes).toEqual([]); + expect(d.conflicts).toEqual([]); + expect(d.manifest.files[".metaobjects/AGENTS.md"]).toBe(hashContents("always-on v2")); + }); + + test("an untracked file that already holds the assembled bytes is no conflict", () => { + const d = planScaffold({ stack, assembled: [files[0]!], prior: undefined, readCurrent: () => "always-on v2", generatedBy: "0.9.0" }); + expect(d.conflicts).toEqual([]); + expect(d.writes).toEqual([]); + expect(d.manifest.files[".metaobjects/AGENTS.md"]).toBe(hashContents("always-on v2")); + }); + test("hand-edited file (on-disk differs from prior hash) → .new conflict + keep original", () => { const prior: Manifest = { version: 1, servers: ["typescript"], clients: ["react"], files: { ".metaobjects/AGENTS.md": hashContents("always-on v1") } }; const d = planScaffold({ diff --git a/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts b/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts index 026d00f5be..b5a79e86e0 100644 --- a/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts +++ b/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts @@ -590,16 +590,16 @@ function buildCompositeKeyCallback( return code`${primaryKeySym}({ columns: [${columnRefs}] })`; } -/** Build a JS-style object literal string (not JSON.stringify which uses quoted keys). - * Array values get `as const` appended so Drizzle's text(...,{ enum: [...] }) - * narrows the inferred column type to a literal union instead of bare `string`. */ -function inlineObjectLiteral(obj: Record): string { +/** Build a JS-style object literal string (not JSON.stringify, which quotes every key): + * `{ length: 200 }`, not `{ "length": 200 }`. A key that is not a bare identifier keeps + * its quotes. Array values get `as const` appended so Drizzle's text(...,{ enum: [...] }) + * narrows the inferred column type to a literal union instead of bare `string`. Shared by + * the table template and the existing-view declaration (`view-decl.ts`). */ +export function inlineObjectLiteral(obj: Record): string { const entries = Object.entries(obj).map(([k, v]) => { + const name = /^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k); const lit = JSON.stringify(v); - if (Array.isArray(v)) { - return `${k}: ${lit} as const`; - } - return `${k}: ${lit}`; + return Array.isArray(v) ? `${name}: ${lit} as const` : `${name}: ${lit}`; }); return `{ ${entries.join(", ")} }`; } diff --git a/server/typescript/packages/test-generators/src/templates/filter-allowlist.ts b/server/typescript/packages/test-generators/src/templates/filter-allowlist.ts index 5d1527373a..b8ef1b2bcd 100644 --- a/server/typescript/packages/test-generators/src/templates/filter-allowlist.ts +++ b/server/typescript/packages/test-generators/src/templates/filter-allowlist.ts @@ -93,24 +93,45 @@ const INTEGER_SUBTYPES = new Set([ * as UTC, the same rule the generated write schema stores it by. Scalar fields only: an * array field's filter value is not one element of the declared type. */ -function valueShape(f: MetaField): string { - if (f.resolvedIsArray()) return ""; - if (INTEGER_SUBTYPES.has(f.subType)) return ", integer: true as const"; +function valueShape(f: MetaField): FilterRuleValueShape { + if (f.resolvedIsArray()) return {}; + if (INTEGER_SUBTYPES.has(f.subType)) return { integer: true }; if (VALUE_FORMAT_SUBTYPES.has(f.subType)) { - const instant = f.subType === FIELD_SUBTYPE_TIMESTAMP && f.attr(FIELD_ATTR_LOCAL_TIME) !== true - ? ", instant: true as const" - : ""; - return `, format: ${JSON.stringify(f.subType)} as const${instant}`; + const instant = f.subType === FIELD_SUBTYPE_TIMESTAMP && f.attr(FIELD_ATTR_LOCAL_TIME) !== true; + return instant ? { format: f.subType, instant: true } : { format: f.subType }; } if (f.subType === FIELD_SUBTYPE_ENUM) { // Member SYMBOLS for string- and int-backed enums alike: an int-backed column's codec // maps the symbol to its integer when the value is bound. const members = enumValues(f); - if (members !== undefined && members.length > 0) { - return `, enumValues: [${members.map((m) => JSON.stringify(m)).join(", ")}] as const`; - } + if (members !== undefined && members.length > 0) return { enumValues: members }; } - return ""; + return {}; +} + +/** The optional members of a rule beyond `ops` / `subType` / `leadingWildcard`. */ +interface FilterRuleValueShape { + readonly dateValues?: true; + readonly format?: string; + readonly instant?: true; + readonly integer?: true; + readonly enumValues?: readonly string[]; +} + +/** + * One field's filter rule, as data: what `FilterAllowlist` carries for it. The + * runtime-ts `FilterFieldRule` shape, kept structural here so codegen does not depend on + * the runtime package. + */ +export interface FilterAllowlistRule extends FilterRuleValueShape { + readonly ops: readonly string[]; + readonly subType: "string" | "number" | "boolean" | "datetime"; + readonly leadingWildcard: false; +} + +/** One sortable field's rule, as data: what `SortAllowlist` carries for it. */ +export interface SortAllowlistRule { + readonly defaultOrder?: "asc" | "desc"; } function filterableFields(entity: MetaObject, exclude: string | undefined, ctx: RenderContext | undefined): MetaField[] { @@ -134,29 +155,49 @@ function filterableFields(entity: MetaObject, exclude: string | undefined, ctx: * normalized to `"string"` for sqlite/D1 at both config choke points, so no dialect * branching is needed here. Absent `ctx`, or in the default mode, output is unchanged. */ +export function filterAllowlistRules( + entity: MetaObject, + exclude?: string, + ctx?: RenderContext, +): ReadonlyArray { + return filterableFields(entity, exclude, ctx).map((f) => { + // opsForField, not opsForSubType — an int-backed field.enum (@intValueMap) + // stores as an integer, so `like` (a substring match) is not in its band. + const rule: FilterAllowlistRule = { + ops: opsForField(f), + subType: filterSubTypeFor(f.subType), + leadingWildcard: false, + // Only field.timestamp is governed by timestampMode — Drizzle types + // field.date / field.time as strings under every dialect. + ...(ctx?.timestampMode === "date" && f.subType === FIELD_SUBTYPE_TIMESTAMP ? { dateValues: true as const } : {}), + ...valueShape(f), + }; + return [f.name, rule] as const; + }); +} + +/** One rule as the generated allowlist spells it (members in a fixed order, `as const` on each). */ +function filterRuleLiteral(rule: FilterAllowlistRule): string { + const ops = rule.ops.map((o) => JSON.stringify(o)).join(", "); + let out = `{ ops: [${ops}] as const, subType: ${JSON.stringify(rule.subType)} as const, leadingWildcard: false`; + if (rule.dateValues) out += ", dateValues: true as const"; + if (rule.integer) out += ", integer: true as const"; + if (rule.format !== undefined) out += `, format: ${JSON.stringify(rule.format)} as const`; + if (rule.instant) out += ", instant: true as const"; + if (rule.enumValues !== undefined) out += `, enumValues: [${rule.enumValues.map((m) => JSON.stringify(m)).join(", ")}] as const`; + return `${out} }`; +} + export function renderFilterAllowlist(entity: MetaObject, exclude?: string, ctx?: RenderContext): Code { - const fields = filterableFields(entity, exclude, ctx); - if (fields.length === 0) { + const rules = filterAllowlistRules(entity, exclude, ctx); + if (rules.length === 0) { return code` import type { FilterAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; export const ${entity.name}FilterAllowlist = {} as const satisfies FilterAllowlist; `; } - const rows = fields - .map((f) => { - // opsForField, not opsForSubType — an int-backed field.enum (@intValueMap) - // stores as an integer, so `like` (a substring match) is not in its band. - const ops = opsForField(f).map((o) => JSON.stringify(o)).join(", "); - const sub = filterSubTypeFor(f.subType); - // Only field.timestamp is governed by timestampMode — Drizzle types - // field.date / field.time as strings under every dialect. - const dateValues = ctx?.timestampMode === "date" && f.subType === FIELD_SUBTYPE_TIMESTAMP - ? ", dateValues: true as const" - : ""; - return ` ${f.name}: { ops: [${ops}] as const, subType: ${JSON.stringify(sub)} as const, leadingWildcard: false${dateValues}${valueShape(f)} }`; - }) - .join(",\n"); + const rows = rules.map(([name, rule]) => ` ${name}: ${filterRuleLiteral(rule)}`).join(",\n"); return code` import type { FilterAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; @@ -166,34 +207,39 @@ ${rows} `; } -export function renderSortAllowlist(entity: MetaObject, exclude?: string, ctx?: RenderContext): Code { +/** The sortable fields and their rules, as data (what `SortAllowlist` carries). */ +export function sortAllowlistRules( + entity: MetaObject, + exclude?: string, + ctx?: RenderContext, +): ReadonlyArray { // Sortable = explicit @sortable === true, OR (no @sortable AND @filterable === true). - // @sortable: false explicitly opts out. - // Uses shared isSortableField predicate — must stay in sync with renderFilterType. - // `exclude` (FR-017): per-subtype TPH allowlists omit the discriminator. - // A credential is never sortable (isSortableField), nor a column a sibling subtype marks as one. + // @sortable: false explicitly opts out. A credential is never sortable, nor a column a + // sibling subtype marks as one. `exclude` (FR-017): per-subtype TPH allowlists omit the + // discriminator. const credentials = credentialFieldNames(entity, ctx?.loadedRoot); - const sortable = flatSurfaceFields(entity).filter((f) => isSortableField(f) && !credentials.has(f.name) && f.name !== exclude); - if (sortable.length === 0) { + return flatSurfaceFields(entity) + .filter((f) => isSortableField(f) && !credentials.has(f.name) && f.name !== exclude) + .map((f) => { + // The DECLARED order only — an undeclared field stays `{}` so the runtime's own + // `?? "asc"` remains the single place the fallback is spelled. + const defaultOrder = declaredSortDefaultOrder(f); + return [f.name, defaultOrder === undefined ? {} : { defaultOrder }] as const; + }); +} + +export function renderSortAllowlist(entity: MetaObject, exclude?: string, ctx?: RenderContext): Code { + const rules = sortAllowlistRules(entity, exclude, ctx); + if (rules.length === 0) { return code` import type { SortAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; export const ${entity.name}SortAllowlist = {} as const satisfies SortAllowlist; `; } - const rows = sortable - .map((f) => { - // The DECLARED order only — an undeclared field stays `{}` so the runtime's own - // `?? "asc"` remains the single place the fallback is spelled. Read through the - // shared resolver, never off the attr here, so this allowlist and the grid tier - // cannot answer one declaration two ways. - const defaultOrder = declaredSortDefaultOrder(f); - const rule = - defaultOrder === undefined - ? `{}` - : `{ defaultOrder: ${JSON.stringify(defaultOrder)} as const }`; - return ` ${f.name}: ${rule}`; - }) + const rows = rules + .map(([name, rule]) => + ` ${name}: ${rule.defaultOrder === undefined ? "{}" : `{ defaultOrder: ${JSON.stringify(rule.defaultOrder)} as const }`}`) .join(",\n"); return code` import type { SortAllowlist } from ${JSON.stringify(allowlistTypesFrom(entity, ctx))}; diff --git a/server/typescript/packages/test-generators/src/templates/view-decl.ts b/server/typescript/packages/test-generators/src/templates/view-decl.ts index 3dd02b2329..6f30828276 100644 --- a/server/typescript/packages/test-generators/src/templates/view-decl.ts +++ b/server/typescript/packages/test-generators/src/templates/view-decl.ts @@ -18,6 +18,7 @@ import { mapColumnType, DURATION_COLUMN_FN, type EnumIntCustomType } from "@meta import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; import { zodTypeFor } from "./field-meta.js"; +import { inlineObjectLiteral } from "./drizzle-schema.js"; import { columnExpr, type ObjectNames } from "@metaobjectsdev/codegen-ts/engine"; export interface ViewDeclOpts { @@ -111,7 +112,7 @@ function viewColumnLine( : imp(`${spec.fnName}@${spec.importModule}`); const optsArg = spec.fnOptions && Object.keys(spec.fnOptions).length > 0 - ? `, ${optionsLiteral(spec.fnOptions)}` + ? `, ${inlineObjectLiteral(spec.fnOptions)}` : ""; // #204 — of the table modifiers, only `.array()` (postgres native array element // typing) and `.notNull()` (shapes the SELECT type) carry to an existing view; @@ -252,12 +253,3 @@ export function renderViewReadZodObject(fields: readonly MetaField[], opts: View ${joinCode(lines, { on: ",\n" })} })`; } - -/** A column's options as a JS object literal: `{ length: 200 }`, not JSON's `{ "length": 200 }`. */ -function optionsLiteral(options: Record): string { - const entries = Object.entries(options).map(([key, value]) => { - const name = /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key); - return `${name}: ${JSON.stringify(value)}`; - }); - return `{ ${entries.join(", ")} }`; -} diff --git a/spec/decisions/ADR-0049-filter-like-is-case-sensitive-sql-like.md b/spec/decisions/ADR-0049-filter-like-is-case-sensitive-sql-like.md index 420e870789..6ef395ffd2 100644 --- a/spec/decisions/ADR-0049-filter-like-is-case-sensitive-sql-like.md +++ b/spec/decisions/ADR-0049-filter-like-is-case-sensitive-sql-like.md @@ -63,9 +63,11 @@ The written record, however, was not silent: operator or an attribute-gated variant); pinning `like` sensitive today forecloses nothing. The reverse pin would: an insensitive `like` makes case-sensitive matching inexpressible over the wire, permanently. -4. **The TS-only `?search` extension remains deliberately case-insensitive** - (ILIKE on Postgres; SQLite native LIKE). It is a human search box, not the - contract's `like` operator, and is documented as a TS-only extension. +4. **The `?search` parameter remains deliberately case-insensitive** + (ILIKE on Postgres; SQLite native LIKE; `LOWER()` on MySQL). It is a human search + box, not the contract's `like` operator. It was a TS-only extension until + [ADR-0068](ADR-0068-list-query-cross-port-contract.md) made it part of the cross-port + list contract; the case-insensitivity is unchanged by that. 5. **The corpora gate the distinction.** Both fixtures now carry case-mismatched probes (a `Foundations` / `foundations lab` seed pair in the persistence corpus; lowercase `a%` / `a_an%` probes against the diff --git a/spec/decisions/ADR-0068-list-query-cross-port-contract.md b/spec/decisions/ADR-0068-list-query-cross-port-contract.md new file mode 100644 index 0000000000..639d985671 --- /dev/null +++ b/spec/decisions/ADR-0068-list-query-cross-port-contract.md @@ -0,0 +1,52 @@ +# ADR-0068: The list query is part of the cross-port REST contract + +## Status + +**Accepted** (2026-11-21), for 1.3.0. Registers no vocabulary: `metamodelVersion` is unchanged. It +changes what the REST standard promises about a list route, in every port. + +## Context + +The REST standard's list handling was TypeScript-only in several places. `?search`, +`filter[or]` / `filter[and]`, the nesting cap, the bare-field and leading-`%` refusals, the +filter-value format check and the `in` list cap existed in the TypeScript runtime and nowhere +else. The `invalid_json`, `invalid_id`, `pagination.invalid_value` and `constraint_violation` +responses were the same. `docs/features/api-contract.md` said these were deferred until a consumer +asked, and told adopters not to assume them on a non-TypeScript backend. + +A client that is generated once and runs against any backend needs one answer to one query +string. Where ports differ, the difference reaches the adopter as a silently different result +set or a 5xx instead of a named 400. The ports also have no shared test of how a list route reads +its query string, so a port could not be held to the TypeScript behaviour. + +## Decision + +1. These are part of the REST contract, with TypeScript's wire names unchanged: + - `?search`, a case-insensitive substring match across the entity's `@filterable` text fields; + - `filter[or]` and `filter[and]`, and the nesting cap of five levels; + - the refusal of a bare field parameter and of a `like` pattern that starts with `%`; + - the filter-value format check, and the cap on the length of an `in` list; + - the `invalid_json`, `invalid_id`, `pagination.invalid_value` and `constraint_violation` + responses. +2. Two shared corpora are the authority, not the prose: + - `fixtures/list-query-conformance/`: a query string in, and a filter tree or the exact 400 + body out, with no server and no database; + - the `list-query/` sub-corpus of `fixtures/api-contract-conformance/`: what a parsed query + matches in a real store, over HTTP, in the generated lane. +3. A name every object inherits (`constructor`, `toString`, `__proto__`) is not an allowlisted + field. A port looks fields up as own keys only, so such a name is `invalid_sort` or an unknown + filter field, like any other name that is not declared. +4. Each port passes both corpora before the 1.3.0 release candidate `rc.4`. Until a port's + runner is in, `docs/CONFORMANCE.md` records that port as pending. Each port's change flips its + own entry; the prose in `docs/features/api-contract.md` is true of a port once its entry reads + as passing. + +## Consequences + +- An adopter can rely on one list-query behaviour on any backend once that backend's entry reads + as passing. +- A port that diverges fails a shared corpus. It no longer diverges unnoticed. +- The TypeScript behaviour becomes a compatibility constraint: changing a wire name or a refusal + needs a new corpus case and an amendment to this ADR. +- At the time of writing only TypeScript passes both corpora. C#, Java, Kotlin, Python and Rust + are pending their 1.3.0 REST-standard work. diff --git a/spec/decisions/README.md b/spec/decisions/README.md index f2caa34a99..3619dceddd 100644 --- a/spec/decisions/README.md +++ b/spec/decisions/README.md @@ -64,6 +64,7 @@ Write one when a decision is **cross-cutting** (affects more than one language p - [ADR-0065 — Rust is the sixth port](ADR-0065-rust-is-the-sixth-port.md) — *Accepted* (a Rust port under `server/rust/`, a full language of 1.3.0, crates ready to publish and not yet published; the command is `cargo meta`; no `migrate`, Jinja refused, generated code as one crate per MetaObjects package; gated by `registry-conformance` and the metamodel corpus with a shrink-only ledger. **Amendment 1**: `cargo meta init` / `gen` / `verify --codegen` / `eject`, an owned generator as a crate the project builds, the generated crate shape, and the `client` and `commands` generators, the second Rust-only by decision) - [ADR-0066 — Business rules: operations, permission points and lifecycles](ADR-0066-business-rules-operations-and-lifecycles.md) — *Accepted* (registers `api.*`, `operation.*`, `binding.*` and `transition.*` in all five ports, experimental, with eleven loader errors and a rules gate in every `verify`; the lifecycle, its states and a transition's command are derived; `transition.timed` reserved; the enforcing shells are later work) - [ADR-0067 — Generated code is layered, and hand-written code attaches at the service seam](ADR-0067-layering-and-the-service-seam.md) — *Accepted* (layers 0 to 6; a service module per metadata package whose surface is its operations; hand-written bodies, policy and event handling implement generated interfaces and are passed in, in every language; a layer is a generator an app chooses, per package, with no named sets; the actor is an app-defined type; amends ADR-0045) +- [ADR-0068 — The list query is part of the cross-port REST contract](ADR-0068-list-query-cross-port-contract.md) — *Accepted* (`?search`, `filter[or]`/`filter[and]`, the nesting cap, the bare-field and leading-`%` refusals, the value-format check, the `in` cap and the invalid_json / invalid_id / pagination.invalid_value / constraint_violation responses are contract in every port; `fixtures/list-query-conformance/` and the api-contract `list-query/` sub-corpus are the authority; each port passes both before rc.4) > **Index gap — ADR-0031 through ADR-0051 are on disk but not listed above.** The index stopped > being maintained after ADR-0030; the files are authoritative, this list is not. Read diff --git a/templates/agent/requirements.md.mustache b/templates/agent/requirements.md.mustache new file mode 100644 index 0000000000..cb7cba06cb --- /dev/null +++ b/templates/agent/requirements.md.mustache @@ -0,0 +1,34 @@ +{{{generatedMarker}}} + +# Requirements + +Read this before adding a capability, and before extending anything that looks like it already does what you were asked for. + +- A requirement is **prescriptive**: it states what should be true, never what happened. `status: retired` means the capability was BUILT and deliberately REMOVED — that entry is a prohibition, not history, and the right response to it is to stop, not to rebuild. +- The **node index** below answers *"does anything claim the thing I am about to change?"*. Match the literal FQN. +- **The ledger under it is not the same list.** A retired capability carries no `@implementedBy` — there is nothing left to point at — so it appears there and in no index. Read it before you conclude a capability does not exist yet. + +## Node index + +{{#hasNodeIndex}} +| Node | Kind | Claimed by | +|---|---|---| +{{#nodeIndex}} +| `{{{address}}}` | `{{{concern}}}` | {{{claims}}} | +{{/nodeIndex}} +{{#hasStatements}} + +### What those requirements say + +{{#statements}} +- `{{{path}}}` (`{{{subType}}}`) — {{{statement}}} +{{/statements}} +{{/hasStatements}} +{{/hasNodeIndex}} +{{^hasNodeIndex}} +No requirement resolves to a model node. The common reason is the ordinary one: an entry at L4 or L5 that simply declares no `@implementedBy` yet, which is legal and is what a `planned` entry looks like. The others are an entry sitting ABOVE the L4 link floor (where a claim is not permitted), a `retired` entry (where it is forbidden outright), and a claim that names a node nothing resolves — `meta verify` is what says which. +{{/hasNodeIndex}} + +## The ledger + +{{{ledger}}} diff --git a/templates/agent/schema.md.mustache b/templates/agent/schema.md.mustache new file mode 100644 index 0000000000..3c3da61ea3 --- /dev/null +++ b/templates/agent/schema.md.mustache @@ -0,0 +1,118 @@ +{{{generatedMarker}}} + +# Schema + +{{#physical}} +The physical shape of the `{{{dialect}}}` database this model generates. Read it before writing a query, a migration, or anything that names a table or a column. +{{/physical}} +{{^physical}} +The tables, columns and keys this model declares. Read it before writing a query, a migration, or anything that names a table or a column. SQL types, defaults, indexes, checks, constraint names and referential actions are not on this page: the migration files carry them. +{{/physical}} + +- The **DDL is not repeated here.** The migration files are the DDL, they are generated, and they are what runs — this page describes the schema they produce. +- Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. +- `Field` and `Declared` are the METADATA names. Edit those; the column name follows. + +{{#descriptionNudge}} +> **Nothing in this model declares a `description`.** The tables and columns below are named but not explained. Adding `description` to an entity or a field is the single highest-value change to this page: it is what tells a reader *which* of two plausible columns to use, and it is the same text `meta migrate` emits as a `COMMENT ON`, so it lands in the database too. + +{{/descriptionNudge}} +{{#hasTables}} +## Tables + +{{#tables}} +### {{{heading}}} + +{{#tableDeclaredBy}} +Declared by `{{{.}}}`. +{{/tableDeclaredBy}} +{{#tableDescription}} + +> {{{.}}} +{{/tableDescription}} + +{{#physical}} +| Column | Field | Declared | SQL type | Null | Default | Key | +|---|---|---|---|---|---|---| +{{/physical}} +{{^physical}} +| Column | Field | Declared | Null | Key | +|---|---|---|---|---| +{{/physical}} +{{#columns}} +| `{{{name}}}` | {{{fieldCell}}} | {{{declaredCell}}} |{{#physical}} {{{sqlTypeCell}}} |{{/physical}} {{{nullCell}}} |{{#physical}} {{{defaultCell}}} |{{/physical}} {{{keyCell}}} | +{{/columns}} +{{#hasDescribed}} + +{{#described}} +- `{{{name}}}` — {{{text}}} +{{/described}} +{{/hasDescribed}} +{{#hasIndexes}} + +**Indexes** + +{{#indexes}} +- {{{.}}} +{{/indexes}} +{{/hasIndexes}} +{{#hasForeignKeys}} + +**Foreign keys** + +{{#foreignKeys}} +- {{{.}}} +{{/foreignKeys}} +{{/hasForeignKeys}} +{{#hasChecks}} + +**Checks** + +{{#checks}} +- {{{.}}} +{{/checks}} +{{/hasChecks}} + +{{/tables}} +{{/hasTables}} +{{#hasViews}} +## Views + +A view is generated from its projection's `origin.*` children{{#hasReportView}} or its report's dimensions and measures{{/hasReportView}} — it is derived, never hand-written. Editing the view SQL directly is drift the tool cannot see. + +{{#views}} +### {{{heading}}} + +{{#viewDeclaredBy}} +Declared by `{{{.}}}`. +{{/viewDeclaredBy}} +{{#hasLineage}} + +| Column | Lineage | +|---|---| +{{#lineage}} +| `{{{column}}}` | {{{text}}} | +{{/lineage}} +{{/hasLineage}} + +{{/views}} +{{/hasViews}} +{{#hasRelationships}} +## Relationships + +{{#relationships}} +- {{{.}}} +{{/relationships}} + +{{/hasRelationships}} +{{#hasEnums}} +## Enums + +Members are the values the wire and the generated types use.{{#physical}} Whether the DATABASE also refuses a value outside the set is that table's **Checks** above — an `@isArray` enum carries none, and neither does a view column.{{/physical}} + +| Field | Members | Storage | +|---|---|---| +{{#enums}} +| `{{{field}}}` | {{{members}}} | {{{storage}}} | +{{/enums}} +{{/hasEnums}} diff --git a/templates/requirements/requirements.md.mustache b/templates/requirements/requirements.md.mustache new file mode 100644 index 0000000000..a200094478 --- /dev/null +++ b/templates/requirements/requirements.md.mustache @@ -0,0 +1,27 @@ +{{^embedded}} +# Requirements + +{{/embedded}} +{{{count}}} declared requirement{{{plural}}}, in declaration order. +{{#entries}} + +{{{heading}}} + +{{{facts}}} +{{#statement}} + +{{{.}}} +{{/statement}} +{{#counterexample}} + +{{{.}}} +{{/counterexample}} +{{#description}} + +{{{.}}} +{{/description}} +{{#implementedBy}} + +{{{.}}} +{{/implementedBy}} +{{/entries}} diff --git a/templates/requirements/requirements.toon.mustache b/templates/requirements/requirements.toon.mustache new file mode 100644 index 0000000000..cae64ef896 --- /dev/null +++ b/templates/requirements/requirements.toon.mustache @@ -0,0 +1,2 @@ +requirements[{{{count}}}]{{{fields}}}:{{#rows}} + {{{line}}}{{/rows}} \ No newline at end of file