From 3956a5894476d74c0e0b934ce3be02ab8c3bdf94 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 20:40:50 -0500 Subject: [PATCH 1/9] feat(csharp): move the route helpers into a MetaObjects.AspNetCore package The helpers generated routes call (FilterParser, EfCoreFilterDispatch, ValueObjectValidator, ConstraintErrors and the rest of HelperRuntime.Files) move from MetaObjects.Codegen/Runtime/ into a new MetaObjects.AspNetCore project and NuGet package, namespace MetaObjects.AspNetCore, which references ASP.NET Core and EF Core and no MetaObjects package. MetaObjects.Codegen drops its EF Core and ASP.NET Core references, so the dotnet meta tool packs 6 DLLs instead of 14. ExtractObject and M2MResolver stay in MetaObjects.Codegen as core. - The packaged routes generator writes `using MetaObjects.AspNetCore;`, so regen moves the import; owned copies keep Codegen.Runtime. Eject reads the helper source embedded by link in MetaObjects.Codegen. - gen and verify --codegen warn (advisory) when a generated file imports MetaObjects.AspNetCore and its project does not reference the package, and when generated output still imports the helpers from MetaObjects.Codegen.Runtime. - CHANGELOG upgrade note, design note, docs, agent-context goldens, showcase regen, and the publish workflow, prerelease script and RELEASING pack five C# packages. --- .github/workflows/publish-csharp.yml | 3 +- CHANGELOG.md | 30 +++ ...e3f75ac9b8e8680.md => 2156dfce0f68c87a.md} | 1 + ...e7f8817bfc35bb5.md => eb9b4e5f5004f09c.md} | 4 +- agent-context-shipped/manifest.json | 16 +- .../metaobjects-codegen/references/csharp.md | 1 + .../references/csharp.md | 4 +- docs/RELEASING.md | 12 +- docs/features/own-your-codegen.md | 13 +- docs/ports/csharp.md | 17 +- ...csharp-aspnetcore-helper-package-design.md | 80 ++++++++ .../.metaobjects/.gen-state/.hashes/acme.json | 2 +- .../generated/csharp/SubscriberRoutes.g.cs | 2 +- .../metaobjects-codegen/references/csharp.md | 1 + .../references/csharp.md | 4 +- scripts/prerelease.mjs | 7 +- .../ConstraintErrors.cs | 2 +- .../DecimalRangeEndpointFilter.cs | 2 +- .../DecimalWire.cs | 2 +- .../DurationWire.cs | 2 +- .../EfCoreFilterDispatch.cs | 2 +- .../FilterParseResult.cs | 2 +- .../FilterParser.cs | 2 +- .../FilterPredicate.cs | 2 +- .../Iso8601TimestampConverter.cs | 2 +- .../MetaObjects.AspNetCore.csproj | 20 ++ .../ReportExportHttp.cs | 2 +- .../SerializerKeys.cs | 2 +- .../UnknownFieldCheck.cs | 2 +- .../ValidationIssues.cs | 2 +- .../ValueObjectValidator.cs | 2 +- .../VerifySubverbTests.cs | 35 ++++ server/csharp/MetaObjects.Cli/EjectCommand.cs | 4 +- .../csharp/MetaObjects.Cli/VerifyCommand.cs | 3 + .../ApiSettingsTests.cs | 2 +- .../ConstraintErrorsTests.cs | 2 +- .../DecimalWireTests.cs | 8 +- .../DurationWireTests.cs | 8 +- .../EjectedGeneratorsAloneTests.cs | 2 +- .../EntityGeneratorTests.cs | 4 +- .../ExtractObjectArrayBoundsTests.cs | 1 + .../ExtractObjectVerdictTests.cs | 1 + .../Golden/pre-rc22-propname/GizmoRoutes.g.cs | 2 +- .../Golden/pre-rc22-propname/LineRoutes.g.cs | 2 +- .../pre-rc22-propname/LineTotalsRoutes.g.cs | 2 +- .../Golden/pre-rc22-propname/TagRoutes.g.cs | 2 +- .../pre-rc22-propname/VehicleRoutes.g.cs | 2 +- .../pre-rc22-propname/VehicleTagRoutes.g.cs | 2 +- .../WidgetSummaryRoutes.g.cs | 2 +- .../HelperRuntimeReferenceTests.cs | 111 ++++++++++ .../HelperRuntimeTests.cs | 21 +- .../Iso8601TimestampConverterTests.cs | 2 +- .../MetaObjects.Codegen.Tests.csproj | 1 + .../PackageKeyedOutputTests.cs | 1 + .../PackageNamespaceTests.cs | 2 +- .../PropertyNamingEmitSitesTests.cs | 12 +- .../ReportExportGeneratorTests.cs | 2 +- .../SerializerKeysTests.cs | 2 +- .../ServerOwnedCreateInputTests.cs | 2 +- .../TphM2mRoutesTests.cs | 4 +- .../ValidationIssuesTests.cs | 2 +- .../csharp/MetaObjects.Codegen/CodegenCli.cs | 4 + .../MetaObjects.Codegen/CodegenRunner.cs | 9 + .../EjectableGenerators.cs | 2 +- .../Generators/EntityGenerator.cs | 4 +- .../Generators/KNOWN_GAPS.md | 2 +- .../Generators/RoutesGenerator.cs | 4 +- .../MetaObjects.Codegen/HelperRuntime.cs | 42 ++-- .../HelperRuntimeReference.cs | 190 ++++++++++++++++++ .../MetaObjects.Codegen.csproj | 49 ++--- .../Api/DecimalWireGeneratedApiTests.cs | 10 +- .../Api/JsonbGeneratedServerFactory.cs | 2 +- .../Api/JsonbReferenceServer.cs | 2 +- .../Api/TphReferenceServer.cs | 2 +- .../MetaObjects.IntegrationTests.csproj | 3 + .../Runner/DbContextAdapter.cs | 2 +- .../Runner/Normalization.cs | 2 +- .../Runner/WriteCoercion.cs | 4 +- server/csharp/MetaObjects.sln | 6 + server/csharp/README.md | 1 + 80 files changed, 675 insertions(+), 156 deletions(-) rename agent-context-shipped/files/{6e3f75ac9b8e8680.md => 2156dfce0f68c87a.md} (99%) rename agent-context-shipped/files/{fe7f8817bfc35bb5.md => eb9b4e5f5004f09c.md} (98%) create mode 100644 docs/superpowers/specs/2026-11-22-csharp-aspnetcore-helper-package-design.md rename server/csharp/{MetaObjects.Codegen/Runtime => MetaObjects.AspNetCore}/ConstraintErrors.cs (99%) rename server/csharp/{MetaObjects.Codegen/Runtime => MetaObjects.AspNetCore}/DecimalRangeEndpointFilter.cs (98%) rename server/csharp/{MetaObjects.Codegen/Runtime => MetaObjects.AspNetCore}/DecimalWire.cs (99%) rename server/csharp/{MetaObjects.Codegen/Runtime => MetaObjects.AspNetCore}/DurationWire.cs (99%) rename server/csharp/{MetaObjects.Codegen/Runtime => MetaObjects.AspNetCore}/EfCoreFilterDispatch.cs (99%) rename server/csharp/{MetaObjects.Codegen/Runtime => MetaObjects.AspNetCore}/FilterParseResult.cs (97%) rename server/csharp/{MetaObjects.Codegen/Runtime => MetaObjects.AspNetCore}/FilterParser.cs (99%) rename server/csharp/{MetaObjects.Codegen/Runtime => MetaObjects.AspNetCore}/FilterPredicate.cs (96%) rename server/csharp/{MetaObjects.Codegen/Runtime => MetaObjects.AspNetCore}/Iso8601TimestampConverter.cs (98%) create mode 100644 server/csharp/MetaObjects.AspNetCore/MetaObjects.AspNetCore.csproj rename server/csharp/{MetaObjects.Codegen/Runtime => MetaObjects.AspNetCore}/ReportExportHttp.cs (99%) rename server/csharp/{MetaObjects.Codegen/Runtime => MetaObjects.AspNetCore}/SerializerKeys.cs (99%) rename server/csharp/{MetaObjects.Codegen/Runtime => MetaObjects.AspNetCore}/UnknownFieldCheck.cs (98%) rename server/csharp/{MetaObjects.Codegen/Runtime => MetaObjects.AspNetCore}/ValidationIssues.cs (99%) rename server/csharp/{MetaObjects.Codegen/Runtime => MetaObjects.AspNetCore}/ValueObjectValidator.cs (99%) create mode 100644 server/csharp/MetaObjects.Codegen.Tests/HelperRuntimeReferenceTests.cs create mode 100644 server/csharp/MetaObjects.Codegen/HelperRuntimeReference.cs diff --git a/.github/workflows/publish-csharp.yml b/.github/workflows/publish-csharp.yml index 6145a8fa8b..4ce4cb0eee 100644 --- a/.github/workflows/publish-csharp.yml +++ b/.github/workflows/publish-csharp.yml @@ -5,7 +5,7 @@ name: publish-csharp # after validating GitHub's OIDC token against the trusted-publishing policy # configured under the `metaobjects` org. See docs/RELEASING.md. # -# Packages: MetaObjects, MetaObjects.Render, MetaObjects.Codegen, MetaObjects.Cli (dotnet tool). +# Packages: MetaObjects, MetaObjects.Render, MetaObjects.Codegen, MetaObjects.AspNetCore, MetaObjects.Cli (dotnet tool). # # One-time setup on nuget.org (your username -> Trusted Publishing -> Create): # Package Owner: metaobjects (the org) @@ -72,6 +72,7 @@ jobs: dotnet pack server/csharp/MetaObjects/MetaObjects.csproj -c Release -o artifacts $VERSION_ARG dotnet pack server/csharp/MetaObjects.Render/MetaObjects.Render.csproj -c Release -o artifacts $VERSION_ARG dotnet pack server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj -c Release -o artifacts $VERSION_ARG + dotnet pack server/csharp/MetaObjects.AspNetCore/MetaObjects.AspNetCore.csproj -c Release -o artifacts $VERSION_ARG dotnet pack server/csharp/MetaObjects.Cli/MetaObjects.Cli.csproj -c Release -o artifacts $VERSION_ARG ls -l artifacts diff --git a/CHANGELOG.md b/CHANGELOG.md index 440cceef29..d2b0aedb82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,32 @@ here.** ## [Unreleased] +- **C#: the route helpers are their own package, `MetaObjects.AspNetCore`, and `MetaObjects.Codegen` + and the `dotnet meta` tool no longer carry EF Core.** `FilterParser`, `FilterParseResult`, + `FilterPredicate`, `EfCoreFilterDispatch`, `ValueObjectValidator`, `ConstraintErrors`, + `ValidationIssues`, `UnknownFieldCheck`, `Iso8601TimestampConverter`, `DecimalWire`, + `DurationWire`, `DecimalRangeEndpointFilter`, `ReportExportHttp` and `SerializerKeys` moved from + `MetaObjects.Codegen` (namespace `MetaObjects.Codegen.Runtime`) to the new `MetaObjects.AspNetCore` + package (namespace `MetaObjects.AspNetCore`), which depends on ASP.NET Core and EF Core and on no + MetaObjects package. `MetaObjects.Codegen` drops its EF Core and ASP.NET Core references: the tool + installs about 42% smaller (14 DLLs to 6), and the first restore of a `codegen/` project no longer + pulls EF Core's 11 packages. `ExtractObject` and `M2MResolver` stay in `MetaObjects.Codegen` under + `MetaObjects.Codegen.Runtime`. The packaged routes generator now writes `using MetaObjects.AspNetCore;`, + so the next `dotnet meta gen` moves that line in every generated routes file. `dotnet meta gen` and + `dotnet meta verify` warn when a generated file imports `MetaObjects.AspNetCore` and the project + that compiles it (the one `.csproj` in its directory or above, a project it references, or a + `Directory.Build.props`/`.targets` above them) does not reference the package, and when generated + output still imports the helpers from `MetaObjects.Codegen.Runtime`. Both warnings are advisory. + `dotnet meta eject routes` still copies the helpers into `codegen/runtime/` as `Codegen.Runtime`. + **Upgrade:** add `` to the + app that compiles the generated routes, run `dotnet meta gen`, and change any hand-written + `using MetaObjects.Codegen.Runtime;` that names one of the helpers (a host registering + `Iso8601TimestampConverter`, say) to `using MetaObjects.AspNetCore;`. A routes generator you + ejected before the helpers were handed over writes `using MetaObjects.Codegen.Runtime;`: set its + `HelperRuntimeNamespace` constant to `"MetaObjects.AspNetCore"`, or re-eject with + `dotnet meta eject routes --force`. An app that only uses the ejected helpers in `codegen/runtime/` + needs nothing. + - **The deprecated-reference finding ends its sentence before naming the replacement.** It read `…Team: the league no longer tracks teams Replaced by acme::app::Club.`; it now reads `…tracks teams. Replaced by acme::app::Club.` A reason that already ends in `.`, `!` or `?` is left as written. - **C#: `dotnet meta verify` runs the three model authoring lints.** The overlay lint @@ -525,6 +551,10 @@ the one `metamodelVersion` value, `1.3`. Each item below is described in full under Security, Added, Changed or Fixed; this list is where to start. +- **C#: add the `MetaObjects.AspNetCore` package to the app that compiles generated routes.** The + helpers those routes call moved out of `MetaObjects.Codegen` into it, and the regenerated routes + import `MetaObjects.AspNetCore`; a hand-written `using MetaObjects.Codegen.Runtime;` for them + changes the same way. `dotnet meta gen` and `verify` warn while the reference is missing. - **`validator.atLeastOne` takes no `@max`.** A model that carries `@max: 1` on an `atLeastOne` fails to load; a rule meaning "exactly one of these fields" is the new `validator.exactlyOne`. - **C# durations on the wire.** A `field.duration` is written in each language's standard form diff --git a/agent-context-shipped/files/6e3f75ac9b8e8680.md b/agent-context-shipped/files/2156dfce0f68c87a.md similarity index 99% rename from agent-context-shipped/files/6e3f75ac9b8e8680.md rename to agent-context-shipped/files/2156dfce0f68c87a.md index 06cfdda9e1..73f2e2b3a1 100644 --- a/agent-context-shipped/files/6e3f75ac9b8e8680.md +++ b/agent-context-shipped/files/2156dfce0f68c87a.md @@ -24,6 +24,7 @@ Per the always-on descriptor: ```bash dotnet tool install --global MetaObjects.Cli # provides `dotnet meta` dotnet add package MetaObjects.Codegen # the codegen generators +dotnet add package MetaObjects.AspNetCore # in the app: the helpers generated routes call dotnet meta init # writes codegen/: Generators.cs, Program.cs, Codegen.csproj ``` diff --git a/agent-context-shipped/files/fe7f8817bfc35bb5.md b/agent-context-shipped/files/eb9b4e5f5004f09c.md similarity index 98% rename from agent-context-shipped/files/fe7f8817bfc35bb5.md rename to agent-context-shipped/files/eb9b4e5f5004f09c.md index 6fd985d885..e65702a006 100644 --- a/agent-context-shipped/files/fe7f8817bfc35bb5.md +++ b/agent-context-shipped/files/eb9b4e5f5004f09c.md @@ -96,8 +96,8 @@ app.Run(); Filter operators (`eq` `ne` `gt` `gte` `lt` `lte` `in` `like` `isNull`) ship via the per-entity `FilterAllowlist` (from `FilterAllowlistGenerator`); the generated list -handler calls the `FilterParser` / `EfCoreFilterDispatch` runtime helpers in -`MetaObjects.Codegen`, so your ASP.NET host references that assembly at runtime. After +handler calls the `FilterParser` / `EfCoreFilterDispatch` runtime helpers in the +`MetaObjects.AspNetCore` package, so your ASP.NET host references that package. After `dotnet meta eject routes` it calls your own copies in `codegen/runtime/` (namespace `Codegen.Runtime`) instead: compile that folder into the app and the reference goes away. The same universal TS/Angular web client consumes those routes unchanged — the wire format matches diff --git a/agent-context-shipped/manifest.json b/agent-context-shipped/manifest.json index f4b44e8178..64d7face73 100644 --- a/agent-context-shipped/manifest.json +++ b/agent-context-shipped/manifest.json @@ -2550,7 +2550,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "6e3f75ac9b8e8680.md" + "file": "2156dfce0f68c87a.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -2590,7 +2590,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "fe7f8817bfc35bb5.md" + "file": "eb9b4e5f5004f09c.md" }, { "path": ".claude/skills/metaobjects-verify/SKILL.md", @@ -2741,7 +2741,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "6e3f75ac9b8e8680.md" + "file": "2156dfce0f68c87a.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -2781,7 +2781,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "fe7f8817bfc35bb5.md" + "file": "eb9b4e5f5004f09c.md" }, { "path": ".claude/skills/metaobjects-runtime-ui/references/react.md", @@ -2937,7 +2937,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "6e3f75ac9b8e8680.md" + "file": "2156dfce0f68c87a.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -2977,7 +2977,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "fe7f8817bfc35bb5.md" + "file": "eb9b4e5f5004f09c.md" }, { "path": ".claude/skills/metaobjects-runtime-ui/references/react.md", @@ -3136,7 +3136,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "6e3f75ac9b8e8680.md" + "file": "2156dfce0f68c87a.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -3176,7 +3176,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "fe7f8817bfc35bb5.md" + "file": "eb9b4e5f5004f09c.md" }, { "path": ".claude/skills/metaobjects-verify/SKILL.md", diff --git a/agent-context/skills/metaobjects-codegen/references/csharp.md b/agent-context/skills/metaobjects-codegen/references/csharp.md index 06cfdda9e1..73f2e2b3a1 100644 --- a/agent-context/skills/metaobjects-codegen/references/csharp.md +++ b/agent-context/skills/metaobjects-codegen/references/csharp.md @@ -24,6 +24,7 @@ Per the always-on descriptor: ```bash dotnet tool install --global MetaObjects.Cli # provides `dotnet meta` dotnet add package MetaObjects.Codegen # the codegen generators +dotnet add package MetaObjects.AspNetCore # in the app: the helpers generated routes call dotnet meta init # writes codegen/: Generators.cs, Program.cs, Codegen.csproj ``` diff --git a/agent-context/skills/metaobjects-runtime-ui/references/csharp.md b/agent-context/skills/metaobjects-runtime-ui/references/csharp.md index 6fd985d885..e65702a006 100644 --- a/agent-context/skills/metaobjects-runtime-ui/references/csharp.md +++ b/agent-context/skills/metaobjects-runtime-ui/references/csharp.md @@ -96,8 +96,8 @@ app.Run(); Filter operators (`eq` `ne` `gt` `gte` `lt` `lte` `in` `like` `isNull`) ship via the per-entity `FilterAllowlist` (from `FilterAllowlistGenerator`); the generated list -handler calls the `FilterParser` / `EfCoreFilterDispatch` runtime helpers in -`MetaObjects.Codegen`, so your ASP.NET host references that assembly at runtime. After +handler calls the `FilterParser` / `EfCoreFilterDispatch` runtime helpers in the +`MetaObjects.AspNetCore` package, so your ASP.NET host references that package. After `dotnet meta eject routes` it calls your own copies in `codegen/runtime/` (namespace `Codegen.Runtime`) instead: compile that folder into the app and the reference goes away. The same universal TS/Angular web client consumes those routes unchanged — the wire format matches diff --git a/docs/RELEASING.md b/docs/RELEASING.md index ee7a48897c..a7961d7ab3 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -743,14 +743,15 @@ How to publish the `MetaObjects*` C# packages to nuget.org. We use **Trusted Pub ## What gets published -Four packages, version-locked at the C# port version (the `` in +Five packages, version-locked at the C# port version (the `` in [`server/csharp/Directory.Build.props`](../server/csharp/Directory.Build.props)): | Package | Contents | |---|---| | `MetaObjects` | Loader + canonical serializer | | `MetaObjects.Render` | Mustache render + payload-VO + `verify` | -| `MetaObjects.Codegen` | EF Core + ASP.NET codegen + the runtime filter/dispatch helpers generated code references | +| `MetaObjects.Codegen` | EF Core + ASP.NET codegen (writes EF and ASP.NET code as text; depends on neither) | +| `MetaObjects.AspNetCore` | The helper runtime generated routes call (filter parser, EF Core filter dispatch, validation, wire forms); the APP references it, the tool does not | | `MetaObjects.Cli` | The `dotnet meta` .NET tool (`gen` / `verify`; `agent-docs` is a redirect stub to the Node `meta` CLI) | Shared package metadata lives in [`server/csharp/Directory.Build.props`](../server/csharp/Directory.Build.props); @@ -818,11 +819,12 @@ lock the repo/owner IDs against resurrection attacks.) 2. **Validate locally** (catches immutable-version mistakes before they're permanent): ```bash cd server/csharp - # NOTE: pack ONE project per invocation. Passing all four to a single `dotnet pack` + # NOTE: pack ONE project per invocation. Passing all five to a single `dotnet pack` # fails on modern SDKs (verified on 8.0.129) with `MSBUILD : error MSB1008: Only one # project can be specified` — MSBuild treats the extra paths as switches. for p in MetaObjects/MetaObjects.csproj MetaObjects.Render/MetaObjects.Render.csproj \ - MetaObjects.Codegen/MetaObjects.Codegen.csproj MetaObjects.Cli/MetaObjects.Cli.csproj; do + MetaObjects.Codegen/MetaObjects.Codegen.csproj MetaObjects.AspNetCore/MetaObjects.AspNetCore.csproj \ + MetaObjects.Cli/MetaObjects.Cli.csproj; do dotnet pack "$p" -c Release -o /tmp/mo-nupkg || echo "PACK FAILED: $p" done # inspect a nuspec — version, license, readme, deps: @@ -833,7 +835,7 @@ lock the repo/owner IDs against resurrection attacks.) 3. **Run persistence conformance** if the runtime/codegen changed: `scripts/integration-test.sh csharp`. 4. **Publish:** GitHub → **Actions → publish-csharp → Run workflow** (or push a `csharp-v` tag). This is the one registry that CANNOT be published locally — see "How we publish" above. -5. **Verify** on nuget.org: all four packages listed and **owned by the `metaobjects` org** +5. **Verify** on nuget.org: all five packages listed (`MetaObjects.AspNetCore` is a new package id from 1.3.0: check its first push landed) and **owned by the `metaobjects` org** (indexing/validation takes a few minutes). # Releasing the Python package to PyPI diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index ecaff67123..dcd225df0a 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -1699,7 +1699,8 @@ is no `dotnet meta docs`: see [the migration section](migrations/docs-are-genera Generated routes call a handful of helpers: the filter parser, the EF Core filter dispatch, the value-object validator and the constraint-error mapping. In the package they -live in `MetaObjects.Codegen.Runtime`. They are helpers, not core, because nothing but +live in `MetaObjects.AspNetCore` (namespace `MetaObjects.AspNetCore`), which the app references; +before 1.3.0 they were part of `MetaObjects.Codegen`, under `MetaObjects.Codegen.Runtime`. They are helpers, not core, because nothing but generated routes calls them, so an owned routes generator comes with owned copies of them. Otherwise a bug in the filter parser would still mean waiting for a MetaObjects release. @@ -1729,7 +1730,7 @@ builder.Services.ConfigureHttpJsonOptions(o => ``` The generated routes then compile against your copy, and the app needs no -`MetaObjects.Codegen` reference for them. A `codegen/Codegen.csproj` scaffolded by this +`MetaObjects.AspNetCore` reference for them. A `codegen/Codegen.csproj` scaffolded by this version already excludes `runtime/**` from the codegen tool's own build. If yours predates it, add ``. The tool builds either way, but the runtime belongs to your app, not to the generator. @@ -1741,7 +1742,7 @@ M of your own` or is `missing`. `dotnet meta verify --codegen` never reads the f compares `--out` against a fresh regen, and your runtime copy is owned code, not generated output. -What stays in the package is core: `ExtractObject`, the reply parser the prompt-tier +What stays in `MetaObjects.Codegen` is core: `ExtractObject`, the reply parser the prompt-tier modules delegate to, and `M2MResolver`, the metadata-driven M:N traversal. The loader, registry, render and verify stay package dependencies too. @@ -1765,8 +1766,10 @@ a conflict only where upstream and you changed the same lines. The same recipe c generator copies. Afterwards, bump the version in `codegen/Codegen.csproj` so the next diff starts from the right place. -A copy of `RoutesGenerator.cs` ejected before this change still emits -`using MetaObjects.Codegen.Runtime;` and keeps working against the package. To move it over, +A copy of `RoutesGenerator.cs` ejected before the helpers were handed over still emits +`using MetaObjects.Codegen.Runtime;`. Since 1.3.0 that namespace no longer holds the helpers, so +its output does not compile, and `dotnet meta gen` and `verify` say so. Either set its +`HelperRuntimeNamespace` constant to `"MetaObjects.AspNetCore"` and reference that package, or run the recipe above: the patch carries the `HelperRuntimeNamespace` line and adds `codegen/runtime/`. diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 923d5dcec1..9c52d2fcd9 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -71,7 +71,8 @@ SQLite so it runs with nothing else installed; the same generated code runs on P enable - + + @@ -935,9 +936,13 @@ is for samples; on Postgres create the tables with the Node CLI's migrations EF Core does the rest — the generated entities and `AppDbContext` are plain EF Core with no MetaObjects types in them. Note the one exception: generated **routes** emit -`using MetaObjects.Codegen.Runtime;` for the shared filter/sort helpers, so a project that -generates routes with the packaged generator references `MetaObjects.Codegen` at runtime. -Entities-and-DbContext-only projects do not. +`using MetaObjects.AspNetCore;` for the shared filter/sort helpers, so a project that +generates routes with the packaged generator references the `MetaObjects.AspNetCore` package +(``). Entities-and-DbContext-only +projects do not. `MetaObjects.Codegen` and the `dotnet meta` tool carry no EF Core or ASP.NET Core +dependency; before 1.3.0 the helpers lived in `MetaObjects.Codegen` under +`MetaObjects.Codegen.Runtime`, and `dotnet meta gen` / `verify` warn when generated routes import +`MetaObjects.AspNetCore` and the project compiling them does not reference it. **Owning the routes, helpers included.** `dotnet meta eject routes` copies the routes generator into `codegen/generators/` AND the helper source its output calls into @@ -946,8 +951,8 @@ generator into `codegen/generators/` AND the helper source its output calls into `Iso8601TimestampConverter`, each under the namespace `Codegen.Runtime`. The owned generator's output imports `Codegen.Runtime` instead of the package. Compile the folder into your app (``) and the generated routes need -no `MetaObjects.Codegen` reference; a fix to the filter parser is then an edit in your repo, -not a wait for a release. What stays in the package is core: `ExtractObject` (the reply +no `MetaObjects.AspNetCore` reference; a fix to the filter parser is then an edit in your repo, +not a wait for a release. What stays in `MetaObjects.Codegen` is core: `ExtractObject` (the reply parser the prompt tier calls) and `M2MResolver` (metadata-driven M:N traversal), plus the loader, registry, render and verify. `dotnet meta gen --list` reports the copy `identical` or per-file `DIFFERS`, `verify --codegen` does not treat it as drift, and diff --git a/docs/superpowers/specs/2026-11-22-csharp-aspnetcore-helper-package-design.md b/docs/superpowers/specs/2026-11-22-csharp-aspnetcore-helper-package-design.md new file mode 100644 index 0000000000..8569f7f5f5 --- /dev/null +++ b/docs/superpowers/specs/2026-11-22-csharp-aspnetcore-helper-package-design.md @@ -0,0 +1,80 @@ +# C#: the route helpers become their own package (1.3.0) + +**Status:** decided 2026-11-22 (owner: "make the C# change to split that out"), built in 1.3.0. + +## Problem + +`MetaObjects.Codegen` carried a `PackageReference` on EF Core and a `FrameworkReference` on +ASP.NET Core for one reason: the helpers under `MetaObjects.Codegen/Runtime/` that generated +routes call. `EfCoreFilterDispatch.cs` was the only source in the assembly that used an EF Core +type, and the generators only write EF code as text. Everything that installs the generators paid +for it: the `dotnet meta` tool (14 DLLs, 11.9 MB installed, EF Core present twice) and every +`codegen/` project's first restore (EF Core's 11-package closure, about 25 MB). The code that +needs EF Core runs in the adopter's app, which already restores EF Core for the generated +`AppDbContext`. + +## Package boundary + +A new project and NuGet package, `server/csharp/MetaObjects.AspNetCore/`, id and namespace +`MetaObjects.AspNetCore`. It holds the fourteen files `HelperRuntime.Files` lists (the filter +parser and its result and predicate types, `EfCoreFilterDispatch`, `ValueObjectValidator`, +`ConstraintErrors`, `ValidationIssues`, `UnknownFieldCheck`, `Iso8601TimestampConverter`, +`DecimalWire`, `DurationWire`, `DecimalRangeEndpointFilter`, `ReportExportHttp`, +`SerializerKeys`). It references ASP.NET Core and EF Core 8 and **no MetaObjects package**: the +helper set was already closed (eject copies it into an adopter's repo as it is), and the project +boundary now enforces that by compilation. + +The name says what it binds to, the .NET convention for a framework integration package. It is +not called `MetaObjects.Runtime`: the runtime-metadata pillar is a separate, unbuilt C# +capability, and a package by that name would claim it. + +What stays in `MetaObjects.Codegen`, under `MetaObjects.Codegen.Runtime`: `ExtractObject` (the +reply parser the generated output parsers delegate to; it needs the metamodel and +`MetaObjects.Render`) and `M2MResolver` (metadata-driven M:N traversal). Both are core, neither +uses EF Core or ASP.NET Core, and moving them would put a prompt-only app on an EF Core +dependency. `MetaObjects.Codegen` drops both framework references. + +## Eject + +`dotnet meta eject routes` still copies the helpers into `codegen/runtime/` as `Codegen.Runtime`. +The tool cannot compile the new project (that is the point), so `MetaObjects.Codegen.csproj` +embeds the files' source by link (``). `HelperRuntimeTests` keeps its gates: each +embedded copy equals its source, the embedded set equals `HelperRuntime.Files`, and every file in +`MetaObjects.AspNetCore/` is a helper and every file in `MetaObjects.Codegen/Runtime/` is core. +The owned namespace is unchanged, so copies ejected before 1.3.0 compare as they did. + +## The namespace move on regen + +The packaged routes generator's `HelperRuntimeNamespace` is `MetaObjects.AspNetCore`, so the next +`dotnet meta gen` rewrites the one `using` line in every generated routes file. Nothing else in +generated output changes. An owned routes generator keeps `Codegen.Runtime` and is unaffected. + +## The reference warning + +`dotnet meta gen` (from what it writes) and `dotnet meta verify --codegen` (from the committed +generated files, on the cached fast path too) warn, never fail, when: + +1. a generated file imports `MetaObjects.AspNetCore` and its project does not reference the + package. The project is the one `.csproj` in the file's directory or above (the rule the + DbContext's assembly name already uses). The reference counts when it is in that project, a + project it references (transitively), or a `Directory.Build.props`/`.targets` above any of + them, as a `PackageReference` or a `ProjectReference`. No project found, or a file that cannot + be read, is silent: the drift-check bias is toward under-flagging. The warning names the + project and the exact `PackageReference` line to add. +2. a generated file still imports `MetaObjects.Codegen.Runtime` and names one of the moved types: + the output of a routes generator owned from before the helpers were handed over. The warning + says to set its `HelperRuntimeNamespace` to `MetaObjects.AspNetCore` or re-eject. + +## Upgrade path + +Add `` to the app, run +`dotnet meta gen`, and change any hand-written `using MetaObjects.Codegen.Runtime;` that names a +helper (typically the host's `Iso8601TimestampConverter` registration). The CHANGELOG carries +this under 1.3.0's "Upgrading from 1.2.0". There is no forwarding shim: a type-forward from +`MetaObjects.Codegen` would need the reference this change removes. + +## Publishing + +`MetaObjects.AspNetCore` joins the lockstep C# set: `publish-csharp.yml`, `scripts/prerelease.mjs` +and `docs/RELEASING.md` pack five packages. diff --git a/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json index 2d0a306469..c5e90b11e0 100644 --- a/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json +++ b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json @@ -3,7 +3,7 @@ "generated/csharp/SubscriberBlurbPayload.g.cs": "29eb3a6ce64496ffe734cba55d0213994316b4281d3fa6791917393bae36c9ed", "generated/csharp/SubscriberFilterAllowlist.g.cs": "3839b04884e4e393d4f7d7bf4c7d4fe5b3852bd3a92b1ecb282cb8935a3c98e5", "generated/csharp/SubscriberNames.g.cs": "c2cf0248c2ecde155ec2623604771e39bed23783603d6f18a2ed82967227a732", - "generated/csharp/SubscriberRoutes.g.cs": "2a217ff5a37674ce5038802631b1d8fd90b22b9849e0288f7daf3bba7f9e862f", + "generated/csharp/SubscriberRoutes.g.cs": "ed026b1eb5209acacdaaf69f517a15a113bb9c924dd2e7cddb9beb8f40fc7080", "generated/python/Subscriber.py": "9dd4c0acea47f99d1daf79930f9de2e400f30780ebce6c63f023be528a72b762", "generated/python/SubscriberBlurbPayload.py": "a5ef8a08e63efbe0f73e39a21a368cff5150c68cc8beeea6e8aab0c755f8bbdd", "generated/python/subscriber_filter_allowlist.py": "1762fb8b41516c9ca4d4384563046b73c25ed681e4e5da3db19d7d290f9e8b25", diff --git a/examples/showcase/generated/csharp/SubscriberRoutes.g.cs b/examples/showcase/generated/csharp/SubscriberRoutes.g.cs index 859eb0d48f..d9fda7bde7 100644 --- a/examples/showcase/generated/csharp/SubscriberRoutes.g.cs +++ b/examples/showcase/generated/csharp/SubscriberRoutes.g.cs @@ -6,7 +6,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.EntityFrameworkCore; -using MetaObjects.Codegen.Runtime; +using MetaObjects.AspNetCore; namespace Acme; diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/csharp.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/csharp.md index 06cfdda9e1..73f2e2b3a1 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/csharp.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/csharp.md @@ -24,6 +24,7 @@ Per the always-on descriptor: ```bash dotnet tool install --global MetaObjects.Cli # provides `dotnet meta` dotnet add package MetaObjects.Codegen # the codegen generators +dotnet add package MetaObjects.AspNetCore # in the app: the helpers generated routes call dotnet meta init # writes codegen/: Generators.cs, Program.cs, Codegen.csproj ``` diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-runtime-ui/references/csharp.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-runtime-ui/references/csharp.md index 6fd985d885..e65702a006 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-runtime-ui/references/csharp.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-runtime-ui/references/csharp.md @@ -96,8 +96,8 @@ app.Run(); Filter operators (`eq` `ne` `gt` `gte` `lt` `lte` `in` `like` `isNull`) ship via the per-entity `FilterAllowlist` (from `FilterAllowlistGenerator`); the generated list -handler calls the `FilterParser` / `EfCoreFilterDispatch` runtime helpers in -`MetaObjects.Codegen`, so your ASP.NET host references that assembly at runtime. After +handler calls the `FilterParser` / `EfCoreFilterDispatch` runtime helpers in the +`MetaObjects.AspNetCore` package, so your ASP.NET host references that package. After `dotnet meta eject routes` it calls your own copies in `codegen/runtime/` (namespace `Codegen.Runtime`) instead: compile that folder into the app and the reference goes away. The same universal TS/Angular web client consumes those routes unchanged — the wire format matches diff --git a/scripts/prerelease.mjs b/scripts/prerelease.mjs index a0c5c9b0ec..905e94720e 100644 --- a/scripts/prerelease.mjs +++ b/scripts/prerelease.mjs @@ -404,13 +404,14 @@ if (wants("csharp")) { // No file edit needed — dotnet takes the version on the command line. const out = scratch("nupkg"); const projs = ["MetaObjects/MetaObjects", "MetaObjects.Render/MetaObjects.Render", - "MetaObjects.Codegen/MetaObjects.Codegen", "MetaObjects.Cli/MetaObjects.Cli"]; + "MetaObjects.Codegen/MetaObjects.Codegen", "MetaObjects.AspNetCore/MetaObjects.AspNetCore", + "MetaObjects.Cli/MetaObjects.Cli"]; for (const p of projs) await run(`cd server/csharp && dotnet pack ${p}.csproj -c Release -o ${out} -p:Version=${V.nuget} --nologo -v q`); - ok(`csharp packed ${V.nuget} (4 packages)`); + ok(`csharp packed ${V.nuget} (${projs.length} packages)`); begin("csharp"); if (!DRY) { await run(`dotnet nuget push "${out}/*.nupkg" --source "${NUGET_SRC}" --api-key "${TOKEN}"`); - ok(`csharp: 4 packages @ ${V.nuget} → ${expectedHost}`); + ok(`csharp: ${projs.length} packages @ ${V.nuget} → ${expectedHost}`); } else ok("csharp: dry run, nothing published"); if (!DRY) published.push("csharp"); } diff --git a/server/csharp/MetaObjects.Codegen/Runtime/ConstraintErrors.cs b/server/csharp/MetaObjects.AspNetCore/ConstraintErrors.cs similarity index 99% rename from server/csharp/MetaObjects.Codegen/Runtime/ConstraintErrors.cs rename to server/csharp/MetaObjects.AspNetCore/ConstraintErrors.cs index 3cdeb1818f..7eb15877d1 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/ConstraintErrors.cs +++ b/server/csharp/MetaObjects.AspNetCore/ConstraintErrors.cs @@ -38,7 +38,7 @@ // command text or parameter collection — so the matched text cannot carry user data into // a classification decision. -namespace MetaObjects.Codegen.Runtime; +namespace MetaObjects.AspNetCore; /// The constraint kinds worth telling a client apart. public enum ConstraintKind diff --git a/server/csharp/MetaObjects.Codegen/Runtime/DecimalRangeEndpointFilter.cs b/server/csharp/MetaObjects.AspNetCore/DecimalRangeEndpointFilter.cs similarity index 98% rename from server/csharp/MetaObjects.Codegen/Runtime/DecimalRangeEndpointFilter.cs rename to server/csharp/MetaObjects.AspNetCore/DecimalRangeEndpointFilter.cs index 6d36bb5275..b0f01a16c7 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/DecimalRangeEndpointFilter.cs +++ b/server/csharp/MetaObjects.AspNetCore/DecimalRangeEndpointFilter.cs @@ -12,7 +12,7 @@ using Microsoft.AspNetCore.Http; -namespace MetaObjects.Codegen.Runtime; +namespace MetaObjects.AspNetCore; /// Turns a driver's decimal-overflow-on-read into 500 {"error":"decimal_out_of_range"}. public sealed class DecimalRangeEndpointFilter : IEndpointFilter diff --git a/server/csharp/MetaObjects.Codegen/Runtime/DecimalWire.cs b/server/csharp/MetaObjects.AspNetCore/DecimalWire.cs similarity index 99% rename from server/csharp/MetaObjects.Codegen/Runtime/DecimalWire.cs rename to server/csharp/MetaObjects.AspNetCore/DecimalWire.cs index c587c91a09..18713efbc3 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/DecimalWire.cs +++ b/server/csharp/MetaObjects.AspNetCore/DecimalWire.cs @@ -27,7 +27,7 @@ using System.Text.Json; using System.Text.Json.Serialization; -namespace MetaObjects.Codegen.Runtime; +namespace MetaObjects.AspNetCore; /// The canonical wire form of a decimal: format, parse, and the System.Text.Json converters. public static class DecimalWire diff --git a/server/csharp/MetaObjects.Codegen/Runtime/DurationWire.cs b/server/csharp/MetaObjects.AspNetCore/DurationWire.cs similarity index 99% rename from server/csharp/MetaObjects.Codegen/Runtime/DurationWire.cs rename to server/csharp/MetaObjects.AspNetCore/DurationWire.cs index 6676b6d739..b071dfc022 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/DurationWire.cs +++ b/server/csharp/MetaObjects.AspNetCore/DurationWire.cs @@ -30,7 +30,7 @@ using System.Text.Json; using System.Text.Json.Serialization; -namespace MetaObjects.Codegen.Runtime; +namespace MetaObjects.AspNetCore; /// The canonical wire form of a duration: format, parse, and the System.Text.Json converters. public static class DurationWire diff --git a/server/csharp/MetaObjects.Codegen/Runtime/EfCoreFilterDispatch.cs b/server/csharp/MetaObjects.AspNetCore/EfCoreFilterDispatch.cs similarity index 99% rename from server/csharp/MetaObjects.Codegen/Runtime/EfCoreFilterDispatch.cs rename to server/csharp/MetaObjects.AspNetCore/EfCoreFilterDispatch.cs index 9e0b11e998..76b8a3f546 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/EfCoreFilterDispatch.cs +++ b/server/csharp/MetaObjects.AspNetCore/EfCoreFilterDispatch.cs @@ -26,7 +26,7 @@ using System.Reflection; using Microsoft.EntityFrameworkCore; -namespace MetaObjects.Codegen.Runtime; +namespace MetaObjects.AspNetCore; /// /// Apply a list of to an diff --git a/server/csharp/MetaObjects.Codegen/Runtime/FilterParseResult.cs b/server/csharp/MetaObjects.AspNetCore/FilterParseResult.cs similarity index 97% rename from server/csharp/MetaObjects.Codegen/Runtime/FilterParseResult.cs rename to server/csharp/MetaObjects.AspNetCore/FilterParseResult.cs index 7c0bc62c15..3dcc552792 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/FilterParseResult.cs +++ b/server/csharp/MetaObjects.AspNetCore/FilterParseResult.cs @@ -5,7 +5,7 @@ // Part of the codegen runtime surface; mirrors Java codegen-spring's // runtime/FilterParseResult.java. -namespace MetaObjects.Codegen.Runtime; +namespace MetaObjects.AspNetCore; /// /// Result of . Exactly one of diff --git a/server/csharp/MetaObjects.Codegen/Runtime/FilterParser.cs b/server/csharp/MetaObjects.AspNetCore/FilterParser.cs similarity index 99% rename from server/csharp/MetaObjects.Codegen/Runtime/FilterParser.cs rename to server/csharp/MetaObjects.AspNetCore/FilterParser.cs index 6f02d9d8cd..4bc26e3569 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/FilterParser.cs +++ b/server/csharp/MetaObjects.AspNetCore/FilterParser.cs @@ -12,7 +12,7 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Http; -namespace MetaObjects.Codegen.Runtime; +namespace MetaObjects.AspNetCore; /// /// Parses the cross-port FR-009 filter URL grammar diff --git a/server/csharp/MetaObjects.Codegen/Runtime/FilterPredicate.cs b/server/csharp/MetaObjects.AspNetCore/FilterPredicate.cs similarity index 96% rename from server/csharp/MetaObjects.Codegen/Runtime/FilterPredicate.cs rename to server/csharp/MetaObjects.AspNetCore/FilterPredicate.cs index abefec8cf2..a9a45eefe6 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/FilterPredicate.cs +++ b/server/csharp/MetaObjects.AspNetCore/FilterPredicate.cs @@ -6,7 +6,7 @@ // runtime in their ASP.NET Core host. Mirrors Java codegen-spring's // runtime/FilterPredicate.java. -namespace MetaObjects.Codegen.Runtime; +namespace MetaObjects.AspNetCore; /// /// A single parsed + validated filter predicate from the FR-009 URL grammar diff --git a/server/csharp/MetaObjects.Codegen/Runtime/Iso8601TimestampConverter.cs b/server/csharp/MetaObjects.AspNetCore/Iso8601TimestampConverter.cs similarity index 98% rename from server/csharp/MetaObjects.Codegen/Runtime/Iso8601TimestampConverter.cs rename to server/csharp/MetaObjects.AspNetCore/Iso8601TimestampConverter.cs index 1f5d6689d1..ea4b09a072 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/Iso8601TimestampConverter.cs +++ b/server/csharp/MetaObjects.AspNetCore/Iso8601TimestampConverter.cs @@ -27,7 +27,7 @@ using System.Text.Json; using System.Text.Json.Serialization; -namespace MetaObjects.Codegen.Runtime; +namespace MetaObjects.AspNetCore; /// /// Reads and writes in the api contract's wire spelling: diff --git a/server/csharp/MetaObjects.AspNetCore/MetaObjects.AspNetCore.csproj b/server/csharp/MetaObjects.AspNetCore/MetaObjects.AspNetCore.csproj new file mode 100644 index 0000000000..b3b9a980f5 --- /dev/null +++ b/server/csharp/MetaObjects.AspNetCore/MetaObjects.AspNetCore.csproj @@ -0,0 +1,20 @@ + + + net8.0 + enable + enable + 12 + true + MetaObjects.AspNetCore + MetaObjects.AspNetCore + MetaObjects.AspNetCore + The helper runtime the routes MetaObjects generates for ASP.NET Core call: the filter parser, the EF Core filter dispatch, validation and constraint-error mapping, and the decimal, duration and timestamp wire forms. Your app references it; the MetaObjects.Codegen package and the dotnet meta tool do not. `dotnet meta eject routes` copies this source into your repository to own. + + + + + + + diff --git a/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs b/server/csharp/MetaObjects.AspNetCore/ReportExportHttp.cs similarity index 99% rename from server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs rename to server/csharp/MetaObjects.AspNetCore/ReportExportHttp.cs index cac15e692b..9730a78532 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs +++ b/server/csharp/MetaObjects.AspNetCore/ReportExportHttp.cs @@ -19,7 +19,7 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Http; -namespace MetaObjects.Codegen.Runtime; +namespace MetaObjects.AspNetCore; /// Format selection, refusals and attachment responses for a report export. public static class ReportExportHttp diff --git a/server/csharp/MetaObjects.Codegen/Runtime/SerializerKeys.cs b/server/csharp/MetaObjects.AspNetCore/SerializerKeys.cs similarity index 99% rename from server/csharp/MetaObjects.Codegen/Runtime/SerializerKeys.cs rename to server/csharp/MetaObjects.AspNetCore/SerializerKeys.cs index 092d670e19..6e71131b4a 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/SerializerKeys.cs +++ b/server/csharp/MetaObjects.AspNetCore/SerializerKeys.cs @@ -16,7 +16,7 @@ using System.Text.Json.Nodes; using System.Text.Json.Serialization.Metadata; -namespace MetaObjects.Codegen.Runtime; +namespace MetaObjects.AspNetCore; public static class SerializerKeys { diff --git a/server/csharp/MetaObjects.Codegen/Runtime/UnknownFieldCheck.cs b/server/csharp/MetaObjects.AspNetCore/UnknownFieldCheck.cs similarity index 98% rename from server/csharp/MetaObjects.Codegen/Runtime/UnknownFieldCheck.cs rename to server/csharp/MetaObjects.AspNetCore/UnknownFieldCheck.cs index b77d291afe..fc6bbbbd61 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/UnknownFieldCheck.cs +++ b/server/csharp/MetaObjects.AspNetCore/UnknownFieldCheck.cs @@ -15,7 +15,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; -namespace MetaObjects.Codegen.Runtime; +namespace MetaObjects.AspNetCore; /// The unknown-field refusal of a generated write route. public static class UnknownFieldCheck diff --git a/server/csharp/MetaObjects.Codegen/Runtime/ValidationIssues.cs b/server/csharp/MetaObjects.AspNetCore/ValidationIssues.cs similarity index 99% rename from server/csharp/MetaObjects.Codegen/Runtime/ValidationIssues.cs rename to server/csharp/MetaObjects.AspNetCore/ValidationIssues.cs index 27067a5bd3..56e613473d 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/ValidationIssues.cs +++ b/server/csharp/MetaObjects.AspNetCore/ValidationIssues.cs @@ -23,7 +23,7 @@ using System.Text.Json.Serialization; using Microsoft.AspNetCore.Http; -namespace MetaObjects.Codegen.Runtime; +namespace MetaObjects.AspNetCore; /// An ordered, de-duplicated list of validation issues, and the 400 response that carries it. public sealed class ValidationIssues diff --git a/server/csharp/MetaObjects.Codegen/Runtime/ValueObjectValidator.cs b/server/csharp/MetaObjects.AspNetCore/ValueObjectValidator.cs similarity index 99% rename from server/csharp/MetaObjects.Codegen/Runtime/ValueObjectValidator.cs rename to server/csharp/MetaObjects.AspNetCore/ValueObjectValidator.cs index 5796838a9e..af6cd38b2a 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/ValueObjectValidator.cs +++ b/server/csharp/MetaObjects.AspNetCore/ValueObjectValidator.cs @@ -21,7 +21,7 @@ using System.ComponentModel.DataAnnotations; using System.Reflection; -namespace MetaObjects.Codegen.Runtime; +namespace MetaObjects.AspNetCore; /// /// Recursive value-object graph validator for generated CRUD handlers (Program D). diff --git a/server/csharp/MetaObjects.Cli.Tests/VerifySubverbTests.cs b/server/csharp/MetaObjects.Cli.Tests/VerifySubverbTests.cs index 0fcc7c3112..3a514234d0 100644 --- a/server/csharp/MetaObjects.Cli.Tests/VerifySubverbTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/VerifySubverbTests.cs @@ -233,6 +233,41 @@ public void Codegen_with_pagination_set_has_no_advisory() Assert.Empty(r.Advisories); } + [Fact] + public void Codegen_routes_in_a_project_without_the_helper_package_warn_and_keep_exit0() + { + File.WriteAllText(Path.Combine(MetaDir, "meta.ai.json"), EntityMetadata); + File.WriteAllText(Path.Combine(_tmp, "App.csproj"), """ + + + + """); + var gen = GenSuite.Run(MetaDir, OutDir, "Acme.Generated"); + var genWarning = Assert.Single(gen.Result!.Warnings, w => w.Contains(HelperRuntime.PackageId)); + Assert.Contains("SubscriberRoutes.g.cs imports MetaObjects.AspNetCore", genWarning); + + var r = VerifyCommand.RunSubverbs(TemplatesOpts(templates: false, codegen: true)); + Assert.Equal(0, r.ExitCode); + var warning = Assert.Single(r.Advisories, a => a.Contains(HelperRuntime.PackageId)); + Assert.Contains("App.csproj", warning); + Assert.Contains(" + + + """); + GenSuite.Run(MetaDir, OutDir, "Acme.Generated"); + + var r = VerifyCommand.RunSubverbs(TemplatesOpts(templates: false, codegen: true)); + Assert.DoesNotContain(r.Advisories, a => a.Contains(HelperRuntime.PackageId)); + } + [Fact] public void Codegen_without_a_routes_generator_has_no_advisory() { diff --git a/server/csharp/MetaObjects.Cli/EjectCommand.cs b/server/csharp/MetaObjects.Cli/EjectCommand.cs index d10edd8e4e..cae34ac968 100644 --- a/server/csharp/MetaObjects.Cli/EjectCommand.cs +++ b/server/csharp/MetaObjects.Cli/EjectCommand.cs @@ -347,7 +347,7 @@ public static Outcome Undo(IReadOnlyList names, string root, bool force) if (runtimeRemoved) lines.Add($"The helper runtime copy is gone: drop the `` " + $"line from the project that compiled it, and register the timestamp converter from " + - $"`{HelperRuntime.PackagedNamespace}` again."); + $"`{HelperRuntime.PackagedNamespace}` again (the app needs its {HelperRuntime.PackageId} package reference back)."); return new Outcome(0, lines, []); } @@ -438,7 +438,7 @@ private static List EjectRuntime(string root, IReadOnlyList user lines.Add($" /{HelperRuntime.OwnedDirectory}/**/*.cs\" />"); lines.Add( $"and register the timestamp converter from `{HelperRuntime.OwnedNamespace}` rather than " + - $"`{HelperRuntime.PackagedNamespace}`. The generated routes then need no MetaObjects.Codegen " + + $"`{HelperRuntime.PackagedNamespace}`. The generated routes then need no {HelperRuntime.PackageId} " + "reference. codegen/Codegen.csproj must not compile runtime/ " + "(``; a scaffold written by this version already has it)."); return lines; diff --git a/server/csharp/MetaObjects.Cli/VerifyCommand.cs b/server/csharp/MetaObjects.Cli/VerifyCommand.cs index 3b6e911fbe..978bad46bd 100644 --- a/server/csharp/MetaObjects.Cli/VerifyCommand.cs +++ b/server/csharp/MetaObjects.Cli/VerifyCommand.cs @@ -524,6 +524,9 @@ private static Codegen.CodegenDrift.Result RunCodegenDrift(Options opts, List $"warning: {w}")); return Codegen.CodegenDrift.Compute(config, load.Root, generators); } diff --git a/server/csharp/MetaObjects.Codegen.Tests/ApiSettingsTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ApiSettingsTests.cs index 996472129d..33e2b35b09 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ApiSettingsTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ApiSettingsTests.cs @@ -4,7 +4,7 @@ using MetaObjects.Codegen; using MetaObjects.Codegen.Generators; -using MetaObjects.Codegen.Runtime; +using MetaObjects.AspNetCore; using Microsoft.AspNetCore.Http; using System.Text.Json; using MetaObjects.Config; diff --git a/server/csharp/MetaObjects.Codegen.Tests/ConstraintErrorsTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ConstraintErrorsTests.cs index 72fa0d7e5e..293f389a72 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ConstraintErrorsTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ConstraintErrorsTests.cs @@ -11,7 +11,7 @@ // EF wrapper text is likewise real: DbUpdateException's own message says nothing about // the constraint, which is exactly why the chain walk is load-bearing. -using MetaObjects.Codegen.Runtime; +using MetaObjects.AspNetCore; using Xunit; namespace MetaObjects.Codegen.Tests; diff --git a/server/csharp/MetaObjects.Codegen.Tests/DecimalWireTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DecimalWireTests.cs index 2fb9c28173..afc4eabc28 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/DecimalWireTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/DecimalWireTests.cs @@ -1,6 +1,6 @@ // ADR-0019 Amendment 1 (W1-W4) — the C# half of the decimal wire rule, gated against the // shared vectors in fixtures/decimal-wire/vectors.json. No database: the production wire -// helper (Runtime/DecimalWire.cs, the SAME text the entity generator emits into every +// helper (MetaObjects.AspNetCore/DecimalWire.cs, the SAME text the entity generator emits into every // generated project) runs every vector, and the emitted text is proven identical to it. // The HTTP bytes and the read path are gated by the api-contract and persistence lanes. @@ -11,7 +11,7 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using MetaObjects.Codegen.Generators; -using MetaObjects.Codegen.Runtime; +using MetaObjects.AspNetCore; using MetaObjects.Loader; using MetaObjects.Meta; using Xunit; @@ -221,12 +221,12 @@ public void The_emitted_helper_is_the_production_helper_with_only_the_namespace_ var emitted = files.Where(f => f.Path == "DecimalWire.g.cs").ToList(); Assert.NotEmpty(emitted); var production = File.ReadAllText(Path.Combine( - CorpusPaths.RepoRoot(), "server", "csharp", "MetaObjects.Codegen", "Runtime", "DecimalWire.cs")).Replace("\r\n", "\n"); + CorpusPaths.RepoRoot(), "server", "csharp", "MetaObjects.AspNetCore", "DecimalWire.cs")).Replace("\r\n", "\n"); foreach (var f in emitted) { var ns = f.Content.Split('\n').First(l => l.StartsWith("namespace ", StringComparison.Ordinal)); Assert.Equal( - production.Replace("namespace MetaObjects.Codegen.Runtime;", ns), + production.Replace("namespace MetaObjects.AspNetCore;", ns), f.Content.Replace("\r\n", "\n")); Assert.DoesNotContain("MetaObjects", ns.Replace("namespace ", ""), StringComparison.Ordinal); } diff --git a/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs index f3dbb7d6c5..8a4ee58f01 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs @@ -1,6 +1,6 @@ // field.duration — the C# half of the duration wire rule, gated against the shared vectors in // fixtures/duration-wire/vectors.json. No database: the production wire helper -// (Runtime/DurationWire.cs, the SAME text the entity generator emits into every generated project) +// (MetaObjects.AspNetCore/DurationWire.cs, the SAME text the entity generator emits into every generated project) // runs every `wire` vector (the `precision` ones at seven digits: a TimeSpan tick is 100 ns), and // the emitted text is proven identical to it. Of the `codecs` groups C# has two in production: // `storedMicros` (the generated value converter on SQLite and MySQL, here) and the Postgres read @@ -13,7 +13,7 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using MetaObjects.Codegen.Generators; -using MetaObjects.Codegen.Runtime; +using MetaObjects.AspNetCore; using MetaObjects.Core.Query; using MetaObjects.Loader; using MetaObjects.Meta; @@ -254,8 +254,8 @@ public void The_emitted_helper_is_the_production_helper_with_only_the_namespace_ { var emitted = Emit().Single(f => f.Path == "DurationWire.g.cs"); var production = File.ReadAllText(Path.Combine( - CorpusPaths.RepoRoot(), "server", "csharp", "MetaObjects.Codegen", "Runtime", "DurationWire.cs")).Replace("\r\n", "\n"); - Assert.Equal(production.Replace("namespace MetaObjects.Codegen.Runtime;", "namespace Acme.Ops;"), emitted.Content.Replace("\r\n", "\n")); + CorpusPaths.RepoRoot(), "server", "csharp", "MetaObjects.AspNetCore", "DurationWire.cs")).Replace("\r\n", "\n"); + Assert.Equal(production.Replace("namespace MetaObjects.AspNetCore;", "namespace Acme.Ops;"), emitted.Content.Replace("\r\n", "\n")); } [Fact] diff --git a/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs index 51d0bc3bdb..2788d7b726 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs @@ -317,7 +317,7 @@ public void Ejected_alone_it_emits_what_the_packaged_generator_emits_byte_for_by SharedModelTestSupport.Configure(alone.Generator); // The ONE documented difference: a generator whose output imports the helper runtime imports the // adopter's owned copy once ejected — `using Codegen.Runtime;` where the packaged output says - // `using MetaObjects.Codegen.Runtime;`. Nothing else. + // `using MetaObjects.AspNetCore;`. Nothing else. var usesRuntime = HelperRuntime.UsedBy(EjectableGenerators.ReadSource(name)!); string Expected(string content) => usesRuntime ? content.Replace($"using {HelperRuntime.PackagedNamespace};", $"using {HelperRuntime.OwnedNamespace};", StringComparison.Ordinal) diff --git a/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs index c0e7c6425e..4f22d94f01 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs @@ -144,12 +144,12 @@ public void Routes_generator_list_handler_calls_FilterParser() { // FR-009: the generated list handler must parse filter[...] qs against // the per-entity allowlist + dispatch via EfCoreFilterDispatch. Both - // are runtime helpers shipped under MetaObjects.Codegen.Runtime. + // are runtime helpers shipped in the MetaObjects.AspNetCore package. var ctx = Ctx(Load()); var src = Assert.Single(new RoutesGenerator().Generate(ctx)).Content; // Imports the runtime namespace. - Assert.Contains("using MetaObjects.Codegen.Runtime;", src); + Assert.Contains("using MetaObjects.AspNetCore;", src); // Parses filter against the per-entity allowlist. Assert.Contains("FilterParser.Parse(qs, SubscriberFilterAllowlist.Fields, SubscriberFilterAllowlist.OpsByField)", src); // 400 envelope on parse error — carries `field`, which every filter envelope diff --git a/server/csharp/MetaObjects.Codegen.Tests/ExtractObjectArrayBoundsTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ExtractObjectArrayBoundsTests.cs index 85c9bb0984..d9a25ab7ab 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ExtractObjectArrayBoundsTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ExtractObjectArrayBoundsTests.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Linq; +using MetaObjects.AspNetCore; using MetaObjects.Codegen.Runtime; using MetaObjects.Loader; using MetaObjects.Meta; diff --git a/server/csharp/MetaObjects.Codegen.Tests/ExtractObjectVerdictTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ExtractObjectVerdictTests.cs index 2c41c4e521..543f98192f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ExtractObjectVerdictTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ExtractObjectVerdictTests.cs @@ -12,6 +12,7 @@ using System.Collections.Generic; using System.Linq; +using MetaObjects.AspNetCore; using MetaObjects.Codegen.Runtime; using MetaObjects.Loader; using MetaObjects.Meta; diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs index 132ec1aedf..defa7656c5 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs @@ -6,7 +6,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.EntityFrameworkCore; -using MetaObjects.Codegen.Runtime; +using MetaObjects.AspNetCore; namespace Acme.Shop; diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs index 3b3d1aba9b..e7c30d8cfe 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs @@ -6,7 +6,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.EntityFrameworkCore; -using MetaObjects.Codegen.Runtime; +using MetaObjects.AspNetCore; namespace Acme.Shop; diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs index 4e83b30597..b205dcd0e2 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs @@ -6,7 +6,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.EntityFrameworkCore; -using MetaObjects.Codegen.Runtime; +using MetaObjects.AspNetCore; namespace Acme.Shop; diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs index 852e0ed6dd..3b5ecec733 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs @@ -6,7 +6,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.EntityFrameworkCore; -using MetaObjects.Codegen.Runtime; +using MetaObjects.AspNetCore; namespace Acme.Shop; diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs index be66505058..5860168767 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs @@ -6,7 +6,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.EntityFrameworkCore; -using MetaObjects.Codegen.Runtime; +using MetaObjects.AspNetCore; namespace Acme.Shop; diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs index e15592ead1..5eb0e0811a 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs @@ -6,7 +6,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.EntityFrameworkCore; -using MetaObjects.Codegen.Runtime; +using MetaObjects.AspNetCore; namespace Acme.Shop; diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs index 2bb6099be9..570c51e30a 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs @@ -6,7 +6,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.EntityFrameworkCore; -using MetaObjects.Codegen.Runtime; +using MetaObjects.AspNetCore; namespace Acme.Shop; diff --git a/server/csharp/MetaObjects.Codegen.Tests/HelperRuntimeReferenceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/HelperRuntimeReferenceTests.cs new file mode 100644 index 0000000000..688e8a15ca --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/HelperRuntimeReferenceTests.cs @@ -0,0 +1,111 @@ +// 1.3.0 — the helper runtime generated routes call moved out of MetaObjects.Codegen into the +// MetaObjects.AspNetCore package. HelperRuntimeReference warns when the project compiling a +// generated file that imports it does not reference that package, and stays silent otherwise. + +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public sealed class HelperRuntimeReferenceTests : IDisposable +{ + private readonly string _tmp = Path.Combine(Path.GetTempPath(), "mo-helper-ref-" + Guid.NewGuid().ToString("N")); + + private const string Importing = "// \nusing MetaObjects.AspNetCore;\nnamespace Acme;\n"; + + public HelperRuntimeReferenceTests() => Directory.CreateDirectory(_tmp); + + public void Dispose() { try { Directory.Delete(_tmp, recursive: true); } catch { } } + + private string Write(string relative, string content) + { + var path = Path.Combine(_tmp, relative.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content); + return path; + } + + private static string Project(string items) => + $"\n \n {items}\n \n\n"; + + private IReadOnlyList Check(params string[] files) => + HelperRuntimeReference.Warnings(files.Select(f => (f, File.ReadAllText(f)))); + + [Fact] + public void A_project_without_the_package_gets_one_warning_naming_the_line_to_add() + { + Write("app/App.csproj", Project("")); + var a = Write("app/Generated/ARoutes.g.cs", Importing); + var b = Write("app/Generated/BRoutes.g.cs", Importing); + + var warning = Assert.Single(Check(a, b)); + Assert.Contains("and 1 other generated file(s) import MetaObjects.AspNetCore", warning); + Assert.Contains("App.csproj does not reference the MetaObjects.AspNetCore package", warning); + Assert.Contains("")] + [InlineData("")] + [InlineData("")] + public void A_direct_reference_is_enough(string item) + { + Write("app/App.csproj", Project(item)); + Assert.Empty(Check(Write("app/Generated/ARoutes.g.cs", Importing))); + } + + [Fact] + public void A_reference_through_a_referenced_project_is_enough() + { + Write("shared/Shared.csproj", Project("")); + Write("app/App.csproj", Project("")); + Assert.Empty(Check(Write("app/Generated/ARoutes.g.cs", Importing))); + } + + [Fact] + public void A_reference_in_a_directory_build_props_above_is_enough() + { + Write("Directory.Build.props", Project("")); + Write("app/App.csproj", Project("")); + Assert.Empty(Check(Write("app/Generated/ARoutes.g.cs", Importing))); + } + + [Fact] + public void No_project_or_no_import_is_silent() + { + Assert.Empty(Check(Write("loose/ARoutes.g.cs", Importing))); + Write("app/App.csproj", Project("")); + Assert.Empty(Check(Write("app/Generated/Entity.g.cs", "// \nnamespace Acme;\n"))); + } + + [Fact] + public void Output_that_still_imports_the_helpers_from_their_old_namespace_warns() + { + Write("app/App.csproj", Project("")); + var stale = Write("app/Generated/ARoutes.g.cs", + "// \nusing MetaObjects.Codegen.Runtime;\nclass A { object f = FilterParser.Parse; }\n"); + var warning = Assert.Single(Check(stale)); + Assert.Contains("imports MetaObjects.Codegen.Runtime", warning); + Assert.Contains("HelperRuntimeNamespace", warning); + } + + [Fact] + public void The_old_namespace_for_the_core_reply_parser_alone_is_silent() + { + Write("app/App.csproj", Project("")); + Assert.Empty(Check(Write("app/Generated/Parser.g.cs", + "// \nusing MetaObjects.Codegen.Runtime;\nclass P { object f = ExtractObject.Extract; }\n"))); + } + + [Fact] + public void ForTrees_reads_only_generated_files_and_skips_build_output() + { + Write("app/App.csproj", Project("")); + Write("app/Generated/Hand.cs", "using MetaObjects.AspNetCore;\n"); + Write("app/Generated/obj/Stale.g.cs", Importing); + Assert.Empty(HelperRuntimeReference.ForTrees([Path.Combine(_tmp, "app", "Generated")])); + + Write("app/Generated/ARoutes.g.cs", Importing); + var warning = Assert.Single(HelperRuntimeReference.ForTrees([Path.Combine(_tmp, "app", "Generated")], _tmp)); + Assert.StartsWith("app/Generated/ARoutes.g.cs imports", warning); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/HelperRuntimeTests.cs b/server/csharp/MetaObjects.Codegen.Tests/HelperRuntimeTests.cs index a3eb6146d2..b47095c827 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/HelperRuntimeTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/HelperRuntimeTests.cs @@ -1,7 +1,8 @@ // ADR-0034 Amendment 3 — the helper runtime `dotnet meta eject routes` hands over with the // generator (MetaObjects.Codegen.HelperRuntime). These tests gate: -// 1. the embedded copies are byte-identical to Runtime/ and match HelperRuntime.Files; -// 2. every Runtime/ file is classified helper (copied) or core (stays in the package); +// 1. the embedded copies are byte-identical to MetaObjects.AspNetCore/ and match HelperRuntime.Files; +// 2. every MetaObjects.AspNetCore/ file is a helper (copied) and every MetaObjects.Codegen/Runtime/ +// file is core (stays in MetaObjects.Codegen); // 3. the helper set is CLOSED — it compiles on its own, with no MetaObjects assembly; // 4. an ejected routes generator's output compiles against the OWNED copy with no // MetaObjects assembly referenced at all, and binds to that copy: break the copy and @@ -17,6 +18,9 @@ namespace MetaObjects.Codegen.Tests; public class HelperRuntimeTests { private static string RuntimeDir() => + Path.Combine(CorpusPaths.RepoRoot(), "server", "csharp", "MetaObjects.AspNetCore"); + + private static string CoreRuntimeDir() => Path.Combine(CorpusPaths.RepoRoot(), "server", "csharp", "MetaObjects.Codegen", "Runtime"); private static string Normalize(string s) => s.Replace("\r\n", "\n"); @@ -27,7 +31,7 @@ public void Embedded_copies_are_byte_identical_to_their_source_files() foreach (var file in HelperRuntime.Files) Assert.True( Normalize(HelperRuntime.ReadSourceFile(file)) == Normalize(File.ReadAllText(Path.Combine(RuntimeDir(), file))), - $"embedded Runtime/{file} diverges from its source file — rebuild MetaObjects.Codegen."); + $"embedded MetaObjects.AspNetCore/{file} diverges from its source file — rebuild MetaObjects.Codegen."); } [Fact] @@ -43,11 +47,12 @@ public void Embedded_resource_set_matches_HelperRuntime_Files_exactly() [Fact] public void Every_runtime_file_is_classified_helper_or_core_and_never_both() { - // A new Runtime/ file must be put on one side of the line on purpose: copied to an - // adopter who ejects, or kept in the package as core. - var onDisk = Directory.GetFiles(RuntimeDir(), "*.cs").Select(Path.GetFileName).OrderBy(n => n, StringComparer.Ordinal); - var classified = HelperRuntime.Files.Concat(HelperRuntime.CoreFiles).OrderBy(n => n, StringComparer.Ordinal); - Assert.Equal(classified, onDisk); + // A new runtime file must be put on one side of the line on purpose: a helper in + // MetaObjects.AspNetCore, copied to an adopter who ejects, or core in MetaObjects.Codegen. + static IEnumerable CsFiles(string dir) => + Directory.GetFiles(dir, "*.cs").Select(Path.GetFileName).OrderBy(n => n, StringComparer.Ordinal); + Assert.Equal(HelperRuntime.Files.OrderBy(n => n, StringComparer.Ordinal), CsFiles(RuntimeDir())); + Assert.Equal(HelperRuntime.CoreFiles.OrderBy(n => n, StringComparer.Ordinal), CsFiles(CoreRuntimeDir())); Assert.Empty(HelperRuntime.Files.Intersect(HelperRuntime.CoreFiles)); } diff --git a/server/csharp/MetaObjects.Codegen.Tests/Iso8601TimestampConverterTests.cs b/server/csharp/MetaObjects.Codegen.Tests/Iso8601TimestampConverterTests.cs index 37587e1fa8..ec8665dafd 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Iso8601TimestampConverterTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Iso8601TimestampConverterTests.cs @@ -8,7 +8,7 @@ // different answers. using System.Text.Json; -using MetaObjects.Codegen.Runtime; +using MetaObjects.AspNetCore; using Xunit; namespace MetaObjects.Codegen.Tests; diff --git a/server/csharp/MetaObjects.Codegen.Tests/MetaObjects.Codegen.Tests.csproj b/server/csharp/MetaObjects.Codegen.Tests/MetaObjects.Codegen.Tests.csproj index b57be70108..c4baeac22e 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/MetaObjects.Codegen.Tests.csproj +++ b/server/csharp/MetaObjects.Codegen.Tests/MetaObjects.Codegen.Tests.csproj @@ -23,6 +23,7 @@ instead of hand-copying it a second time (a hand-copy that drifted silently is the reason this reference exists — see CodegenDriftTests.cs). --> + - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/DecimalWireGeneratedApiTests.cs b/server/csharp/MetaObjects.IntegrationTests/Api/DecimalWireGeneratedApiTests.cs index f8da8b0fe3..abffa8525b 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/DecimalWireGeneratedApiTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/DecimalWireGeneratedApiTests.cs @@ -112,12 +112,12 @@ public async Task W4_a_sqlite_read_of_a_double_is_exact_to_15_digits() cmd.CommandText = "SELECT 0.1 + 0.2, 1.0 / 3, 123456789012345680.0, 12.5"; await using var r = await cmd.ExecuteReaderAsync(); Assert.True(await r.ReadAsync()); - Assert.Equal("0.3", MetaObjects.Codegen.Runtime.DecimalWire.Format(r.GetDecimal(0))); - Assert.Equal("0.333333333333333", MetaObjects.Codegen.Runtime.DecimalWire.Format(r.GetDecimal(1))); - Assert.Equal("123456789012346000", MetaObjects.Codegen.Runtime.DecimalWire.Format(r.GetDecimal(2))); - Assert.Equal("12.5", MetaObjects.Codegen.Runtime.DecimalWire.Format(r.GetDecimal(3))); + Assert.Equal("0.3", MetaObjects.AspNetCore.DecimalWire.Format(r.GetDecimal(0))); + Assert.Equal("0.333333333333333", MetaObjects.AspNetCore.DecimalWire.Format(r.GetDecimal(1))); + Assert.Equal("123456789012346000", MetaObjects.AspNetCore.DecimalWire.Format(r.GetDecimal(2))); + Assert.Equal("12.5", MetaObjects.AspNetCore.DecimalWire.Format(r.GetDecimal(3))); // ...which is what the helper's own W4 rendering says for the same doubles. - Assert.Equal(r.GetDecimal(0), MetaObjects.Codegen.Runtime.DecimalWire.FromDouble15(0.1 + 0.2)); + Assert.Equal(r.GetDecimal(0), MetaObjects.AspNetCore.DecimalWire.FromDouble15(0.1 + 0.2)); } [Fact] diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/JsonbGeneratedServerFactory.cs b/server/csharp/MetaObjects.IntegrationTests/Api/JsonbGeneratedServerFactory.cs index fe61423832..d03f5cc548 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/JsonbGeneratedServerFactory.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/JsonbGeneratedServerFactory.cs @@ -62,7 +62,7 @@ public static async Task StartAsync(PostgresContain // The documented host registration: a field.timestamp crosses the wire as UTC with the Z // designator (a Telemetry value object holds one). builder.Services.ConfigureHttpJsonOptions(o => - o.SerializerOptions.Converters.Add(new MetaObjects.Codegen.Runtime.Iso8601TimestampConverter())); + o.SerializerOptions.Converters.Add(new MetaObjects.AspNetCore.Iso8601TimestampConverter())); var app = builder.Build(); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/JsonbReferenceServer.cs b/server/csharp/MetaObjects.IntegrationTests/Api/JsonbReferenceServer.cs index 5f695c663b..367b6d977f 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/JsonbReferenceServer.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/JsonbReferenceServer.cs @@ -23,7 +23,7 @@ using System.Text; using System.Text.Json; using System.Text.Json.Nodes; -using MetaObjects.Codegen.Runtime; +using MetaObjects.AspNetCore; using MetaObjects.IntegrationTests.Runner; using Npgsql; using NpgsqlTypes; diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/TphReferenceServer.cs b/server/csharp/MetaObjects.IntegrationTests/Api/TphReferenceServer.cs index dca01ef17b..414e43b6bf 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/TphReferenceServer.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/TphReferenceServer.cs @@ -22,7 +22,7 @@ using System.Text; using System.Text.Json; using System.Text.Json.Nodes; -using MetaObjects.Codegen.Runtime; +using MetaObjects.AspNetCore; using MetaObjects.IntegrationTests.Runner; using Npgsql; diff --git a/server/csharp/MetaObjects.IntegrationTests/MetaObjects.IntegrationTests.csproj b/server/csharp/MetaObjects.IntegrationTests/MetaObjects.IntegrationTests.csproj index f36edeb8d1..0c867eb711 100644 --- a/server/csharp/MetaObjects.IntegrationTests/MetaObjects.IntegrationTests.csproj +++ b/server/csharp/MetaObjects.IntegrationTests/MetaObjects.IntegrationTests.csproj @@ -53,4 +53,7 @@ + + + diff --git a/server/csharp/MetaObjects.IntegrationTests/Runner/DbContextAdapter.cs b/server/csharp/MetaObjects.IntegrationTests/Runner/DbContextAdapter.cs index 507086333e..4aabe189e2 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Runner/DbContextAdapter.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Runner/DbContextAdapter.cs @@ -369,7 +369,7 @@ private static IQueryable ApplySort(IQueryable queryable, IReadOnlyList // A decimal operand is exact: the string form (plain or exponent notation) parses through the // shipped wire rule, never through a double. if (underlying == typeof(decimal)) - return MetaObjects.Codegen.Runtime.DecimalWire.TryParse(raw.ToString(), out var exact) + return MetaObjects.AspNetCore.DecimalWire.TryParse(raw.ToString(), out var exact) ? exact : throw new FormatException($"not a decimal: {raw}"); return Convert.ChangeType(raw, underlying, System.Globalization.CultureInfo.InvariantCulture); diff --git a/server/csharp/MetaObjects.IntegrationTests/Runner/Normalization.cs b/server/csharp/MetaObjects.IntegrationTests/Runner/Normalization.cs index 55122fac0c..cc8f4b04a2 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Runner/Normalization.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Runner/Normalization.cs @@ -78,7 +78,7 @@ string js when TryParseJsonContainer(js, out var node) => NormalizeJsonContainer IPAddress ip => ip.ToString(), // field.duration (System.TimeSpan — Npgsql reads an interval as one) renders its canonical // ISO-8601 wire form: hours never folded into days, at most six fractional digits. - TimeSpan span => MetaObjects.Codegen.Runtime.DurationWire.Format(span), + TimeSpan span => MetaObjects.AspNetCore.DurationWire.Format(span), byte[] bytes => Convert.ToBase64String(bytes), // A pre-parsed JsonNode (assembled by a runner path) — sort keys. // (JsonDocument/JsonElement from a @dbColumnType:jsonb column are handled above.) diff --git a/server/csharp/MetaObjects.IntegrationTests/Runner/WriteCoercion.cs b/server/csharp/MetaObjects.IntegrationTests/Runner/WriteCoercion.cs index 2ec42b8bae..5ce62b13d7 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Runner/WriteCoercion.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Runner/WriteCoercion.cs @@ -87,13 +87,13 @@ public static PropertyInfo Property(Type entity, string fieldName) => if (underlying == typeof(double)) return double.Parse(raw, NumberStyles.Float, CultureInfo.InvariantCulture); if (underlying == typeof(float)) return float.Parse(raw, NumberStyles.Float, CultureInfo.InvariantCulture); if (underlying == typeof(decimal)) - return MetaObjects.Codegen.Runtime.DecimalWire.TryParse(raw, out var exact) + return MetaObjects.AspNetCore.DecimalWire.TryParse(raw, out var exact) ? exact : throw new FormatException($"not a decimal: {raw}"); // field.duration → System.TimeSpan from the ISO-8601 authoring form (Npgsql binds a // TimeSpan as interval natively; elsewhere the context's converter stores its microsecond count). if (underlying == typeof(TimeSpan)) - return MetaObjects.Codegen.Runtime.DurationWire.TryParse(raw, out var span) + return MetaObjects.AspNetCore.DurationWire.TryParse(raw, out var span) ? span : throw new FormatException($"not an ISO-8601 duration: {raw}"); if (underlying == typeof(DateOnly)) return ParseDate(raw); diff --git a/server/csharp/MetaObjects.sln b/server/csharp/MetaObjects.sln index 1cf5e3c4a3..63edf95fb9 100644 --- a/server/csharp/MetaObjects.sln +++ b/server/csharp/MetaObjects.sln @@ -21,6 +21,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MetaObjects.Cli.Tests", "Me EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MetaObjects.TestVocabulary", "MetaObjects.TestVocabulary\MetaObjects.TestVocabulary.csproj", "{07E0DCA5-F951-44CA-9660-3C30E7EBA30B}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MetaObjects.AspNetCore", "MetaObjects.AspNetCore\MetaObjects.AspNetCore.csproj", "{A2286DE2-2C92-4D9D-B03A-3E48992F0A4C}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -66,5 +68,9 @@ Global {07E0DCA5-F951-44CA-9660-3C30E7EBA30B}.Debug|Any CPU.Build.0 = Debug|Any CPU {07E0DCA5-F951-44CA-9660-3C30E7EBA30B}.Release|Any CPU.ActiveCfg = Release|Any CPU {07E0DCA5-F951-44CA-9660-3C30E7EBA30B}.Release|Any CPU.Build.0 = Release|Any CPU + {A2286DE2-2C92-4D9D-B03A-3E48992F0A4C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A2286DE2-2C92-4D9D-B03A-3E48992F0A4C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A2286DE2-2C92-4D9D-B03A-3E48992F0A4C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A2286DE2-2C92-4D9D-B03A-3E48992F0A4C}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal diff --git a/server/csharp/README.md b/server/csharp/README.md index ace9ce1131..080ffb4565 100644 --- a/server/csharp/README.md +++ b/server/csharp/README.md @@ -56,6 +56,7 @@ The test suite includes per-fixture `Lint` and `Conformance` theories over the s - `ConformanceAdapter.cs`, `FixtureDiscovery.cs`, `OperationScript.cs`, `FixtureLint.cs`, `Navigator.cs`, `CapabilityBinding.cs`, `Result.cs`, `ExpectedFailures.cs`, `conformance-expected-failures.json`, `ConformanceTests.cs` - `YamlConformanceTests.cs`, `YamlDesugarTests.cs`, `yaml-conformance-expected-failures.json` — YAML conformance + unit tests - Per-pipeline-stage unit tests (`ErrorsTests`, `RegistryTests`, `TreeTests`, `ParserTests`, `SerializerTests`, `LoaderTests`, `SuperResolveTests`, `ValidationTests`, …) +- `MetaObjects.AspNetCore/` — the helper runtime generated routes call (filter parser, EF Core filter dispatch, validation, wire forms); the app references it, `MetaObjects.Codegen` and the tool do not - `MetaObjects.Codegen/` — the .NET emit pipeline (`Generators/` holds entity, db-context, routes, payload, filter-allowlist, output-parser/prompt, extractor, template) + `CodegenRunner`, `GeneratorRegistry`, `CodegenDrift` - `MetaObjects.Render/` — Mustache render, payload value objects, `verify` - `MetaObjects.Cli/` — the `dotnet meta` tool (`init`, `gen`, `eject`, `verify`, `fmt`) From 8e47b9c005824cfc09d7fd7e0fa2555f25dbed99 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 21:56:56 -0500 Subject: [PATCH 2/9] feat(csharp): a list with no limit answers 50 rows (D11-CS) A generated entity, TPH or projection list in a project that sets no api.pagination returned every row when the request carried no limit. It now answers the first 50 (ApiSettings.DefaultPageLimit), the default of every port; an explicit limit is served as asked. Without the setting a malformed limit or offset is 400 pagination.invalid_value and limit=0 is an empty page, as with it. The dotnet meta verify --codegen advisory unbounded-list-pages is retired. The C# generated lane runs the shared list-query sub-corpus: the paging and refusal scenarios the routes answer today; search, or/and and the named refusals are listed by name until R-CS. Docs, upgrade guide, CHANGELOG, goldens and the showcase routes file follow. --- CHANGELOG.md | 11 ++ docs/CONFORMANCE.md | 4 +- docs/features/api-contract.md | 13 +- docs/features/language-differences.md | 2 +- .../migrations/default-list-page-of-fifty.md | 14 +- docs/ports/csharp.md | 8 +- .../.metaobjects/.gen-state/.hashes/acme.json | 2 +- .../generated/csharp/SubscriberRoutes.g.cs | 13 +- fixtures/api-contract-conformance/README.md | 2 +- .../list-query/README.md | 9 +- .../VerifySubverbTests.cs | 23 +-- .../csharp/MetaObjects.Cli/VerifyCommand.cs | 17 -- .../Golden/pre-rc22-propname/GizmoRoutes.g.cs | 13 +- .../Golden/pre-rc22-propname/LineRoutes.g.cs | 13 +- .../Golden/pre-rc22-propname/TagRoutes.g.cs | 13 +- .../pre-rc22-propname/VehicleRoutes.g.cs | 39 +++- .../pre-rc22-propname/VehicleTagRoutes.g.cs | 13 +- .../WidgetSummaryRoutes.g.cs | 13 +- .../PropertyNamingGoldenTests.cs | 6 +- .../Generators/RoutesGenerator.cs | 47 ++--- .../Api/ApiContractCorpusPaths.cs | 7 +- .../ApiContractListQueryConformanceTest.cs | 122 ++++++++++++ .../Api/ApiContractScenarios.cs | 8 +- .../Api/ListQueryFixture.cs | 61 ++++++ .../Api/ListQueryGeneratedServerFactory.cs | 174 ++++++++++++++++++ server/csharp/MetaObjects/Meta/ApiSettings.cs | 8 +- 26 files changed, 548 insertions(+), 107 deletions(-) create mode 100644 server/csharp/MetaObjects.IntegrationTests/Api/ApiContractListQueryConformanceTest.cs create mode 100644 server/csharp/MetaObjects.IntegrationTests/Api/ListQueryFixture.cs create mode 100644 server/csharp/MetaObjects.IntegrationTests/Api/ListQueryGeneratedServerFactory.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index d2b0aedb82..431881317f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,17 @@ here.** ## [Unreleased] +- **C#: a list with no `limit` answers 50 rows (breaking).** A generated entity, TPH or projection + list route in a project that sets no `api.pagination` returned every matching row when the + request carried no `limit`; it now answers the first 50 (`ApiSettings.DefaultPageLimit`), as every + port does. An explicit `limit` is still served as asked (no maximum without the setting), and a + project that sets `api.pagination` is unchanged. Without the setting a `limit` or `offset` that is + not a non-negative integer is now `400 pagination.invalid_value` instead of being ignored, and + `limit=0` is a page of zero rows. The `dotnet meta verify --codegen` advisory `unbounded-list-pages` + is retired. The C# generated lane now runs the shared `list-query/` sub-corpus: the paging and + refusal scenarios its routes answer today, with search and `or`/`and` to follow. Regenerate, and + check any client that reads a whole list without a `limit`: + [docs/features/migrations/default-list-page-of-fifty.md](docs/features/migrations/default-list-page-of-fifty.md). - **C#: the route helpers are their own package, `MetaObjects.AspNetCore`, and `MetaObjects.Codegen` and the `dotnet meta` tool no longer carry EF Core.** `FilterParser`, `FilterParseResult`, `FilterPredicate`, `EfCoreFilterDispatch`, `ValueObjectValidator`, `ConstraintErrors`, diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index e0f346a4e4..3f6a1d9d19 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -36,7 +36,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`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/) | 68 (56 query + 12 migration) | all 68; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` and `guarded-update` also on MySQL (a scenario's `engines:` key is exact) | 55 query (migrations TS-only, ADR-0015; `guarded-update` deferred to L-JV-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (via Exposed; `guarded-update` deferred to L-KT-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (`guarded-update` deferred to L-CS-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (pg8000; `guarded-update` deferred to L-PY-2); the `report-*` and `engines:` scenarios also on SQLite (`sqlite3`) and MySQL (PyMySQL) | -| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 179 (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 + 21 list-query + 17 rules) | ✓ (Fastify reference + generated lane; service lanes on Fastify and Hono for the entity, `projection/`, `report/`, `write-through/`, `tph/`, `m2m/`, `decimal/` and `secret-fields/` sub-corpora, see the [api-contract README](../fixtures/api-contract-conformance/README.md#ts-lanes-illustrative-detail)); `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, and `rules/` until each port's 1.3.0 service 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/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 179 (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 + 21 list-query + 17 rules) | ✓ (Fastify reference + generated lane; service lanes on Fastify and Hono for the entity, `projection/`, `report/`, `write-through/`, `tph/`, `m2m/`, `decimal/` and `secret-fields/` sub-corpora, see the [api-contract README](../fixtures/api-contract-conformance/README.md#ts-lanes-illustrative-detail)); `report/`, `decimal/` and `duration/` also on SQLite, MySQL and D1; `list-query/` runs in full in TypeScript and in part in C# (the paging and refusal scenarios its routes answer today; the rest with its 1.3.0 REST-standard work), and in no other port until that port's 1.3.0 REST-standard work; `rules/` is TypeScript-only until each port's 1.3.0 service 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`) | @@ -548,7 +548,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`), `rules/` (17, ADR-0066 through a generated service: derived and declared commands, a query, permission points, the three 409 codes, a declared error and a refusal rolling back, under the default settings and three `rules.*` variants; generated lane, TypeScript only until each port's 1.3.0 service work), `list-query/` (21, 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, a default page of 50, 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, +`api.unknownFields: drop`), `rules/` (17, ADR-0066 through a generated service: derived and declared commands, a query, permission points, the three 409 codes, a declared error and a refusal rolling back, under the default settings and three `rules.*` variants; generated lane, TypeScript only until each port's 1.3.0 service work), `list-query/` (21, 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, a default page of 50, paging past 50, and the `invalid_json`, `invalid_id`, `pagination.invalid_value` and `constraint_violation` refusals; generated lane, TypeScript in full and C# in part 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, diff --git a/docs/features/api-contract.md b/docs/features/api-contract.md index 6521738391..80b2ecc66e 100644 --- a/docs/features/api-contract.md +++ b/docs/features/api-contract.md @@ -323,13 +323,12 @@ each handler they register instead; an `HTTPException` is rethrown to your **Without the setting a list still pages: 50 rows, and no maximum.** With `limit` omitted, a list answers the first **50** matching rows (`list-query/default-page-of-fifty`, over a 60-row seed), and no port caps an explicit `limit` on an entity (`limit=100000` is honoured as asked). - The Java, Kotlin and Python controllers have always answered 50; the TypeScript mounts did so - from 1.3.0 (before, they returned **every** matching row), and the C# routes still return every - row until the same change lands there. A client that read a whole list with no `limit` now gets - the first page: send `limit`, or page with `offset` and `withCount=1`. `meta verify` no longer - advises `unbounded-list-pages`; `metaobjects verify`, `mvn metaobjects:verify` (Java and Kotlin) - and `dotnet meta verify --codegen` still name a wired routes generator with no page size (never - a failure). + The Java, Kotlin and Python controllers have always answered 50; the TypeScript mounts and the + C# routes do so from 1.3.0 (before, they returned **every** matching row). A client that read a + whole list with no `limit` now gets the first page: send `limit`, or page with `offset` and + `withCount=1`. `meta verify` and `dotnet meta verify --codegen` no longer advise + `unbounded-list-pages`; `metaobjects verify` and `mvn metaobjects:verify` (Java and Kotlin) + still name a wired routes generator with no page size (never a failure). **Every port reads it:** the TypeScript Fastify and Hono routes, the C# minimal-API routes, the Java and Kotlin Spring controllers and the Python FastAPI routers, packaged and ejected (an owned diff --git a/docs/features/language-differences.md b/docs/features/language-differences.md index 1324109fe2..7b6335709f 100644 --- a/docs/features/language-differences.md +++ b/docs/features/language-differences.md @@ -34,7 +34,7 @@ project. | **Generated data access** | Drizzle tables and row types (`entityFile()`), CRUD queries (`queriesFile()`) | EF Core entities and `AppDbContext` | Spring DTOs and a repository interface | Exposed tables and a repository base | None: the generated router calls a repository `Protocol` you implement | | **Runtime metadata access** | `ObjectManager` on Kysely (`@metaobjectsdev/runtime-ts`) | None yet (roadmap) | OMDB (JDBC, Spring transactions) | Through Java's OMDB | `ObjectManager` on DB-API 2; not wired to the generated router | | **Generated REST routes** | Fastify (`routesFile()`; Hono and Drizzle mounts in `runtime-ts`) | ASP.NET minimal API | Spring `@RestController` | Spring `@RestController` | FastAPI `APIRouter` | -| **List with no `limit` and no `api.pagination`** | The first 50 (every matching row before 1.3.0) | Every matching row | The first 50 | The first 50 | The first 50 | +| **List with no `limit` and no `api.pagination`** | The first 50 (every matching row before 1.3.0) | The first 50 (every matching row before 1.3.0) | The first 50 | The first 50 | The first 50 | | **Largest report page** | 10,000 rows, then 400 `report_too_large` | Same | Same | Same | Same | | **`api.pagination`, `api.unknownFields`, the validation `issues` list** | The same in every port; defined once in [api-contract.md](api-contract.md) ([page size](api-contract.md#sort--pagination), [unknown fields](api-contract.md#unknown-request-fields-apiunknownfields), [validation issues](api-contract.md#a-validation-error-lists-every-issue)) | | | | | | **Filter and sort errors** | 400 with `field`, plus `op`, `expected` and the allowed fields | 400 with `field` | 400 with `field` | 400 with `field` | 400 with `field` | diff --git a/docs/features/migrations/default-list-page-of-fifty.md b/docs/features/migrations/default-list-page-of-fifty.md index 8f0eab05a5..a4eab9c163 100644 --- a/docs/features/migrations/default-list-page-of-fifty.md +++ b/docs/features/migrations/default-list-page-of-fifty.md @@ -1,8 +1,9 @@ # Migration — a list with no `limit` answers 50 rows (`1.3.0`) -**TypeScript only; check any client that reads a whole list.** A generated list route (entity -or projection, on the Fastify, Hono and ObjectManager mounts) in a project that sets no -`api.pagination` used to answer **every** matching row when the request carried no `limit`. +**TypeScript and C#; check any client that reads a whole list.** A generated list route (entity +or projection, on the Fastify, Hono and ObjectManager mounts, and the C# minimal-API entity, TPH and +projection routes) in a project that sets no `api.pagination` used to answer **every** matching row +when the request carried no `limit`. From 1.3.0 it answers the first **50**, as the Java, Kotlin and Python routes always have. An explicit `limit` is still served as asked: without `api.pagination` there is no maximum. @@ -15,13 +16,16 @@ shipped) sees no change: its `defaultLimit` and `maxLimit` apply as before. |---|---| | `GET /api/items` returns the whole table | it returns 50 rows; send `?limit=N`, or page with `offset` and `withCount=1` | | a client that reads `rows.length` as the total | read `total` from `?withCount=1` | -| `meta verify` advises `unbounded-list-pages` | the advisory is gone: the lists are bounded | +| `meta verify` or `dotnet meta verify --codegen` advises `unbounded-list-pages` | the advisory is gone: the lists are bounded | +| C#: `?limit=abc` or `?offset=-1` is ignored | it is `400 pagination.invalid_value`, as it already was with `api.pagination` set | The generated TanStack list hooks are not affected: the grid hook always sends a `limit`. **An owned runtime copy** (copied by `meta eject routes` or `meta eject routes-hono`) keeps the behaviour of the copy you took. Take a fresh copy with `meta eject routes --force` (or `routes-hono`) to get the default, or change `pageLimit` in your -copy's `drizzle-fastify/list-params.ts`. +copy's `drizzle-fastify/list-params.ts`. In C#, an owned copy of the routes generator (`dotnet meta eject +routes`) keeps writing what it wrote; take a fresh copy with `--force`, or change `WriteOffsetLimit` in it. +Regenerate (`dotnet meta gen`) to move the packaged routes onto the default. To keep a larger default page, set it: diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 9c52d2fcd9..8a81720cbf 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -1256,10 +1256,10 @@ the route binds the body (the app's System.Text.Json options). What each setting [api-contract](../features/api-contract.md) ([page size](../features/api-contract.md#sort--pagination), [unknown fields](../features/api-contract.md#unknown-request-fields-apiunknownfields)). `dotnet meta init` writes `.metaobjects/config.json` with the same new-project settings as `meta init`: `api.pagination` 50/1000, `api.unknownFields: reject`, `verify.handEdits: fail` and -`migrate.foreignKeyIndexes: true`; an existing config is left alone. `dotnet meta verify --codegen` prints a -non-failing advisory (`unbounded-list-pages`, stderr, exit code unchanged) when the run includes the routes -generator and the project sets no `api.pagination`; plain `verify` says nothing, because only `--codegen` -runs the generator list. +`migrate.foreignKeyIndexes: true`; an existing config is left alone. A project that sets no `api.pagination` +still pages: a list with no `limit` answers the first 50 rows (`ApiSettings.DefaultPageLimit`, the default of +every port) and an explicit `limit` is served as asked, with no maximum. A bound that is not a non-negative +integer is `400 pagination.invalid_value` with or without the setting. **Known gaps** (full list with workarounds in [KNOWN_GAPS.md](https://github.com/metaobjectsdev/metaobjects/blob/main/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md)): diff --git a/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json index c5e90b11e0..a5f024b591 100644 --- a/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json +++ b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json @@ -3,7 +3,7 @@ "generated/csharp/SubscriberBlurbPayload.g.cs": "29eb3a6ce64496ffe734cba55d0213994316b4281d3fa6791917393bae36c9ed", "generated/csharp/SubscriberFilterAllowlist.g.cs": "3839b04884e4e393d4f7d7bf4c7d4fe5b3852bd3a92b1ecb282cb8935a3c98e5", "generated/csharp/SubscriberNames.g.cs": "c2cf0248c2ecde155ec2623604771e39bed23783603d6f18a2ed82967227a732", - "generated/csharp/SubscriberRoutes.g.cs": "ed026b1eb5209acacdaaf69f517a15a113bb9c924dd2e7cddb9beb8f40fc7080", + "generated/csharp/SubscriberRoutes.g.cs": "59cab9100550a5f947828adbed92f5f32d5f2207459a3a03180f8e761881dbee", "generated/python/Subscriber.py": "9dd4c0acea47f99d1daf79930f9de2e400f30780ebce6c63f023be528a72b762", "generated/python/SubscriberBlurbPayload.py": "a5ef8a08e63efbe0f73e39a21a368cff5150c68cc8beeea6e8aab0c755f8bbdd", "generated/python/subscriber_filter_allowlist.py": "1762fb8b41516c9ca4d4384563046b73c25ed681e4e5da3db19d7d290f9e8b25", diff --git a/examples/showcase/generated/csharp/SubscriberRoutes.g.cs b/examples/showcase/generated/csharp/SubscriberRoutes.g.cs index d9fda7bde7..66434bbb94 100644 --- a/examples/showcase/generated/csharp/SubscriberRoutes.g.cs +++ b/examples/showcase/generated/csharp/SubscriberRoutes.g.cs @@ -70,10 +70,19 @@ public static IEndpointRouteBuilder MapSubscriberRoutes(this IEndpointRouteBuild } // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (qs.TryGetValue("offset", out var offsetRawBad) && !(int.TryParse(offsetRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offsetBad) && offsetBad >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offsetRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) q = q.Skip(offset); - if (qs.TryGetValue("limit", out var limitRaw) && int.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit > 0) - q = q.Take(limit); + if (qs.TryGetValue("limit", out var limitRawNeg) && !(long.TryParse(limitRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limitNeg) && limitNeg >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limitRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. + var __take = 50; + if (qs.TryGetValue("limit", out var limitRaw) && long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit >= 0) + { + __take = (int)System.Math.Min(limit, int.MaxValue); + } + q = q.Take(__take); var rows = await q.ToListAsync(); diff --git a/fixtures/api-contract-conformance/README.md b/fixtures/api-contract-conformance/README.md index 9ab04340d2..666c111003 100644 --- a/fixtures/api-contract-conformance/README.md +++ b/fixtures/api-contract-conformance/README.md @@ -72,7 +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/` | 21 | 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, a default page of 50, 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 | +| `list-query/` | 21 | 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, a default page of 50, 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 in full; C# runs the scenarios its routes answer today (see the sub-corpus README); the other ports from their 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 | | `rules/` | 17 | ADR-0066 through a generated service: a derived transition command and its derived permission name, a declared `@permission`, 403 `forbidden`, the three 409 codes (`invalid_transition`, `transition_condition_failed`, `state_managed` on update and create), a declared command and its declared error, a `@public` command and query, a claimed transition with no command of its own, and a hook's and the event hook's refusal rolling the write back; `settings/` runs `rules.lifecycle.create: any` and `rules.lifecycle.commands: all` and `none` over the same model | generated only, TypeScript only until each port's 1.3.0 service work | diff --git a/fixtures/api-contract-conformance/list-query/README.md b/fixtures/api-contract-conformance/list-query/README.md index 741d9ec664..b6f7d3ee64 100644 --- a/fixtures/api-contract-conformance/list-query/README.md +++ b/fixtures/api-contract-conformance/list-query/README.md @@ -49,5 +49,10 @@ port's generated list route honours the REST standard; a hand-rolled reference s 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. +(one Postgres container for the file, reseeded before every scenario), and C# +`server/csharp/MetaObjects.IntegrationTests/Api/ApiContractListQueryConformanceTest.cs` (the +generated routes on Kestrel against Postgres). The C# runner names the scenarios its routes do +not answer yet (`NotYetInCSharp`: search, `or`/`and`, the bare-field and leading-`%` refusals, +`invalid_json` and `invalid_id`, which land with its 1.3.0 REST-standard work) and runs every +other one, the paging scenarios included. The other ports' runners arrive with their 1.3.0 +REST-standard work. diff --git a/server/csharp/MetaObjects.Cli.Tests/VerifySubverbTests.cs b/server/csharp/MetaObjects.Cli.Tests/VerifySubverbTests.cs index 3a514234d0..65859562c8 100644 --- a/server/csharp/MetaObjects.Cli.Tests/VerifySubverbTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/VerifySubverbTests.cs @@ -206,31 +206,16 @@ public void Codegen_clean_committed_output_is_exit0() } [Fact] - public void Codegen_with_routes_and_no_pagination_advises_and_keeps_exit0() + public void Codegen_with_routes_and_no_pagination_has_no_page_size_advisory() { + // A project without api.pagination pages at 50 (ApiSettings.DefaultPageLimit), so the retired + // unbounded-list-pages advisory is never printed. File.WriteAllText(Path.Combine(MetaDir, "meta.ai.json"), EntityMetadata); GenSuite.Run(MetaDir, OutDir, "Acme.Generated"); var r = VerifyCommand.RunSubverbs(TemplatesOpts(templates: false, codegen: true)); Assert.Equal(0, r.ExitCode); - Assert.Contains(r.Advisories, a => a.Contains("unbounded-list-pages")); - } - - [Fact] - public void Codegen_with_pagination_set_has_no_advisory() - { - File.WriteAllText(Path.Combine(MetaDir, "meta.ai.json"), EntityMetadata); - GenSuite.Run(MetaDir, OutDir, "Acme.Generated"); - - var opts = TemplatesOpts(templates: false, codegen: true); - var r = VerifyCommand.RunSubverbs(new VerifyCommand.Options - { - MetadataDir = opts.MetadataDir, Generators = opts.Generators, TemplatesRoot = opts.TemplatesRoot, - OutDir = opts.OutDir, Namespace = opts.Namespace, Codegen = true, Templates = false, - Api = new ApiSettings(new ApiPagination(50, 1000)), - }); - // (Exit is not asserted: the committed output was generated without a page size, so it drifts.) - Assert.Empty(r.Advisories); + Assert.DoesNotContain(r.Advisories, a => a.Contains("unbounded-list-pages")); } [Fact] diff --git a/server/csharp/MetaObjects.Cli/VerifyCommand.cs b/server/csharp/MetaObjects.Cli/VerifyCommand.cs index 978bad46bd..72de953d04 100644 --- a/server/csharp/MetaObjects.Cli/VerifyCommand.cs +++ b/server/csharp/MetaObjects.Cli/VerifyCommand.cs @@ -57,14 +57,6 @@ public sealed record Outcome( // ADR-0021 D2 — explicit verify subverbs (--templates / --codegen / --db). // ------------------------------------------------------------------------ - /// The name the generated-routes generator reports (RoutesGenerator.Name). - private const string RoutesGeneratorName = "routes-generator"; - - /// Advisory rule unbounded-list-pages: routes are generated and no api.pagination is set. - public const string UNBOUNDED_LIST_PAGES_ADVISORY = - "dotnet meta verify --codegen: advisory unbounded-list-pages: list routes return every row when `limit` is omitted; " + - "set `api.pagination` in .metaobjects/config.json (for example { \"defaultLimit\": 50, \"maxLimit\": 1000 })."; - /// The message printed when --db is requested in the C# port. public const string DB_NOT_SUPPORTED = "verify --db: schema drift is not supported in the C# port; schema verify is the " + @@ -490,15 +482,6 @@ private static Codegen.CodegenDrift.Result RunCodegenDrift(Options opts, List g is Codegen.Generators.RoutesGenerator || g.Name == RoutesGeneratorName) - && load.Root.Objects().Any(o => Codegen.Generators.RoutesGenerator.AppliesTo(o, load.Root))) - advisories.Add(UNBOUNDED_LIST_PAGES_ADVISORY); - // C1 — same presence gate `gen` computes (GeneratorRegistry.IncludesNames over // the SAME resolved `names` list above), or a regen under a `--generators` // selection that excludes `names` would reference `Names.*` while `gen` diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs index defa7656c5..2e6da47f10 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs @@ -80,10 +80,19 @@ public static IEndpointRouteBuilder MapGizmoRoutes(this IEndpointRouteBuilder ap } // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (qs.TryGetValue("offset", out var offsetRawBad) && !(int.TryParse(offsetRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offsetBad) && offsetBad >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offsetRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) q = q.Skip(offset); - if (qs.TryGetValue("limit", out var limitRaw) && int.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit > 0) - q = q.Take(limit); + if (qs.TryGetValue("limit", out var limitRawNeg) && !(long.TryParse(limitRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limitNeg) && limitNeg >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limitRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. + var __take = 50; + if (qs.TryGetValue("limit", out var limitRaw) && long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit >= 0) + { + __take = (int)System.Math.Min(limit, int.MaxValue); + } + q = q.Take(__take); var rows = await q.ToListAsync(); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs index e7c30d8cfe..d5a65005f9 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs @@ -65,10 +65,19 @@ public static IEndpointRouteBuilder MapLineRoutes(this IEndpointRouteBuilder app } // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (qs.TryGetValue("offset", out var offsetRawBad) && !(int.TryParse(offsetRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offsetBad) && offsetBad >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offsetRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) q = q.Skip(offset); - if (qs.TryGetValue("limit", out var limitRaw) && int.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit > 0) - q = q.Take(limit); + if (qs.TryGetValue("limit", out var limitRawNeg) && !(long.TryParse(limitRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limitNeg) && limitNeg >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limitRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. + var __take = 50; + if (qs.TryGetValue("limit", out var limitRaw) && long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit >= 0) + { + __take = (int)System.Math.Min(limit, int.MaxValue); + } + q = q.Take(__take); var rows = await q.ToListAsync(); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs index 3b5ecec733..425fb24538 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs @@ -65,10 +65,19 @@ public static IEndpointRouteBuilder MapTagRoutes(this IEndpointRouteBuilder app, } // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (qs.TryGetValue("offset", out var offsetRawBad) && !(int.TryParse(offsetRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offsetBad) && offsetBad >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offsetRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) q = q.Skip(offset); - if (qs.TryGetValue("limit", out var limitRaw) && int.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit > 0) - q = q.Take(limit); + if (qs.TryGetValue("limit", out var limitRawNeg) && !(long.TryParse(limitRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limitNeg) && limitNeg >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limitRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. + var __take = 50; + if (qs.TryGetValue("limit", out var limitRaw) && long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit >= 0) + { + __take = (int)System.Math.Min(limit, int.MaxValue); + } + q = q.Take(__take); var rows = await q.ToListAsync(); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs index 5860168767..85d49e8ff9 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs @@ -85,10 +85,19 @@ public static IEndpointRouteBuilder MapVehicleRoutes(this IEndpointRouteBuilder : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; q = ApplySort(q, resolved, desc); } + if (qs.TryGetValue("offset", out var offRawBad) && !(int.TryParse(offRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offBad) && offBad >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); if (qs.TryGetValue("offset", out var offRaw) && int.TryParse(offRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var off) && off > 0) q = q.Skip(off); - if (qs.TryGetValue("limit", out var limRaw) && int.TryParse(limRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim > 0) - q = q.Take(lim); + if (qs.TryGetValue("limit", out var limRawNeg) && !(long.TryParse(limRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limNeg) && limNeg >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. + var __take = 50; + if (qs.TryGetValue("limit", out var limRaw) && long.TryParse(limRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim >= 0) + { + __take = (int)System.Math.Min(lim, int.MaxValue); + } + q = q.Take(__take); var rows = await q.ToListAsync(); var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "VinHash" }); @@ -130,10 +139,19 @@ await db.Vehicles.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } fou : CarSortDefaultDesc.TryGetValue(resolved, out var dd) && dd; q = desc ? q.OrderByDescending(x => EF.Property(x!, resolved) == null).ThenByDescending(x => EF.Property(x!, resolved)) : q.OrderBy(x => EF.Property(x!, resolved) == null).ThenBy(x => EF.Property(x!, resolved)); } + if (qs.TryGetValue("offset", out var offRawBad) && !(int.TryParse(offRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offBad) && offBad >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); if (qs.TryGetValue("offset", out var offRaw) && int.TryParse(offRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var off) && off > 0) q = q.Skip(off); - if (qs.TryGetValue("limit", out var limRaw) && int.TryParse(limRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim > 0) - q = q.Take(lim); + if (qs.TryGetValue("limit", out var limRawNeg) && !(long.TryParse(limRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limNeg) && limNeg >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. + var __take = 50; + if (qs.TryGetValue("limit", out var limRaw) && long.TryParse(limRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim >= 0) + { + __take = (int)System.Math.Min(lim, int.MaxValue); + } + q = q.Take(__take); var rows = await q.ToListAsync(); var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "VinHash" }); @@ -296,10 +314,19 @@ async System.Threading.Tasks.Task UpdateCar(long id, HttpContext http, : VanSortDefaultDesc.TryGetValue(resolved, out var dd) && dd; q = desc ? q.OrderByDescending(x => EF.Property(x!, resolved) == null).ThenByDescending(x => EF.Property(x!, resolved)) : q.OrderBy(x => EF.Property(x!, resolved) == null).ThenBy(x => EF.Property(x!, resolved)); } + if (qs.TryGetValue("offset", out var offRawBad) && !(int.TryParse(offRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offBad) && offBad >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); if (qs.TryGetValue("offset", out var offRaw) && int.TryParse(offRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var off) && off > 0) q = q.Skip(off); - if (qs.TryGetValue("limit", out var limRaw) && int.TryParse(limRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim > 0) - q = q.Take(lim); + if (qs.TryGetValue("limit", out var limRawNeg) && !(long.TryParse(limRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limNeg) && limNeg >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. + var __take = 50; + if (qs.TryGetValue("limit", out var limRaw) && long.TryParse(limRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim >= 0) + { + __take = (int)System.Math.Min(lim, int.MaxValue); + } + q = q.Take(__take); var rows = await q.ToListAsync(); var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "VinHash" }); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs index 5eb0e0811a..6ebc47934f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs @@ -58,10 +58,19 @@ public static IEndpointRouteBuilder MapVehicleTagRoutes(this IEndpointRouteBuild } // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (qs.TryGetValue("offset", out var offsetRawBad) && !(int.TryParse(offsetRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offsetBad) && offsetBad >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offsetRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) q = q.Skip(offset); - if (qs.TryGetValue("limit", out var limitRaw) && int.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit > 0) - q = q.Take(limit); + if (qs.TryGetValue("limit", out var limitRawNeg) && !(long.TryParse(limitRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limitNeg) && limitNeg >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limitRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. + var __take = 50; + if (qs.TryGetValue("limit", out var limitRaw) && long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit >= 0) + { + __take = (int)System.Math.Min(limit, int.MaxValue); + } + q = q.Take(__take); var rows = await q.ToListAsync(); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs index 570c51e30a..bceb3090a7 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs @@ -57,10 +57,19 @@ public static IEndpointRouteBuilder MapWidgetSummaryRoutes(this IEndpointRouteBu } // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (qs.TryGetValue("offset", out var offsetRawBad) && !(int.TryParse(offsetRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offsetBad) && offsetBad >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offsetRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) q = q.Skip(offset); - if (qs.TryGetValue("limit", out var limitRaw) && int.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit > 0) - q = q.Take(limit); + if (qs.TryGetValue("limit", out var limitRawNeg) && !(long.TryParse(limitRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limitNeg) && limitNeg >= 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limitRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. + var __take = 50; + if (qs.TryGetValue("limit", out var limitRaw) && long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit >= 0) + { + __take = (int)System.Math.Min(limit, int.MaxValue); + } + q = q.Take(__take); var rows = await q.ToListAsync(); diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs index 0b86aace4d..e7b47d6aa1 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs @@ -3,8 +3,10 @@ // generators BEFORE the fix (de59161f5) and then re-captured ONLY where the credential-stripping security // fix legitimately changed the output: the four routes files (GizmoRoutes, VehicleRoutes, TagRoutes, // LineRoutes: the credential omit list, the strip helper call, the startup contract check and the PATCH key -// lookup). Callable, Extractor, ReportExport, FilterAllowlist and DbContext are still byte-identical to -// de59161f5. So with no resolver the output is unchanged except for that security change. +// lookup), and the routes files again for the 1.3.0 default page of 50 (a list with no `api.pagination` +// pages at 50 and refuses a malformed bound). Callable, Extractor, ReportExport, FilterAllowlist and +// DbContext are still byte-identical to de59161f5. So with no resolver the output is unchanged except +// for those two deliberate route changes. // // Capture (re-capture only for a deliberate, reviewed output change): GOLDEN_WRITE=1 dotnet test // --filter PropertyNamingGoldenTests. Compare mode is the default. diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index f09117e41f..3fd331a1a6 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -10,7 +10,8 @@ // (see docs/features/api-contract.md): // - GET list honours ?limit=N&offset=N pagination. With `api.pagination` set, no limit // takes `defaultLimit` and a limit above `maxLimit` is 400 { "error": "limit_too_large", -// "maxLimit": N }; without it, no limit returns every row. +// "maxLimit": N }; without it, no limit answers 50 rows (ApiSettings.DefaultPageLimit, +// the default of every port) and an explicit limit is served as asked. // - GET list honours ?sort=:asc|desc against a static SortAllowlist // derived from the entity's scalar fields (case-insensitive lookup). // Unknown field → 400 { "error": "invalid_sort", "field": ... }. @@ -1214,37 +1215,37 @@ protected virtual void WriteUnknownFieldsCheck(CsWriter w, MetaRoot root, string w.Line($"if (UnknownFieldCheck.Reject({bodyVar}.RootElement, {KnownFieldsConst}, http) is {{ }} __unknown) return __unknown;"); } - // The offset + limit lines of a list route. Without `api.pagination` they are exactly what they always - // were; with it, no limit takes defaultLimit and one above maxLimit is 400 limit_too_large. + // The offset + limit lines of a list route. A bound that is present but not a non-negative integer is + // refused (pagination.invalid_value), never read as "absent". No limit takes `api.pagination`'s + // defaultLimit, or ApiSettings.DefaultPageLimit (50, as in every port) when the project sets no block; + // with the block, a limit above maxLimit is 400 limit_too_large, and without it there is no maximum. protected virtual void WriteOffsetLimit(CsWriter w, ApiPagination? page, string offRaw, string off, string limRaw, string lim) { - if (page is not null) - { - // An offset that is present but not a non-negative int is refused, as the TypeScript routes answer, - // never read as "absent" and answered with a page the client did not ask for. - w.Line($"if (qs.TryGetValue(\"offset\", out var {offRaw}Bad) && !(int.TryParse({offRaw}Bad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {off}Bad) && {off}Bad >= 0))"); - using (w.Hanging()) w.Line($"return Results.BadRequest(new {{ error = \"pagination.invalid_value\", param = \"offset\", value = {offRaw}Bad.ToString(), expected = \"a non-negative integer (0 or more)\" }});"); - } + w.Line($"if (qs.TryGetValue(\"offset\", out var {offRaw}Bad) && !(int.TryParse({offRaw}Bad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {off}Bad) && {off}Bad >= 0))"); + using (w.Hanging()) w.Line($"return Results.BadRequest(new {{ error = \"pagination.invalid_value\", param = \"offset\", value = {offRaw}Bad.ToString(), expected = \"a non-negative integer (0 or more)\" }});"); w.Line($"if (qs.TryGetValue(\"offset\", out var {offRaw}) && int.TryParse({offRaw}, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {off}) && {off} > 0)"); using (w.Hanging()) w.Line($"q = q.Skip({off});"); - if (page is null) - { - w.Line($"if (qs.TryGetValue(\"limit\", out var {limRaw}) && int.TryParse({limRaw}, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {lim}) && {lim} > 0)"); - using (w.Hanging()) w.Line($"q = q.Take({lim});"); - return; - } - w.Line($"// api.pagination: no limit takes defaultLimit; a limit above maxLimit is refused."); - // A negative or non-numeric limit is refused with the malformed-bound envelope, as the TypeScript routes answer. w.Line($"if (qs.TryGetValue(\"limit\", out var {limRaw}Neg) && !(long.TryParse({limRaw}Neg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {lim}Neg) && {lim}Neg >= 0))"); using (w.Hanging()) w.Line($"return Results.BadRequest(new {{ error = \"pagination.invalid_value\", param = \"limit\", value = {limRaw}Neg.ToString(), expected = \"a non-negative integer (0 or more)\" }});"); - w.Line($"var __take = {page.DefaultLimit};"); + if (page is not null) + w.Line("// api.pagination: no limit takes defaultLimit; a limit above maxLimit is refused."); + else + w.Line("// No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked."); + w.Line($"var __take = {page?.DefaultLimit ?? ApiSettings.DefaultPageLimit};"); // `limit=0` is a page of zero rows, as every other port serves it, not "no limit". w.Line($"if (qs.TryGetValue(\"limit\", out var {limRaw}) && long.TryParse({limRaw}, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {lim}) && {lim} >= 0)"); w.Open("{"); - w.Line($"if ({lim} > {page.MaxLimit}) return Results.BadRequest(new {{ error = \"limit_too_large\", maxLimit = {page.MaxLimit} }});"); - w.Line($"__take = (int){lim};"); - w.Close($"}}"); - w.Line($"q = q.Take(__take);"); + if (page is not null) + { + w.Line($"if ({lim} > {page.MaxLimit}) return Results.BadRequest(new {{ error = \"limit_too_large\", maxLimit = {page.MaxLimit} }});"); + w.Line($"__take = (int){lim};"); + } + else + { + w.Line($"__take = (int)System.Math.Min({lim}, int.MaxValue);"); + } + w.Close("}"); + w.Line("q = q.Take(__take);"); } protected virtual void WriteCreateHandler( diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs index 323402f94f..45a72f0d17 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs @@ -128,5 +128,10 @@ internal static class ApiContractCorpusPaths public static readonly string EnumDefaultScenariosDir = Path.Combine(EnumDefaultDir, "scenarios"); public static readonly string EnumDefaultSeedFile = Path.Combine(EnumDefaultDir, "seed.json"); public static readonly string EnumDefaultMetaJson = Path.Combine(EnumDefaultDir, "meta.json"); -} + // list-query subcorpus (the REST standard's list handling over a 60-row Part seed), generated lane only. + public static readonly string ListQueryDir = Path.Combine(Corpus, "list-query"); + public static readonly string ListQueryScenariosDir = Path.Combine(ListQueryDir, "scenarios"); + public static readonly string ListQuerySeedFile = Path.Combine(ListQueryDir, "seed.json"); + public static readonly string ListQueryMetaJson = Path.Combine(ListQueryDir, "meta.json"); +} diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractListQueryConformanceTest.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractListQueryConformanceTest.cs new file mode 100644 index 0000000000..88402bfb60 --- /dev/null +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractListQueryConformanceTest.cs @@ -0,0 +1,122 @@ +// ApiContractListQueryConformanceTest — the C# list-query api-contract lane. +// +// Drives the fixtures/api-contract-conformance/list-query/ scenarios over HTTP against the +// GENERATED Part routes booted unmodified on Kestrel against a Postgres testcontainer, over the +// corpus's 60-row seed. Generated lane only, as the corpus README rules. +// +// The REST-standard work (search, or/and groups, the bare-field and leading-% refusals, the named +// error bodies) lands in C# with R-CS-1 and R-CS-2; until then those scenarios are listed in +// NotYetInCSharp, by name, and each one is checked to exist so the list cannot go stale. Every +// other scenario in the directory runs, so a new one is held to C# by default. + +using System.Text.Json; +using System.Text.Json.Nodes; +using MetaObjects.IntegrationTests.Runner; +using Xunit; + +namespace MetaObjects.IntegrationTests.Api; + +public sealed class ApiContractListQueryConformanceTest +{ + /// Scenarios the C# routes do not answer yet (the REST standard, R-CS-1 and R-CS-2). + internal static readonly IReadOnlySet NotYetInCSharp = new HashSet(StringComparer.Ordinal) + { + "and-inside-or", + "bare-field-not-filterable-refused", + "bare-field-refused", + "count-matches-the-filter", + "invalid-id", + "invalid-json", + "leading-wildcard-refused", + "nesting-at-the-cap", + "nesting-too-deep", + "or-beside-a-field", + "or-two-branches", + "search-is-case-insensitive", + "search-matches-every-text-field", + "search-with-filter", + }; + + [Theory] + [MemberData(nameof(Scenarios))] + public async Task Api_contract_list_query_generated(string scenarioPath) + { + var scenario = ApiContractScenarioLoader.LoadScenario(scenarioPath); + await using var pg = await PostgresContainer.StartAsync(); + await using var server = await ListQueryGeneratedServerFactory.StartAsync(pg); + await server.ApplySeedAsync(); + await RunAsync(scenario, server.BaseUrl); + } + + [Fact] + public void Every_scenario_not_yet_in_CSharp_exists() + { + var names = AllScenarioPaths().Select(Path.GetFileNameWithoutExtension).ToHashSet(StringComparer.Ordinal); + Assert.Empty(NotYetInCSharp.Where(n => !names.Contains(n))); + } + + private static IEnumerable AllScenarioPaths() => + Directory.EnumerateFiles(ApiContractCorpusPaths.ListQueryScenariosDir, "*.yaml", SearchOption.TopDirectoryOnly) + .OrderBy(p => p, StringComparer.Ordinal); + + public static IEnumerable Scenarios() => + AllScenarioPaths() + .Where(p => !NotYetInCSharp.Contains(Path.GetFileNameWithoutExtension(p))) + .Select(p => new object[] { p }); + + private static async Task RunAsync(ApiScenario scenario, string baseUrl) + { + using var client = new HttpClient { BaseAddress = new Uri(baseUrl) }; + foreach (var req in scenario.Requests) + { + var request = new HttpRequestMessage(new HttpMethod(req.Method), ApiContractWire.VerbatimUri(client, req.Path)); + if (req.RawBody is not null) + request.Content = new StringContent(req.RawBody, System.Text.Encoding.UTF8, "application/json"); + else if (req.Body is not null) + { + string json = JsonSerializer.Serialize(req.Body, JsonOpts); + request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); + } + var response = await client.SendAsync(request); + string bodyText = await response.Content.ReadAsStringAsync(); + object? parsed = null; + if (!string.IsNullOrEmpty(bodyText)) + { + try { parsed = ToObject(JsonNode.Parse(bodyText)); } + catch (JsonException) { parsed = bodyText; } // a non-JSON answer fails the body assertion, not the parse + } + ApiContractAssertions.AssertResponse(scenario.Name, req, (int)response.StatusCode, parsed); + } + } + + private static readonly JsonSerializerOptions JsonOpts = new() + { + DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.Never, + }; + + private static object? ToObject(JsonNode? node) + { + if (node is null) return null; + if (node is JsonObject obj) + { + var d = new Dictionary(StringComparer.Ordinal); + foreach (var kvp in obj) d[kvp.Key] = ToObject(kvp.Value); + return d; + } + if (node is JsonArray arr) + { + var l = new List(arr.Count); + foreach (var item in arr) l.Add(ToObject(item)); + return l; + } + if (node is JsonValue jv) + { + if (jv.TryGetValue(out var b)) return b; + if (jv.TryGetValue(out var lv)) return lv; + if (jv.TryGetValue(out var dv)) return dv; // exact: never a double (ADR-0019 Amendment 1) + if (jv.TryGetValue(out var sv)) return sv; + return jv.ToString(); + } + return null; + } +} diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractScenarios.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractScenarios.cs index be17887fa6..25b8fbef9f 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractScenarios.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractScenarios.cs @@ -20,7 +20,9 @@ public sealed record ApiRequest( // Report export (docs/features/api-contract.md, "Report export"): headers SENT with the request, // and `expect.headers` — lower-cased name -> exact value, null = the header is absent. IReadOnlyDictionary? Headers = null, - IReadOnlyDictionary? ExpectHeaders = null); + IReadOnlyDictionary? ExpectHeaders = null, + // `rawBody`: sent byte-for-byte as application/json (how a scenario sends a body that is not JSON). + string? RawBody = null); /// A scenario file (one *.yaml under scenarios/). public sealed record ApiScenario( @@ -151,7 +153,9 @@ private static ApiRequest ParseRequest(Dictionary r, string yam ExpectStatus: status, ExpectBody: expectBody, Headers: sentHeaders, - ExpectHeaders: expectHeaders); + ExpectHeaders: expectHeaders, + RawBody: r.TryGetValue("rawBody", out var raw) ? raw as string + ?? throw new InvalidOperationException($"{yamlPath}: 'rawBody' must be a string") : null); } /// diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ListQueryFixture.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ListQueryFixture.cs new file mode 100644 index 0000000000..1a9a572d59 --- /dev/null +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ListQueryFixture.cs @@ -0,0 +1,61 @@ +// ListQueryFixture — schema + seed for the list-query api-contract GENERATED lane +// (fixtures/api-contract-conformance/list-query/): one `parts` table with a unique `sku`, 60 rows. +using System.Text.Json.Nodes; +using Npgsql; + +namespace MetaObjects.IntegrationTests.Api; + +internal static class ListQueryFixture +{ + public const string SchemaDdl = """ + CREATE TABLE "parts" ( + "id" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, + "name" VARCHAR(100) NOT NULL, + "sku" VARCHAR(20) NOT NULL, + "category" TEXT NOT NULL, + "stock" INTEGER NOT NULL, + "notes" VARCHAR(200) NULL, + CONSTRAINT "parts_pkey" PRIMARY KEY ("id"), + CONSTRAINT "parts_sku_key" UNIQUE ("sku") + ); + """; + + private static readonly string[] Columns = ["id", "name", "sku", "category", "stock", "notes"]; + + public static async Task ProvisionSchemaAsync(string connString) + { + await using var c = new NpgsqlConnection(connString); + await c.OpenAsync(); + await using var cmd = c.CreateCommand(); + cmd.CommandText = SchemaDdl; + await cmd.ExecuteNonQueryAsync(); + } + + public static async Task ApplySeedAsync(string connString, string seedPath) + { + var root = JsonNode.Parse(File.ReadAllText(seedPath)) as JsonObject + ?? throw new InvalidOperationException($"{seedPath}: top-level must be an object"); + await using var c = new NpgsqlConnection(connString); + await c.OpenAsync(); + foreach (var rowNode in root["rows"]!.AsArray()) + { + var row = rowNode!.AsObject(); + await using var ins = c.CreateCommand(); + ins.CommandText = "INSERT INTO \"parts\" (" + string.Join(", ", Columns.Select(x => "\"" + x + "\"")) + + ") VALUES (" + string.Join(", ", Columns.Select((_, i) => "@p" + i)) + ")"; + for (int i = 0; i < Columns.Length; i++) + { + var v = row[Columns[i]]; + object val = v is null ? DBNull.Value + : Columns[i] == "id" ? v.GetValue() + : Columns[i] == "stock" ? v.GetValue() + : v.GetValue(); + ins.Parameters.AddWithValue("@p" + i, val); + } + await ins.ExecuteNonQueryAsync(); + } + await using var bump = c.CreateCommand(); + bump.CommandText = "SELECT setval(pg_get_serial_sequence('parts', 'id'), COALESCE((SELECT MAX(id) FROM \"parts\"), 1))"; + await bump.ExecuteScalarAsync(); + } +} diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ListQueryGeneratedServerFactory.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ListQueryGeneratedServerFactory.cs new file mode 100644 index 0000000000..69537164e9 --- /dev/null +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ListQueryGeneratedServerFactory.cs @@ -0,0 +1,174 @@ +// ListQueryGeneratedServerFactory — the C# GENERATED-server lane for the enum-default +// corpus. Runs the real Codegen generators (Entity + DbContext + FilterAllowlist + Routes) on the +// Account model, Roslyn-compiles the output in memory and hosts it on Kestrel against Postgres. + +using MetaObjects.Meta; +using System.Reflection; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using MetaObjects.IntegrationTests.Runner; +using MetaObjects.Loader; + +namespace MetaObjects.IntegrationTests.Api; + +internal sealed class ListQueryGeneratedServerFactory : IAsyncDisposable +{ + private const string GeneratedNamespace = "MetaObjects.ApiContract.ListQueryGenerated"; + + private readonly PostgresContainer _pg; + private readonly WebApplication _app; + + public string BaseUrl { get; } + + private ListQueryGeneratedServerFactory(PostgresContainer pg, WebApplication app, string baseUrl) + { + _pg = pg; + _app = app; + BaseUrl = baseUrl; + } + + public static async Task StartAsync(PostgresContainer pg) + { + await ListQueryFixture.ProvisionSchemaAsync(pg.ConnectionString); + + var (assembly, entityNames) = CompileGeneratedServer(); + var dbContextType = assembly.GetType($"{GeneratedNamespace}.AppDbContext") + ?? throw new InvalidOperationException("generated AppDbContext type not found"); + + var builder = WebApplication.CreateBuilder(); + LoopbackKestrel.BindAnyPort(builder); + builder.Logging.ClearProviders(); + // Wire enums are strings: the host registers the converter, as the TPH and report lanes do. + builder.Services.ConfigureHttpJsonOptions(o => + o.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter())); + RegisterGeneratedDbContext(builder.Services, dbContextType, pg.ConnectionString); + + var app = builder.Build(); + + // Mount each generated MapRoutes(app, "/api"). + foreach (var entity in entityNames) + { + var routesType = assembly.GetType($"{GeneratedNamespace}.{entity}Routes"); + if (routesType is null) continue; + var mapMethod = routesType.GetMethod($"Map{entity}Routes", BindingFlags.Public | BindingFlags.Static); + mapMethod?.Invoke(null, new object[] { app, "/api" }); + } + + await app.StartAsync(); + return new ListQueryGeneratedServerFactory(pg, app, LoopbackKestrel.BoundUrl(app)); + } + + public async Task ApplySeedAsync() => + await ListQueryFixture.ApplySeedAsync(_pg.ConnectionString, ApiContractCorpusPaths.ListQuerySeedFile); + + public async ValueTask DisposeAsync() + { + try { await _app.StopAsync(); } catch { /* ignored */ } + try { await _app.DisposeAsync(); } catch { /* ignored */ } + } + + private static (Assembly Assembly, IReadOnlyList EntityNames) CompileGeneratedServer() + { + var loadResult = new MetaDataLoader().Load([new FileSource(ApiContractCorpusPaths.ListQueryMetaJson)]); + // ADR-0058 — the corpus's committed naming rule, not a hardcoded default. + loadResult.Root.PhysicalNaming = ApiContractCorpusPaths.Naming; + loadResult.Root.WireFormat = ApiContractCorpusPaths.Wire; + if (loadResult.Errors.Count != 0) + throw new InvalidOperationException( + "list-query corpus metadata failed to load: " + + string.Join("; ", loadResult.Errors.Select(e => e.ToString()))); + + var entityNames = loadResult.Root.Objects() + .Where(o => o.IsEntity()) + .Select(o => CSharpNaming.Pascal(o.Name)) + .ToList(); + + var ctx = new GenContext + { + Entities = loadResult.Root.Objects(), + Root = loadResult.Root, + Config = new GenConfig + { + OutDir = "/unused", + Namespace = GeneratedNamespace, + ColumnNamingStrategy = ApiContractCorpusPaths.Naming.Columns, + EmitAbstractShapes = false, + }, + }; + + var files = new EntityGenerator().Generate(ctx) + .Concat(new DbContextGenerator().Generate(ctx)) + .Concat(new FilterAllowlistGenerator().Generate(ctx)) + .Concat(new RoutesGenerator().Generate(ctx)) + .ToList(); + + var trees = files + .Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12))) + .ToArray(); + + var refs = BuildReferenceSet(); + var comp = CSharpCompilation.Create( + "apicontract_listquery_generated_" + Guid.NewGuid().ToString("N"), + trees, refs, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + + using var ms = new MemoryStream(); + var emit = comp.Emit(ms); + if (!emit.Success) + { + var errors = emit.Diagnostics + .Where(d => d.Severity == DiagnosticSeverity.Error) + .Select(d => $"{d.Id}: {d.GetMessage()}") + .ToList(); + throw new InvalidOperationException( + "generated list-query server failed to compile:\n " + string.Join("\n ", errors)); + } + + ms.Seek(0, SeekOrigin.Begin); + return (Assembly.Load(ms.ToArray()), entityNames); + } + + private static List BuildReferenceSet() + { + var byFileName = new Dictionary(StringComparer.OrdinalIgnoreCase); + var tpa = (string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") ?? ""; + foreach (var path in tpa.Split(Path.PathSeparator)) + if (path.Length > 0 && path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) + byFileName[Path.GetFileName(path)] = path; + + var aspNetDir = Path.GetDirectoryName(typeof(WebApplication).Assembly.Location); + if (aspNetDir is not null && Directory.Exists(aspNetDir)) + foreach (var dll in Directory.EnumerateFiles(aspNetDir, "*.dll")) + byFileName[Path.GetFileName(dll)] = dll; + + return byFileName.Values + .Select(loc => (MetadataReference)MetadataReference.CreateFromFile(loc)) + .ToList(); + } + + private static void RegisterGeneratedDbContext( + IServiceCollection services, Type dbContextType, string connString) + { + var addDbContext = typeof(EntityFrameworkServiceCollectionExtensions) + .GetMethods(BindingFlags.Public | BindingFlags.Static) + .First(m => m.Name == "AddDbContext" + && m.IsGenericMethodDefinition + && m.GetGenericArguments().Length == 1 + && m.GetParameters().Length == 4) + .MakeGenericMethod(dbContextType); + + Action configure = opts => opts.UseNpgsql(connString); + addDbContext.Invoke(null, new object?[] + { + services, configure, ServiceLifetime.Scoped, ServiceLifetime.Scoped, + }); + } +} diff --git a/server/csharp/MetaObjects/Meta/ApiSettings.cs b/server/csharp/MetaObjects/Meta/ApiSettings.cs index ce031748e9..22a3344e28 100644 --- a/server/csharp/MetaObjects/Meta/ApiSettings.cs +++ b/server/csharp/MetaObjects/Meta/ApiSettings.cs @@ -18,14 +18,18 @@ public enum UnknownFieldsMode /// and a limit above is 400 { "error": "limit_too_large", "maxLimit": N }. public sealed record ApiPagination(int DefaultLimit, int MaxLimit); -/// The project's api block. A project that sets nothing has no page size and rejects unknown fields. +/// The project's api block. A project that sets nothing pages at with no maximum and rejects unknown fields. public sealed record ApiSettings(ApiPagination? Pagination, UnknownFieldsMode UnknownFields = UnknownFieldsMode.Reject) { /// What a tree loaded with no project carries. public static readonly ApiSettings Default = new(null, UnknownFieldsMode.Reject); + /// The rows a list with no limit answers when the project sets no api.pagination: + /// the same 50 in every port. Without the block there is no maximum, so an explicit limit is served as asked. + public const int DefaultPageLimit = 50; + /// What dotnet meta init writes for a new project. - public const int InitDefaultLimit = 50; + public const int InitDefaultLimit = DefaultPageLimit; /// What dotnet meta init writes for a new project. public const int InitMaxLimit = 1000; From ade3dc666090643a272ee824ff42a3007f04b917 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 22:20:59 -0500 Subject: [PATCH 3/9] feat(csharp): parse the whole list query into a predicate tree (R-CS-1) MetaObjects.AspNetCore gains ListQueryParser, a port of runtime-ts's parseListQuery. It reads or/and groups to a depth of five, search, sort with @sortableDefaultOrder, and page bounds. It refuses bare-field parameters, a leading %, and malformed values, naming each refusal with the shared wire codes and details. Faults are reported in the shared order. FilterValueFormat ports the format checks and the UTC spelling of timestamp bounds. EfCoreFilterDispatch.Apply turns the parsed tree and the search into one Where each. Each generated FilterAllowlist now also carries Rules, Sort and FieldNames. FieldNames leaves out credentials. The sortable set follows the TypeScript rule: @sortable, otherwise @filterable. FilterRules, SortRules and FieldNames are public, so ListQueryConformanceTests can derive the allowlist the generator emits. That runner passes all 95 cases in fixtures/list-query-conformance/. The allowlist now imports the helper runtime, so it carries the eject marker. Instant timestamps bind as DateTimeOffset at offset zero, and local-time timestamps bind as an unspecified DateTime. The generated routes still call the flat FilterParser. R-CS-2 wires them to the new parser. --- .../.metaobjects/.gen-state/.hashes/acme.json | 2 +- .../csharp/SubscriberFilterAllowlist.g.cs | 23 + .../EfCoreFilterDispatch.cs | 190 ++++++- .../MetaObjects.AspNetCore/FilterRules.cs | 82 +++ .../FilterValueFormat.cs | 120 +++++ .../MetaObjects.AspNetCore/ListQuery.cs | 470 ++++++++++++++++++ .../FilterAllowlistGeneratorTests.cs | 8 +- .../GeneratorExtensibilityTests.cs | 8 +- .../pre-rc22-propname/CarFilterAllowlist.g.cs | 25 + .../GizmoFilterAllowlist.g.cs | 29 ++ .../LineFilterAllowlist.g.cs | 20 + .../LineTotalsFilterAllowlist.g.cs | 24 + .../pre-rc22-propname/TagFilterAllowlist.g.cs | 20 + .../pre-rc22-propname/VanFilterAllowlist.g.cs | 24 + .../VehicleFilterAllowlist.g.cs | 23 + .../VehicleTagFilterAllowlist.g.cs | 20 + .../WidgetSummaryFilterAllowlist.g.cs | 19 + .../HelperRuntimeTests.cs | 10 +- .../ListQueryConformanceTests.cs | 84 ++++ .../ReportingInertTests.cs | 27 + .../Generators/FilterAllowlistGenerator.cs | 186 ++++++- .../Generators/KNOWN_GAPS.md | 2 +- .../MetaObjects.Codegen/HelperRuntime.cs | 3 + .../MetaObjects.Codegen.csproj | 3 + 24 files changed, 1381 insertions(+), 41 deletions(-) create mode 100644 server/csharp/MetaObjects.AspNetCore/FilterRules.cs create mode 100644 server/csharp/MetaObjects.AspNetCore/FilterValueFormat.cs create mode 100644 server/csharp/MetaObjects.AspNetCore/ListQuery.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/ListQueryConformanceTests.cs diff --git a/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json index a5f024b591..65daaf1eee 100644 --- a/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json +++ b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json @@ -1,7 +1,7 @@ { "generated/csharp/Subscriber.g.cs": "a7701fda82e3eb27dad5a01f326c0893ecd2ac418eea6e3afc5c4a2b81535bc2", "generated/csharp/SubscriberBlurbPayload.g.cs": "29eb3a6ce64496ffe734cba55d0213994316b4281d3fa6791917393bae36c9ed", - "generated/csharp/SubscriberFilterAllowlist.g.cs": "3839b04884e4e393d4f7d7bf4c7d4fe5b3852bd3a92b1ecb282cb8935a3c98e5", + "generated/csharp/SubscriberFilterAllowlist.g.cs": "9adb22081b65d6f29aa303f84e632f051bc19e85fefc2c93701c137bceb17da5", "generated/csharp/SubscriberNames.g.cs": "c2cf0248c2ecde155ec2623604771e39bed23783603d6f18a2ed82967227a732", "generated/csharp/SubscriberRoutes.g.cs": "59cab9100550a5f947828adbed92f5f32d5f2207459a3a03180f8e761881dbee", "generated/python/Subscriber.py": "9dd4c0acea47f99d1daf79930f9de2e400f30780ebce6c63f023be528a72b762", diff --git a/examples/showcase/generated/csharp/SubscriberFilterAllowlist.g.cs b/examples/showcase/generated/csharp/SubscriberFilterAllowlist.g.cs index c34c35a0b5..effa8424c7 100644 --- a/examples/showcase/generated/csharp/SubscriberFilterAllowlist.g.cs +++ b/examples/showcase/generated/csharp/SubscriberFilterAllowlist.g.cs @@ -2,6 +2,7 @@ // Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. #nullable enable using System.Collections.Generic; +using MetaObjects.AspNetCore; namespace Acme; @@ -9,6 +10,8 @@ namespace Acme; /// GENERATED — per-entity FR-009 filter allowlist for Subscriber. /// lists the filterable field names; /// constrains the operator vocabulary for each field by its subtype. +/// , and are what +/// ListQueryParser reads a list route's query string against. /// public static class SubscriberFilterAllowlist { @@ -19,4 +22,24 @@ public static class SubscriberFilterAllowlist public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) { }; + + /// Each filterable field's rule: its operators, how its values are typed and checked. + public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + { + }; + + /// The sortable fields, each with its declared @sortableDefaultOrder. + public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + { + }; + + /// Every field of the entity, filterable or not, except a credential. + public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + { + "id", + "email", + "name", + "status", + "createdAt", + }; } diff --git a/server/csharp/MetaObjects.AspNetCore/EfCoreFilterDispatch.cs b/server/csharp/MetaObjects.AspNetCore/EfCoreFilterDispatch.cs index 76b8a3f546..9e0cc8ab0c 100644 --- a/server/csharp/MetaObjects.AspNetCore/EfCoreFilterDispatch.cs +++ b/server/csharp/MetaObjects.AspNetCore/EfCoreFilterDispatch.cs @@ -92,20 +92,162 @@ public static FilterParseResult Validate(FilterParseResult parsed, IReadOnlyD private static Expression> BuildLambda(FilterPredicate p, IReadOnlyDictionary? propertyByField) { var x = Expression.Parameter(typeof(T), "x"); - var prop = ResolveProperty(typeof(T), p.Field, propertyByField); + return Expression.Lambda>(LeafBody(x, typeof(T), p.Field, p.Op, p.Value, propertyByField), x); + } + + /// + /// Apply a parsed list query's filter tree and search () to + /// : and/or groups become AndAlso/OrElse in one + /// Where, and the search one more Where ORing a case-insensitive pattern match over + /// its fields. Sort and page are the caller's. Run + /// first, so an operand the column cannot hold is a 400 and not an exception here. + /// + public static IQueryable Apply( + IQueryable source, + ListQuery query, + IReadOnlyDictionary rules, + IReadOnlyDictionary? propertyByField = null) where T : class + { + var x = Expression.Parameter(typeof(T), "x"); + if (query.Filter is not null) + source = source.Where(Expression.Lambda>(NodeBody(x, typeof(T), query.Filter, propertyByField), x)); + if (query.Search is not null) + source = source.Where(Expression.Lambda>(SearchBody(x, typeof(T), query.Search, rules, propertyByField), x)); + return source; + } + + /// + /// Check every operand of a parsed list query against the CLR type of its property (a value + /// out of an int column's range, an enum symbol the CLR enum does not carry). Null when + /// every operand converts, else the invalid_filter_value refusal for the first that does not. + /// + public static ListQueryError? Validate(ListQuery query, IReadOnlyDictionary? propertyByField = null) + { + foreach (var leaf in Leaves(query.Filter)) + { + if (leaf.Op is "isNull" or "like") continue; + var prop = ResolveProperty(typeof(T), leaf.Field, propertyByField); + if (prop is null) continue; + var memberType = prop.PropertyType; + var underlying = Nullable.GetUnderlyingType(memberType) ?? memberType; + var operands = leaf.Value is IReadOnlyList list ? list : new[] { leaf.Value }; + foreach (var operand in operands) + { + try + { + CoerceTo(OperandText(operand), memberType, underlying); + } + catch (Exception ex) when (ex is FormatException or InvalidCastException or OverflowException or ArgumentException) + { + var text = OperandText(operand); + return new ListQueryError("invalid_filter_value", + $"Field \"{leaf.Field}\" op \"{leaf.Op}\" requires a value of the field's type, got \"{text}\".", + new[] + { + new KeyValuePair("field", leaf.Field), + new KeyValuePair("op", leaf.Op), + new KeyValuePair("expected", "a value of the field's type"), + }); + } + } + } + return null; + } + + private static IEnumerable Leaves(FilterNode? node) => node switch + { + null => Array.Empty(), + FilterLeaf leaf => new[] { leaf }, + FilterAnd and => and.Nodes.SelectMany(Leaves), + FilterOr or => or.Nodes.SelectMany(Leaves), + _ => throw new InvalidOperationException("unknown filter node: " + node.GetType().Name), + }; + + private static Expression NodeBody(ParameterExpression x, Type entityType, FilterNode node, IReadOnlyDictionary? propertyByField) => node switch + { + FilterLeaf leaf => LeafBody(x, entityType, leaf.Field, leaf.Op, leaf.Value, propertyByField), + FilterAnd and => and.Nodes.Select(n => NodeBody(x, entityType, n, propertyByField)).Aggregate(Expression.AndAlso), + FilterOr or => or.Nodes.Select(n => NodeBody(x, entityType, n, propertyByField)).Aggregate(Expression.OrElse), + _ => throw new InvalidOperationException("unknown filter node: " + node.GetType().Name), + }; + + // `?search` is case-INSENSITIVE (a search box, not the contract's case-sensitive `like`): + // LOWER(column) LIKE LOWER('%term%') on a text column. The term is a like pattern, as in + // TypeScript. An enum column is matched in memory against its declared members, and the + // members that match become `column IN (...)`: a string-backed enum's stored text is its symbol. + private static Expression SearchBody(ParameterExpression x, Type entityType, ListSearch search, + IReadOnlyDictionary rules, IReadOnlyDictionary? propertyByField) + { + var pattern = "%" + search.Term + "%"; + var parts = new List(); + foreach (var field in search.Fields) + { + var prop = ResolveProperty(entityType, field, propertyByField) + ?? throw new InvalidOperationException($"search field \"{field}\" has no matching property on {entityType.Name}"); + Expression member = Expression.Property(x, prop); + var underlying = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; + if (underlying.IsEnum) + { + var members = rules.TryGetValue(field, out var rule) && rule.EnumValues is { } declared ? declared : Enum.GetNames(underlying); + var matched = members.Where(m => LikeMatches(m, pattern)).ToList(); + parts.Add(LeafBody(x, entityType, field, "in", matched.Cast().ToList(), propertyByField)); + continue; + } + if (underlying != typeof(string)) member = Expression.Call(member, typeof(object).GetMethod(nameof(object.ToString))!); + var lowered = Expression.Call(member, typeof(string).GetMethod(nameof(string.ToLower), Type.EmptyTypes)!); + var call = Expression.Call(LikeMethod, EfFunctions, lowered, Expression.Constant(pattern.ToLowerInvariant(), typeof(string))); + // A null column matches nothing (and is not dereferenced in memory). + parts.Add(prop.PropertyType.IsValueType && Nullable.GetUnderlyingType(prop.PropertyType) is null + ? call + : Expression.AndAlso(Expression.NotEqual(Expression.Convert(Expression.Property(x, prop), typeof(object)), Expression.Constant(null)), call)); + } + return parts.Count == 0 ? Expression.Constant(false) : parts.Aggregate(Expression.OrElse); + } + + private static readonly MethodInfo LikeMethod = typeof(DbFunctionsExtensions).GetMethod( + nameof(DbFunctionsExtensions.Like), new[] { typeof(DbFunctions), typeof(string), typeof(string) })!; + + private static readonly Expression EfFunctions = Expression.Property(null, typeof(EF).GetProperty(nameof(EF.Functions))!); + + // A SQL LIKE pattern (`%` any run, `_` one character) matched case-insensitively in memory. + private static bool LikeMatches(string value, string pattern) + { + var re = new System.Text.StringBuilder("^"); + foreach (var ch in pattern) + re.Append(ch switch { '%' => ".*", '_' => ".", _ => System.Text.RegularExpressions.Regex.Escape(ch.ToString()) }); + re.Append('$'); + return System.Text.RegularExpressions.Regex.IsMatch(value, re.ToString(), + System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline | System.Text.RegularExpressions.RegexOptions.CultureInvariant); + } + + // A neutral operand (string, long, double, bool) as the text CoerceTo reads. + private static string OperandText(object? value) => value switch + { + null => "", + string s => s, + bool b => b ? "true" : "false", + double d => d.ToString("R", CultureInfo.InvariantCulture), + IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), + _ => value.ToString() ?? "", + }; + + /// One condition on the resolved CLR property, as an expression over . + private static Expression LeafBody(ParameterExpression x, Type entityType, string field, string op, object? value, IReadOnlyDictionary? propertyByField) + { + var prop = ResolveProperty(entityType, field, propertyByField); // The metadata field name must map to a CLR property — the allowlist gate // upstream guarantees the field exists on the entity, so a miss here is a // generator/runtime contract violation, not user input. if (prop is null) throw new InvalidOperationException( - $"filter field \"{p.Field}\" has no matching property on {typeof(T).Name}"); + $"filter field \"{field}\" has no matching property on {entityType.Name}"); Expression member = Expression.Property(x, prop); // The non-nullable underlying type the raw string coerces to. var memberType = prop.PropertyType; var underlying = Nullable.GetUnderlyingType(memberType) ?? memberType; - switch (p.Op) + switch (op) { case "isNull": { @@ -114,27 +256,21 @@ private static Expression> BuildLambda(FilterPredicate p, IRead // members. var asObj = Expression.Convert(member, typeof(object)); var nullConst = Expression.Constant(null, typeof(object)); - Expression body = (p.Value is true) - ? Expression.Equal(asObj, nullConst) - : Expression.NotEqual(asObj, nullConst); - return Expression.Lambda>(body, x); + return value is true ? Expression.Equal(asObj, nullConst) : Expression.NotEqual(asObj, nullConst); } case "in": { - var items = (IReadOnlyList)p.Value!; - if (items.Count == 0) - return Expression.Lambda>(Expression.Constant(false), x); + var items = ((IEnumerable)value!).Cast().ToList(); + if (items.Count == 0) return Expression.Constant(false); // Build a typed List and call list.Contains(x.Property), // which EF translates to SQL `IN (...)`. var listType = typeof(List<>).MakeGenericType(memberType); var typedList = (IList)Activator.CreateInstance(listType)!; - foreach (var item in items) typedList.Add(CoerceTo(item, memberType, underlying)); + foreach (var item in items) typedList.Add(CoerceTo(OperandText(item), memberType, underlying)); var containsMethod = listType.GetMethod("Contains", new[] { memberType })!; - var listConst = Expression.Constant(typedList, listType); - var call = Expression.Call(listConst, containsMethod, member); - return Expression.Lambda>(call, x); + return Expression.Call(Expression.Constant(typedList, listType), containsMethod, member); } case "like": @@ -143,22 +279,16 @@ private static Expression> BuildLambda(FilterPredicate p, IRead var memberStr = (underlying == typeof(string)) ? member : Expression.Call(member, typeof(object).GetMethod(nameof(object.ToString))!); - var pattern = Expression.Constant((string)(p.Value ?? ""), typeof(string)); - var efFunctions = Expression.Property(null, typeof(EF).GetProperty(nameof(EF.Functions))!); - var likeMethod = typeof(DbFunctionsExtensions).GetMethod( - nameof(DbFunctionsExtensions.Like), - new[] { typeof(DbFunctions), typeof(string), typeof(string) })!; - var call = Expression.Call(likeMethod, efFunctions, memberStr, pattern); - return Expression.Lambda>(call, x); + var pattern = Expression.Constant(OperandText(value), typeof(string)); + return Expression.Call(LikeMethod, EfFunctions, memberStr, pattern); } default: { // eq / ne / gt / gte / lt / lte — typed comparison against the // coerced constant. EF translates each to the SQL operator. - var value = CoerceTo((string)(p.Value ?? ""), memberType, underlying); - var constant = Expression.Constant(value, memberType); - Expression body = p.Op switch + var constant = Expression.Constant(CoerceTo(OperandText(value), memberType, underlying), memberType); + return op switch { "eq" => Expression.Equal(member, constant), "ne" => Expression.NotEqual(member, constant), @@ -166,9 +296,8 @@ private static Expression> BuildLambda(FilterPredicate p, IRead "gte" => Expression.GreaterThanOrEqual(member, constant), "lt" => Expression.LessThan(member, constant), "lte" => Expression.LessThanOrEqual(member, constant), - _ => throw new InvalidOperationException("unknown filter op: " + p.Op), + _ => throw new InvalidOperationException("unknown filter op: " + op), }; - return Expression.Lambda>(body, x); } } } @@ -194,8 +323,15 @@ private static Expression> BuildLambda(FilterPredicate p, IRead { if (underlying == typeof(string)) return raw; if (underlying == typeof(Guid)) return Guid.Parse(raw); + // A timestamp instant (DateTimeOffset, timestamptz) binds at offset zero; a @localTime wall + // clock (DateTime, timestamp without time zone) binds with an unspecified kind, which is + // what Npgsql requires of each. The list query parser has already spelled a zoned bound in UTC. + if (underlying == typeof(DateTimeOffset)) + return DateTimeOffset.Parse(raw, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime(); if (underlying == typeof(DateTime)) - return DateTime.Parse(raw, CultureInfo.InvariantCulture, DateTimeStyles.None); + return DateTime.SpecifyKind( + DateTime.Parse(raw, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal), + DateTimeKind.Unspecified); if (underlying == typeof(DateOnly)) return DateOnly.Parse(raw, CultureInfo.InvariantCulture); if (underlying == typeof(TimeOnly)) diff --git a/server/csharp/MetaObjects.AspNetCore/FilterRules.cs b/server/csharp/MetaObjects.AspNetCore/FilterRules.cs new file mode 100644 index 0000000000..965d055ce0 --- /dev/null +++ b/server/csharp/MetaObjects.AspNetCore/FilterRules.cs @@ -0,0 +1,82 @@ +// FilterRules — the per-field data a generated FilterAllowlist carries, which the list +// query parser (ListQueryParser) reads to accept or refuse a filter, a sort and a search. +// +// The shape mirrors runtime-ts's FilterFieldRule / SortFieldRule +// (server/typescript/packages/runtime-ts/src/drizzle-fastify/filter-allowlist.ts), so the same +// metadata derives the same allowlist in both ports and the shared parse cases +// (fixtures/list-query-conformance/) hold both to it. + +#nullable enable +using System.Collections.Generic; + +namespace MetaObjects.AspNetCore; + +/// The coarse kind of a filter value: how a query-string operand is typed. +public enum FilterValueKind +{ + /// Text, an enum member, a uuid, a duration: kept as the string sent. + String, + /// int, long, double, float, decimal, currency. + Number, + /// true/1/false/0. + Boolean, + /// date, time, timestamp. + Datetime, +} + +/// +/// The exact wire formats a filter value is checked against, beyond . +/// Each value IS the field.* subtype name whose wire encoding the value must match. +/// +public static class FilterValueFormats +{ + public const string Date = "date"; + public const string Time = "time"; + public const string Timestamp = "timestamp"; + public const string Uuid = "uuid"; + public const string Decimal = "decimal"; + public const string Duration = "duration"; +} + +/// One filterable field's rule: its operators, its value kind and the checks on its values. +public sealed class FilterFieldRule +{ + public FilterFieldRule(FilterValueKind kind, params string[] ops) + { + Kind = kind; + Ops = ops; + } + + /// The operators the field takes (its band, QueryConstants.OpsForField). + public IReadOnlyList Ops { get; } + + /// How an operand is typed. + public FilterValueKind Kind { get; } + + /// One of , for date/time/timestamp/uuid/decimal/duration fields. + public string? Format { get; init; } + + /// + /// A field.timestamp that is an instant (not @localTime): a zoneless bound is read + /// as UTC and a date alone as midnight UTC, the rule the write path stores such a value by. + /// + public bool Instant { get; init; } + + /// int, long, currency: a bound that is not a whole number is refused. + public bool Integer { get; init; } + + /// The declared members of a field.enum; a value that is not one is refused. + public IReadOnlyList? EnumValues { get; init; } + + /// Whether a like pattern may start with %. Always false in generated rules. + public bool LeadingWildcard { get; init; } +} + +/// One sortable field's rule. +public sealed class SortFieldRule +{ + public SortFieldRule(string? defaultOrder = null) => DefaultOrder = defaultOrder; + + /// The DECLARED @sortableDefaultOrder (asc/desc), or null for none. + public string? DefaultOrder { get; } +} diff --git a/server/csharp/MetaObjects.AspNetCore/FilterValueFormat.cs b/server/csharp/MetaObjects.AspNetCore/FilterValueFormat.cs new file mode 100644 index 0000000000..ec2d2abe5a --- /dev/null +++ b/server/csharp/MetaObjects.AspNetCore/FilterValueFormat.cs @@ -0,0 +1,120 @@ +// FilterValueFormat — the well-formedness checks for filter values, keyed by the wire format a +// field's values take (docs/features/api-contract.md, "Type encodings"), and the UTC spelling of +// a timestamp bound. The list query parser runs these before a value reaches SQL, so a malformed +// value is a 400 naming the format rather than a driver error or a silent empty result. +// +// A port of runtime-ts's filter-value-format.ts; the `expected` strings are the cross-port wire +// text and must stay byte-identical to it. + +#nullable enable +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace MetaObjects.AspNetCore; + +/// Format checks, their expected text, and the UTC normalization of timestamp bounds. +public static class FilterValueFormat +{ + private static readonly Regex DateRe = new(@"^(\d{4})-(\d{2})-(\d{2})$", RegexOptions.CultureInvariant); + private static readonly Regex TimeRe = new(@"^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,9})?)?$", RegexOptions.CultureInvariant); + // Date, then optionally a `T`/space time, then optionally `Z` or a ±HH[:]MM offset. + private static readonly Regex TimestampRe = new( + @"^(\d{4}-\d{2}-\d{2})(?:[T ]((?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,9})?)?)(?:Z|[+-](?:[01]\d|2[0-3]):?[0-5]\d)?)?$", + RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + private static readonly Regex UuidRe = new(@"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", + RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + private static readonly Regex TimestampPartsRe = new( + @"^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$", + RegexOptions.CultureInvariant); + private static readonly Regex CanonicalUtcRe = new(@"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$", RegexOptions.CultureInvariant); + private static readonly Regex SpaceForPlusOffsetRe = new( + @"^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)? \d{2}(?::?\d{2})?$", RegexOptions.CultureInvariant); + + /// The expected member of the invalid_filter_value body, per format. + public static readonly IReadOnlyDictionary Expected = new Dictionary(StringComparer.Ordinal) + { + [FilterValueFormats.Date] = "date (YYYY-MM-DD)", + [FilterValueFormats.Time] = "time (HH:MM[:SS[.fff]])", + [FilterValueFormats.Timestamp] = "timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + [FilterValueFormats.Uuid] = "uuid (8-4-4-4-12 hex)", + [FilterValueFormats.Decimal] = "decimal number (digits, optional fraction, optional exponent)", + [FilterValueFormats.Duration] = "duration (ISO 8601, e.g. PT1H30M; no years or months)", + }; + + /// expected for a temporal rule that does not say which temporal format it is. + public const string AnyTemporalExpected = "date, time or timestamp (ISO 8601)"; + + /// The hint for a timestamp bound that fails only because its + offset was not encoded. + public const string PlusOffsetHint = + "a \"+\" in a query string decodes to a space: URL-encode the offset's \"+\" as %2B, or use Z for UTC"; + + /// Whether is a value of . + public static bool Matches(string format, string s) => format switch + { + FilterValueFormats.Date => IsCalendarDate(s), + FilterValueFormats.Time => TimeRe.IsMatch(s), + FilterValueFormats.Timestamp => IsTimestamp(s), + FilterValueFormats.Uuid => UuidRe.IsMatch(s), + FilterValueFormats.Decimal => DecimalWire.TryParse(s, out _), + FilterValueFormats.Duration => DurationWire.TryParse(s, out _), + _ => throw new ArgumentException("unknown filter value format: " + format, nameof(format)), + }; + + /// For a datetime rule with no format: any of date, time or timestamp. + public static bool MatchesAnyTemporal(string s) => IsCalendarDate(s) || TimeRe.IsMatch(s) || IsTimestamp(s); + + /// A timestamp bound whose + offset arrived as a space (an unencoded +). + public static bool LooksLikeUnencodedPlusOffset(string s) => SpaceForPlusOffsetRe.IsMatch(s); + + /// A zoned timestamp bound in UTC; a naive or date-only one unchanged (a wall clock). + public static string UtcIfZoned(string s) => UtcIso(s, zonelessIsUtc: false); + + /// + /// A field.timestamp instant bound in UTC: a zoned value at its instant, a zoneless one + /// read as UTC, a date alone as midnight UTC. + /// + public static string UtcInstant(string s) => UtcIso(s, zonelessIsUtc: true); + + private static bool IsCalendarDate(string s) + { + var m = DateRe.Match(s); + if (!m.Success) return false; + int y = int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture); + int mo = int.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture); + int d = int.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture); + return y >= 1 && mo >= 1 && mo <= 12 && d >= 1 && d <= DateTime.DaysInMonth(y, mo); + } + + private static bool IsTimestamp(string s) + { + var m = TimestampRe.Match(s); + return m.Success && IsCalendarDate(m.Groups[1].Value); + } + + // The canonical UTC spelling `YYYY-MM-DDTHH:MM:SS[.fff]Z`: millisecond resolution, no trailing + // zeros, no fraction when it is zero. A value already spelled that way is returned as sent. + private static string UtcIso(string s, bool zonelessIsUtc) + { + if (CanonicalUtcRe.IsMatch(s)) return s; + var m = TimestampPartsRe.Match(s); + if (!m.Success) return s; + var date = m.Groups[1].Value; + var hm = m.Groups[2].Success ? m.Groups[2].Value : "00:00"; + var sec = m.Groups[3].Success ? m.Groups[3].Value : "00"; + var frac = m.Groups[4].Success ? m.Groups[4].Value : ""; + bool zoned = m.Groups[5].Success || m.Groups[6].Success; + if (!zoned && !zonelessIsUtc) return s; + var ms = (frac.Length > 3 ? frac.Substring(0, 3) : frac).PadRight(3, '0'); + var offset = m.Groups[6].Success ? $"{m.Groups[6].Value}:{(m.Groups[7].Success ? m.Groups[7].Value : "00")}" : "+00:00"; + if (!DateTimeOffset.TryParseExact($"{date}T{hm}:{sec}.{ms}{offset}", "yyyy-MM-dd'T'HH:mm:ss.fffzzz", + CultureInfo.InvariantCulture, DateTimeStyles.None, out var instant)) + return s; + var utc = instant.UtcDateTime; + var text = utc.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture); + if (utc.Millisecond != 0) + text += "." + utc.Millisecond.ToString("000", CultureInfo.InvariantCulture).TrimEnd('0'); + return text + "Z"; + } +} diff --git a/server/csharp/MetaObjects.AspNetCore/ListQuery.cs b/server/csharp/MetaObjects.AspNetCore/ListQuery.cs new file mode 100644 index 0000000000..156d46a0a7 --- /dev/null +++ b/server/csharp/MetaObjects.AspNetCore/ListQuery.cs @@ -0,0 +1,470 @@ +// ListQuery — how a list route reads its query string: the filter tree (and/or groups to a depth +// cap), search, sort and page, or the named 400 it refuses with. A port of runtime-ts's +// parseListQuery (server/typescript/packages/runtime-ts/src/drizzle-fastify/list-query.ts), held +// to it by the shared parse cases in fixtures/list-query-conformance/. +// +// The parse runs before any store sees the query. EfCoreFilterDispatch turns the parsed tree into +// an IQueryable filter; a hand-written list endpoint over another store reads the same tree. +// +// Faults are found, and the first reported, in this order: bare field parameters; limit, then +// offset; the filter, depth-first in the order its keys were sent; the sort; the search. + +#nullable enable +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; + +namespace MetaObjects.AspNetCore; + +/// A node of a parsed filter: a , a or a . +public abstract record FilterNode; + +/// +/// One condition. is neutral, not a driver's: a (text, enum +/// member, date, time, uuid, duration, like pattern, a decimal's canonical text, a timestamp's UTC +/// spelling), a (an integer field), a (another number), a +/// (a boolean, and isNull's operand), or for in a list of those. +/// +public sealed record FilterLeaf(string Field, string Op, object Value) : FilterNode; + +/// Every branch holds. +public sealed record FilterAnd(IReadOnlyList Nodes) : FilterNode; + +/// At least one branch holds. +public sealed record FilterOr(IReadOnlyList Nodes) : FilterNode; + +/// A case-insensitive substring search over . +public sealed record ListSearch(string Term, IReadOnlyList Fields); + +/// One sort key; is asc or desc. +public sealed record ListSort(string Field, string Order) +{ + public bool Descending => Order == "desc"; +} + +/// A parsed list query. Members a query did not send are null. +public sealed record ListQuery(FilterNode? Filter, ListSearch? Search, ListSort? Sort, long? Limit, long? Offset); + +/// +/// A refused list query: the wire code and its , in the +/// order the 400 body lists them (). +/// +public sealed class ListQueryError +{ + public ListQueryError(string error, string message, IReadOnlyList> details) + { + Error = error; + Message = message; + Details = details; + } + + /// The wire code: 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 or pagination.invalid_value. + public string Error { get; } + + /// A sentence for a person; not part of the 400 body. + public string Message { get; } + + /// The members after error in the 400 body. + public IReadOnlyList> Details { get; } + + /// The 400 body: { "error": code, ...details }. + public Dictionary Body() + { + var body = new Dictionary(StringComparer.Ordinal) { ["error"] = Error }; + foreach (var (k, v) in Details) body[k] = v; + return body; + } +} + +/// The outcome of : a query or an error, never both. +public sealed record ListQueryResult(ListQuery? Query, ListQueryError? Error) +{ + public bool Ok => Error is null; +} + +/// Parses a list route's raw query string against the generated allowlist. +public static class ListQueryParser +{ + /// Five levels of or/and nesting; the sixth is filter.nesting_too_deep. + public const int DefaultMaxNesting = 5; + + /// At most 100 in elements; more is filter.in_too_large. + public const int DefaultMaxInList = 100; + + /// The expected text of an invalid_sort. + public const string SortExpected = "sort=:asc|desc"; + + /// The expected text of a malformed limit or offset. + public const string PaginationExpected = "a non-negative integer (0 or more)"; + + private static readonly HashSet ReservedParams = new(StringComparer.Ordinal) + { + "filter", "sort", "limit", "offset", "search", "withCount", + }; + + /// + /// Parse (the query string as it arrives, with or without its + /// leading ?). , when given, names every field of the + /// entity, so a bare ?notes=x for a field that is not filterable is refused with a reason + /// rather than ignored as an unknown parameter. + /// + public static ListQueryResult Parse( + string? rawQuery, + IReadOnlyDictionary rules, + IReadOnlyDictionary sortRules, + IReadOnlySet? fieldNames = null, + int maxNesting = DefaultMaxNesting, + int maxInList = DefaultMaxInList) + { + try + { + var q = QueryString.Parse(rawQuery); + RejectBareFields(q, rules, fieldNames); + var limit = PageBound(q, "limit"); + var offset = PageBound(q, "offset"); + FilterNode? filter = null; + if (q.TryGet("filter", out var f) && f is QueryString.Map fm) + filter = ParseNode(fm, rules, maxNesting, maxInList, 0); + ListSort? sort = null; + if (q.TryGet("sort", out var s) && s is QueryString.Scalar ss) sort = ParseSort(ss.Value, sortRules); + ListSearch? search = null; + if (q.TryGet("search", out var t) && t is QueryString.Scalar ts && ts.Value != "") + { + var fields = SearchFields(rules); + if (fields.Count > 0) search = new ListSearch(ts.Value, fields); + } + return new ListQueryResult(new ListQuery(filter, search, sort, limit, offset), null); + } + catch (Refusal r) + { + return new ListQueryResult(null, r.Error); + } + } + + /// + /// The fields ?search matches: text rules (no format) whose band has like, so a + /// uuid and an int-backed enum take no text match. + /// + public static IReadOnlyList SearchFields(IReadOnlyDictionary rules) => + rules.Where(kv => kv.Value.Kind == FilterValueKind.String && kv.Value.Format is null && kv.Value.Ops.Contains("like")) + .Select(kv => kv.Key).ToList(); + + private sealed class Refusal : Exception + { + public Refusal(string error, string message, params (string Key, object? Value)[] details) : base(message) => + Error = new ListQueryError(error, message, details.Select(d => new KeyValuePair(d.Key, d.Value)).ToList()); + + public ListQueryError Error { get; } + } + + private static void RejectBareFields(QueryString.Map q, IReadOnlyDictionary rules, IReadOnlySet? fieldNames) + { + foreach (var (key, value) in q.Entries()) + { + if (ReservedParams.Contains(key)) continue; + if (rules.ContainsKey(key)) + { + var shown = value is QueryString.Scalar sv ? sv.Value : ""; + throw new Refusal("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 (fieldNames is not null && fieldNames.Contains(key)) + { + var allowed = rules.Keys.ToList(); + throw new Refusal("filter.bare_field", + $"\"{key}\" is a field of this entity, but it is not @filterable, so it cannot be filtered on" + + (allowed.Count > 0 ? $" (filterable: {string.Join(", ", allowed)})." : " (no field is filterable)."), + ("field", key), ("filterable", false), ("expected", $"a filterable field — \"{key}\" is not @filterable"), ("allowed", allowed)); + } + } + } + + private static long? PageBound(QueryString.Map q, string param) + { + if (!q.TryGet(param, out var raw)) return null; + var s = raw.Text(); + if (s.Length > 0 && s.All(c => c >= '0' && c <= '9') + && long.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out var n) && n <= MaxSafeInteger) + return n; + throw new Refusal("pagination.invalid_value", $"?{param}= must be {PaginationExpected}, got \"{s}\".", + ("param", param), ("value", s), ("expected", PaginationExpected)); + } + + // 2^53 - 1: the largest bound TypeScript accepts (Number.isSafeInteger), so both ports refuse the same input. + private const long MaxSafeInteger = 9007199254740991L; + + private static FilterNode? ParseNode(QueryString.Map node, IReadOnlyDictionary rules, int maxNesting, int maxInList, int depth) + { + if (depth > maxNesting) + throw new Refusal("filter.nesting_too_deep", $"Filter nesting depth exceeds limit ({maxNesting}).", ("limit", maxNesting)); + var parts = new List(); + foreach (var (key, value) in node.Entries()) + { + if (key is "or" or "and") + { + if (value is not QueryString.Map branches) + throw new Refusal("invalid_filter_value", $"Expected array for \"{key}\".", ("field", key)); + var subs = new List(); + foreach (var (_, branch) in branches.Entries()) + { + if (branch is not QueryString.Map bm) + throw new Refusal("invalid_filter_value", $"Each \"{key}\" branch must be a filter object.", ("field", key)); + var sub = ParseNode(bm, rules, maxNesting, maxInList, depth + 1); + if (sub is not null) subs.Add(sub); + } + if (subs.Count == 0) continue; + parts.Add(subs.Count == 1 ? subs[0] : key == "or" ? new FilterOr(subs) : new FilterAnd(subs)); + continue; + } + if (!rules.TryGetValue(key, out var rule)) + throw new Refusal("invalid_filter_field", $"Unknown filter field \"{key}\".", ("field", key), ("allowed", rules.Keys.ToList())); + if (value is QueryString.Map ops) + foreach (var (op, operand) in ops.Entries()) parts.Add(Leaf(key, rule, op, operand.Text(), maxInList)); + else + parts.Add(Leaf(key, rule, "eq", value.Text(), maxInList)); + } + if (parts.Count == 0) return null; + return parts.Count == 1 ? parts[0] : new FilterAnd(parts); + } + + private static FilterLeaf Leaf(string field, FilterFieldRule rule, string op, string operand, int maxInList) + { + if (!rule.Ops.Contains(op)) + throw new Refusal("invalid_filter_op", $"Op \"{op}\" not supported for field \"{field}\".", + ("field", field), ("op", op), ("allowed", rule.Ops.ToList())); + switch (op) + { + case "in": + { + var list = operand.Split(',').Select(v => Operand(v.Trim(), rule, field, op)).ToList(); + if (list.Count > maxInList) + throw new Refusal("filter.in_too_large", $"In-list size {list.Count} exceeds limit {maxInList}.", + ("field", field), ("limit", maxInList)); + return new FilterLeaf(field, op, list); + } + case "like": + if (operand.StartsWith('%') && !rule.LeadingWildcard) + throw new Refusal("filter.leading_wildcard_disallowed", $"Leading wildcard not allowed for field \"{field}\".", ("field", field)); + return new FilterLeaf(field, op, operand); + case "isNull": + return new FilterLeaf(field, op, AsBoolean(operand, field, op)); + default: + return new FilterLeaf(field, op, Operand(operand, rule, field, op)); + } + } + + private const string IntegerExpected = "integer (a whole number)"; + + private static Refusal InvalidValue(string field, string op, string s, string expected, params (string Key, object? Value)[] extra) + { + string hint = ""; + foreach (var (k, v) in extra) if (k == "hint" && v is string h) hint = $" Hint: {h}."; + var details = new List<(string, object?)> { ("field", field), ("op", op), ("expected", expected) }; + details.AddRange(extra); + return new Refusal("invalid_filter_value", $"Field \"{field}\" op \"{op}\" requires {expected}, got \"{s}\".{hint}", details.ToArray()); + } + + private static object Operand(string s, FilterFieldRule rule, string field, string op) + { + if (rule.EnumValues is { } members && !members.Contains(s)) + throw InvalidValue(field, op, s, "one of: " + string.Join(", ", members), ("allowed", members.ToList())); + if (rule.Format is { } format) + { + if (!FilterValueFormat.Matches(format, s)) + { + if (format == FilterValueFormats.Timestamp && FilterValueFormat.LooksLikeUnencodedPlusOffset(s)) + throw InvalidValue(field, op, s, FilterValueFormat.Expected[format], ("hint", FilterValueFormat.PlusOffsetHint)); + throw InvalidValue(field, op, s, FilterValueFormat.Expected[format]); + } + } + else if (rule.Kind == FilterValueKind.Datetime && !FilterValueFormat.MatchesAnyTemporal(s)) + { + throw InvalidValue(field, op, s, FilterValueFormat.AnyTemporalExpected); + } + if (rule.Format == FilterValueFormats.Decimal) + { + DecimalWire.TryParse(s, out var d); + return DecimalWire.Format(d); + } + if (rule.Format == FilterValueFormats.Timestamp) + return rule.Instant ? FilterValueFormat.UtcInstant(s) : FilterValueFormat.UtcIfZoned(s); + if (rule.Format is not null) return s; + switch (rule.Kind) + { + case FilterValueKind.Boolean: + return AsBoolean(s, field, op); + case FilterValueKind.Number: + { + var t = s.Trim(); + if (rule.Integer && long.TryParse(t, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var whole)) + return whole; + if (t == "" || !double.TryParse(t, NumberStyles.Float, CultureInfo.InvariantCulture, out var n) || !double.IsFinite(n)) + throw new Refusal("invalid_filter_value", $"Field \"{field}\" op \"{op}\" requires number, got \"{s}\".", + ("field", field), ("op", op), ("expected", "number")); + if (rule.Integer) + { + if (Math.Floor(n) != n) throw InvalidValue(field, op, s, IntegerExpected); + if (n >= long.MinValue && n <= long.MaxValue) return (long)n; + } + return n; + } + default: + return s; + } + } + + private static bool AsBoolean(string s, string field, string op) => s switch + { + "true" or "1" => true, + "false" or "0" => false, + _ => throw new Refusal("invalid_filter_value", $"Field \"{field}\" op \"{op}\" requires boolean, got \"{s}\".", + ("field", field), ("op", op), ("expected", "boolean")), + }; + + private static ListSort ParseSort(string spec, IReadOnlyDictionary sortRules) + { + int colon = spec.IndexOf(':'); + var field = colon < 0 ? spec : spec.Substring(0, colon); + if (!sortRules.TryGetValue(field, out var rule)) + throw new Refusal("invalid_sort", $"Unknown sort field \"{field}\". The syntax is {SortExpected}.", + ("field", field), ("expected", SortExpected), ("allowed", sortRules.Keys.ToList())); + // The caller's order, else the field's DECLARED @sortableDefaultOrder, else ascending. + var orderRaw = colon < 0 ? rule.DefaultOrder ?? "asc" : spec.Substring(colon + 1); + var order = orderRaw.ToLowerInvariant(); + if (order is not ("asc" or "desc")) + throw new Refusal("invalid_sort", $"Sort order must be asc|desc, got \"{orderRaw}\". The syntax is {SortExpected}.", + ("field", field), ("expected", SortExpected), ("allowed", sortRules.Keys.ToList())); + return new ListSort(field, order); + } + + /// + /// The bracket grammar of a query string, read the way the TypeScript mounts' qs reads it: + /// a[b][c]=v nests, a repeated key collects its values, and a map's keys come back with + /// array-index keys first in numeric order and every other key in the order it was sent (a + /// JavaScript object's own key order), so filter[or][1]…&filter[or][0]… is in index order. + /// + private static class QueryString + { + internal abstract class Value + { + /// The value as text; a repeated value is its parts joined by commas. + public abstract string Text(); + } + + internal sealed class Scalar : Value + { + public Scalar(string value) => Value = value; + public string Value { get; } + public override string Text() => Value; + } + + internal sealed class Many : Value + { + public List Values { get; } = new(); + public override string Text() => string.Join(",", Values); + } + + internal sealed class Map : Value + { + private readonly List _order = new(); + private readonly Dictionary _values = new(StringComparer.Ordinal); + + public override string Text() => "[object Object]"; + + public bool TryGet(string key, out Value value) => _values.TryGetValue(key, out value!); + + public IEnumerable<(string Key, Value Value)> Entries() => + _order.Where(IsIndex).OrderBy(k => long.Parse(k, CultureInfo.InvariantCulture)) + .Concat(_order.Where(k => !IsIndex(k))) + .Select(k => (k, _values[k])); + + public void Set(List path, int at, string value) + { + var key = path[at]; + if (at == path.Count - 1) + { + if (!_values.TryGetValue(key, out var existing)) { Add(key, new Scalar(value)); return; } + switch (existing) + { + case Scalar s: + var many = new Many(); + many.Values.Add(s.Value); + many.Values.Add(value); + _values[key] = many; + break; + case Many m: + m.Values.Add(value); + break; + // A scalar sent beside a map under the same key: the map keeps its members. + } + return; + } + if (!_values.TryGetValue(key, out var child) || child is not Map map) + { + map = new Map(); + if (child is null) Add(key, map); else _values[key] = map; + } + map.Set(path, at + 1, value); + } + + private void Add(string key, Value value) + { + _order.Add(key); + _values[key] = value; + } + + // A JavaScript array index: a canonical non-negative integer below 2^32 - 1. + private static bool IsIndex(string k) => + k.Length > 0 && k.Length <= 10 && k.All(c => c >= '0' && c <= '9') && (k == "0" || k[0] != '0') + && long.Parse(k, CultureInfo.InvariantCulture) < 4294967295L; + } + + public static Map Parse(string? raw) + { + var root = new Map(); + if (string.IsNullOrEmpty(raw)) return root; + if (raw[0] == '?') raw = raw.Substring(1); + foreach (var pair in raw.Split('&')) + { + if (pair.Length == 0) continue; + int eq = pair.IndexOf('='); + var key = Decode(eq < 0 ? pair : pair.Substring(0, eq)); + var value = eq < 0 ? "" : Decode(pair.Substring(eq + 1)); + var path = KeyPath(key); + if (path.Count == 0 || path[0].Length == 0) continue; + root.Set(path, 0, value); + } + return root; + } + + // `a[b][c]` → a, b, c. Text after the last balanced bracket pair, or an unclosed `[`, stays + // part of the last segment, as qs leaves it. + private static List KeyPath(string key) + { + var path = new List(); + int open = key.IndexOf('['); + if (open <= 0) { path.Add(key); return path; } + path.Add(key.Substring(0, open)); + int i = open; + while (i < key.Length && key[i] == '[') + { + int close = key.IndexOf(']', i + 1); + if (close < 0) break; + path.Add(key.Substring(i + 1, close - i - 1)); + i = close + 1; + } + if (i < key.Length) path[^1] += key.Substring(i); + return path; + } + + private static string Decode(string s) + { + try { return Uri.UnescapeDataString(s.Replace('+', ' ')); } + catch (UriFormatException) { return s; } + } + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/FilterAllowlistGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/FilterAllowlistGeneratorTests.cs index 3fc64f8f82..12bfa207db 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/FilterAllowlistGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/FilterAllowlistGeneratorTests.cs @@ -50,9 +50,11 @@ public void Empty_allowlist_when_no_filterable_fields() // Field set is the empty initializer block. Assert.Contains("public static readonly HashSet Fields = new(System.StringComparer.Ordinal)", src); Assert.Contains("public static readonly Dictionary> OpsByField", src); - // No field strings of any kind in the emitted source. - Assert.DoesNotContain("\"name\"", src); - Assert.DoesNotContain("\"id\"", src); + // No filter or sort entry; the two fields appear only in FieldNames (a bare ?name= is + // refused as a field that is not filterable). + Assert.DoesNotContain("[\"name\"]", src); + Assert.DoesNotContain("[\"id\"]", src); + Assert.Contains("FieldNames = new HashSet(System.StringComparer.Ordinal)\n {\n \"id\",\n \"name\",\n };", src.ReplaceLineEndings("\n")); } [Fact] diff --git a/server/csharp/MetaObjects.Codegen.Tests/GeneratorExtensibilityTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GeneratorExtensibilityTests.cs index 0300bdc810..217a64c5d5 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/GeneratorExtensibilityTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/GeneratorExtensibilityTests.cs @@ -130,9 +130,11 @@ public void FilterAllowlist_subclass_can_override_compute_ops_seam() { var ctx = Ctx(Load(EntityModel)); var src = Assert.Single(new NoOpsFilterAllowlistGenerator().Generate(ctx)).Content; - // Overridden to empty → no field entries emitted. - Assert.DoesNotContain("\"email\"", src); - Assert.DoesNotContain("\"subscribed\"", src); + // Overridden to empty → no filter entries emitted: no operator set, no rule. (FieldNames + // and Sort still list the fields: what is a field, and what sorts, is not this seam's.) + Assert.DoesNotContain("[\"email\"] = new(System.StringComparer.Ordinal)", src); + Assert.DoesNotContain("[\"email\"] = new(FilterValueKind", src); + Assert.DoesNotContain("[\"subscribed\"] = new(FilterValueKind", src); } [Fact] diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/CarFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/CarFilterAllowlist.g.cs index bc27216e3c..330e2a7d89 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/CarFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/CarFilterAllowlist.g.cs @@ -2,6 +2,7 @@ // Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. #nullable enable using System.Collections.Generic; +using MetaObjects.AspNetCore; namespace Acme.Shop; @@ -9,6 +10,8 @@ namespace Acme.Shop; /// GENERATED — per-entity FR-009 filter allowlist for Car. /// lists the filterable field names; /// constrains the operator vocabulary for each field by its subtype. +/// , and are what +/// ListQueryParser reads a list route's query string against. /// public static class CarFilterAllowlist { @@ -21,4 +24,26 @@ public static class CarFilterAllowlist { ["plate"] = new(System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, }; + + /// Each filterable field's rule: its operators, how its values are typed and checked. + public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + { + ["plate"] = new(FilterValueKind.String, "eq", "ne", "in", "like", "isNull"), + }; + + /// The sortable fields, each with its declared @sortableDefaultOrder. + public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + { + ["plate"] = new(), + }; + + /// Every field of the entity, filterable or not, except a credential. + public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + { + "id", + "kind", + "plate", + "seatCount", + "regNo", + }; } diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoFilterAllowlist.g.cs index feb66b9426..8eaf62ddb3 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoFilterAllowlist.g.cs @@ -2,6 +2,7 @@ // Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. #nullable enable using System.Collections.Generic; +using MetaObjects.AspNetCore; namespace Acme.Shop; @@ -9,6 +10,8 @@ namespace Acme.Shop; /// GENERATED — per-entity FR-009 filter allowlist for Gizmo. /// lists the filterable field names; /// constrains the operator vocabulary for each field by its subtype. +/// , and are what +/// ListQueryParser reads a list route's query string against. /// public static class GizmoFilterAllowlist { @@ -21,4 +24,30 @@ public static class GizmoFilterAllowlist { ["title"] = new(System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, }; + + /// Each filterable field's rule: its operators, how its values are typed and checked. + public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + { + ["title"] = new(FilterValueKind.String, "eq", "ne", "in", "like", "isNull"), + }; + + /// The sortable fields, each with its declared @sortableDefaultOrder. + public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + { + ["title"] = new("desc"), + }; + + /// Every field of the entity, filterable or not, except a credential. + public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + { + "id", + "title", + "stamp", + "serial", + "tokenHash", + "createdAt", + "updatedAt", + "dims", + "extras", + }; } diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineFilterAllowlist.g.cs index 948a184142..09c92829c6 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineFilterAllowlist.g.cs @@ -2,6 +2,7 @@ // Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. #nullable enable using System.Collections.Generic; +using MetaObjects.AspNetCore; namespace Acme.Shop; @@ -9,6 +10,8 @@ namespace Acme.Shop; /// GENERATED — per-entity FR-009 filter allowlist for Line. /// lists the filterable field names; /// constrains the operator vocabulary for each field by its subtype. +/// , and are what +/// ListQueryParser reads a list route's query string against. /// public static class LineFilterAllowlist { @@ -19,4 +22,21 @@ public static class LineFilterAllowlist public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) { }; + + /// Each filterable field's rule: its operators, how its values are typed and checked. + public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + { + }; + + /// The sortable fields, each with its declared @sortableDefaultOrder. + public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + { + }; + + /// Every field of the entity, filterable or not, except a credential. + public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + { + "id", + "label", + }; } diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsFilterAllowlist.g.cs index 1bff83183d..236a7a132c 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsFilterAllowlist.g.cs @@ -2,6 +2,7 @@ // Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. #nullable enable using System.Collections.Generic; +using MetaObjects.AspNetCore; namespace Acme.Shop; @@ -9,6 +10,8 @@ namespace Acme.Shop; /// GENERATED — per-entity FR-009 filter allowlist for LineTotals. /// lists the filterable field names; /// constrains the operator vocabulary for each field by its subtype. +/// , and are what +/// ListQueryParser reads a list route's query string against. /// public static class LineTotalsFilterAllowlist { @@ -23,4 +26,25 @@ public static class LineTotalsFilterAllowlist ["label"] = new(System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, ["lines"] = new(System.StringComparer.Ordinal) { "eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull" }, }; + + /// Each filterable field's rule: its operators, how its values are typed and checked. + public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + { + ["label"] = new(FilterValueKind.String, "eq", "ne", "in", "like", "isNull"), + ["lines"] = new(FilterValueKind.Number, "eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull") { Integer = true }, + }; + + /// The sortable fields, each with its declared @sortableDefaultOrder. + public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + { + ["label"] = new(), + ["lines"] = new(), + }; + + /// Every field of the entity, filterable or not, except a credential. + public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + { + "label", + "lines", + }; } diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagFilterAllowlist.g.cs index 60c41974b5..5b2e42d06a 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagFilterAllowlist.g.cs @@ -2,6 +2,7 @@ // Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. #nullable enable using System.Collections.Generic; +using MetaObjects.AspNetCore; namespace Acme.Shop; @@ -9,6 +10,8 @@ namespace Acme.Shop; /// GENERATED — per-entity FR-009 filter allowlist for Tag. /// lists the filterable field names; /// constrains the operator vocabulary for each field by its subtype. +/// , and are what +/// ListQueryParser reads a list route's query string against. /// public static class TagFilterAllowlist { @@ -19,4 +22,21 @@ public static class TagFilterAllowlist public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) { }; + + /// Each filterable field's rule: its operators, how its values are typed and checked. + public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + { + }; + + /// The sortable fields, each with its declared @sortableDefaultOrder. + public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + { + }; + + /// Every field of the entity, filterable or not, except a credential. + public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + { + "id", + "name", + }; } diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VanFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VanFilterAllowlist.g.cs index 0444514ca1..5f5e0fd181 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VanFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VanFilterAllowlist.g.cs @@ -2,6 +2,7 @@ // Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. #nullable enable using System.Collections.Generic; +using MetaObjects.AspNetCore; namespace Acme.Shop; @@ -9,6 +10,8 @@ namespace Acme.Shop; /// GENERATED — per-entity FR-009 filter allowlist for Van. /// lists the filterable field names; /// constrains the operator vocabulary for each field by its subtype. +/// , and are what +/// ListQueryParser reads a list route's query string against. /// public static class VanFilterAllowlist { @@ -21,4 +24,25 @@ public static class VanFilterAllowlist { ["plate"] = new(System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, }; + + /// Each filterable field's rule: its operators, how its values are typed and checked. + public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + { + ["plate"] = new(FilterValueKind.String, "eq", "ne", "in", "like", "isNull"), + }; + + /// The sortable fields, each with its declared @sortableDefaultOrder. + public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + { + ["plate"] = new(), + }; + + /// Every field of the entity, filterable or not, except a credential. + public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + { + "id", + "kind", + "plate", + "payloadKg", + }; } diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleFilterAllowlist.g.cs index 345446a7f2..3c75c85722 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleFilterAllowlist.g.cs @@ -2,6 +2,7 @@ // Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. #nullable enable using System.Collections.Generic; +using MetaObjects.AspNetCore; namespace Acme.Shop; @@ -9,6 +10,8 @@ namespace Acme.Shop; /// GENERATED — per-entity FR-009 filter allowlist for Vehicle. /// lists the filterable field names; /// constrains the operator vocabulary for each field by its subtype. +/// , and are what +/// ListQueryParser reads a list route's query string against. /// public static class VehicleFilterAllowlist { @@ -21,4 +24,24 @@ public static class VehicleFilterAllowlist { ["plate"] = new(System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, }; + + /// Each filterable field's rule: its operators, how its values are typed and checked. + public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + { + ["plate"] = new(FilterValueKind.String, "eq", "ne", "in", "like", "isNull"), + }; + + /// The sortable fields, each with its declared @sortableDefaultOrder. + public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + { + ["plate"] = new(), + }; + + /// Every field of the entity, filterable or not, except a credential. + public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + { + "id", + "kind", + "plate", + }; } diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagFilterAllowlist.g.cs index 6791ce02e7..389504e98f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagFilterAllowlist.g.cs @@ -2,6 +2,7 @@ // Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. #nullable enable using System.Collections.Generic; +using MetaObjects.AspNetCore; namespace Acme.Shop; @@ -9,6 +10,8 @@ namespace Acme.Shop; /// GENERATED — per-entity FR-009 filter allowlist for VehicleTag. /// lists the filterable field names; /// constrains the operator vocabulary for each field by its subtype. +/// , and are what +/// ListQueryParser reads a list route's query string against. /// public static class VehicleTagFilterAllowlist { @@ -19,4 +22,21 @@ public static class VehicleTagFilterAllowlist public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) { }; + + /// Each filterable field's rule: its operators, how its values are typed and checked. + public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + { + }; + + /// The sortable fields, each with its declared @sortableDefaultOrder. + public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + { + }; + + /// Every field of the entity, filterable or not, except a credential. + public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + { + "vehicleId", + "tagId", + }; } diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryFilterAllowlist.g.cs index 69644c321b..b64b1c4e6d 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryFilterAllowlist.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryFilterAllowlist.g.cs @@ -2,6 +2,7 @@ // Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. #nullable enable using System.Collections.Generic; +using MetaObjects.AspNetCore; namespace Acme.Shop; @@ -9,6 +10,8 @@ namespace Acme.Shop; /// GENERATED — per-entity FR-009 filter allowlist for WidgetSummary. /// lists the filterable field names; /// constrains the operator vocabulary for each field by its subtype. +/// , and are what +/// ListQueryParser reads a list route's query string against. /// public static class WidgetSummaryFilterAllowlist { @@ -19,4 +22,20 @@ public static class WidgetSummaryFilterAllowlist public static readonly Dictionary> OpsByField = new(System.StringComparer.Ordinal) { }; + + /// Each filterable field's rule: its operators, how its values are typed and checked. + public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + { + }; + + /// The sortable fields, each with its declared @sortableDefaultOrder. + public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + { + }; + + /// Every field of the entity, filterable or not, except a credential. + public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + { + "widgetId", + }; } diff --git a/server/csharp/MetaObjects.Codegen.Tests/HelperRuntimeTests.cs b/server/csharp/MetaObjects.Codegen.Tests/HelperRuntimeTests.cs index b47095c827..7ec67bd486 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/HelperRuntimeTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/HelperRuntimeTests.cs @@ -78,7 +78,7 @@ public void Only_generators_whose_output_imports_the_runtime_carry_the_marker() .Where(e => HelperRuntime.UsedBy(EjectableGenerators.ReadSourceFile(e.SourceFileName!))) .Select(e => e.Name) .ToList(); - Assert.Equal(["routes"], users); + Assert.Equal(["filter-allowlist", "routes"], users); var rewritten = EjectableGenerators.RewriteForEject(EjectableGenerators.ReadSource("routes")!); Assert.DoesNotContain(HelperRuntime.GeneratorMarkerLine, rewritten); @@ -150,8 +150,9 @@ public void The_helper_set_is_closed_and_compiles_without_any_MetaObjects_assemb "does not hand over:\n" + string.Join("\n", errors)); } - /// What an adopter who ejected routes generates: the packaged entity / - /// db-context / filter-allowlist / names output plus the OWNED routes copy's output. + /// What an adopter who ejected routes and the filter allowlist generates: the packaged + /// entity / db-context / names output plus the OWNED routes and allowlist copies' output (the + /// allowlist's rules are helper-runtime types, so it binds to the owned runtime too). private static List GenerateWithEjectedRoutes() { var root = EjectedGeneratorCompileTests.LoadCorpus(); @@ -162,9 +163,10 @@ private static List GenerateWithEjectedRoutes() Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", IncludeNames = true }, }; var ownedRoutes = EjectedGeneratorsAloneTests.EjectAlone("routes").Generator; + var ownedAllowlist = EjectedGeneratorsAloneTests.EjectAlone("filter-allowlist").Generator; var generators = new List { - new EntityGenerator(), new DbContextGenerator(), new FilterAllowlistGenerator(), new NamesGenerator(), ownedRoutes, + new EntityGenerator(), new DbContextGenerator(), ownedAllowlist, new NamesGenerator(), ownedRoutes, }; return generators.SelectMany(g => g.Generate(ctx)).ToList(); } diff --git a/server/csharp/MetaObjects.Codegen.Tests/ListQueryConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ListQueryConformanceTests.cs new file mode 100644 index 0000000000..f45ea64d6e --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/ListQueryConformanceTests.cs @@ -0,0 +1,84 @@ +// The C# runner for fixtures/list-query-conformance/: every shared parse case (a query string in, +// the parsed list query or the exact 400 body out) through MetaObjects.AspNetCore's +// ListQueryParser, against the allowlist FilterAllowlistGenerator derives from the corpus's +// meta.json. The allowlist is derived, never written here, so a generator that derives a +// different one fails the same cases a parser bug would. + +using System.Text.Json; +using System.Text.Json.Nodes; +using MetaObjects.AspNetCore; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class ListQueryConformanceTests +{ + private static readonly string Dir = + Path.Combine(CorpusPaths.RepoRoot(), "fixtures", "list-query-conformance"); + + private sealed record Allowlist( + IReadOnlyDictionary Rules, + IReadOnlyDictionary Sort, + IReadOnlySet FieldNames); + + private static readonly Lazy Ticket = new(() => + { + var result = new MetaDataLoader().Load([new FileSource(Path.Combine(Dir, "meta.json"))]); + Assert.True(result.Errors.Count == 0, string.Join("; ", result.Errors.Select(e => e.ToString()))); + var entity = result.Root.Objects().Single(o => o.Name == "Ticket"); + var rules = new Dictionary(StringComparer.Ordinal); + foreach (var (field, spec) in FilterAllowlistGenerator.FilterRules(entity, result.Root)) + rules[field] = new FilterFieldRule(Enum.Parse(spec.Kind), spec.Ops.ToArray()) + { + Format = spec.Format, Instant = spec.Instant, Integer = spec.Integer, EnumValues = spec.EnumValues, + }; + var sort = new Dictionary(StringComparer.Ordinal); + foreach (var (field, order) in FilterAllowlistGenerator.SortRules(entity, result.Root)) sort[field] = new SortFieldRule(order); + return new Allowlist(rules, sort, entity.Fields().Select(f => f.Name).ToHashSet(StringComparer.Ordinal)); + }); + + public static IEnumerable Cases() + { + using var doc = JsonDocument.Parse(File.ReadAllText(Path.Combine(Dir, "cases.json"))); + foreach (var c in doc.RootElement.GetProperty("cases").EnumerateArray()) + yield return new object[] { c.GetProperty("name").GetString()! }; + } + + [Theory] + [MemberData(nameof(Cases))] + public void Case_parses_as_the_corpus_says(string name) + { + var all = JsonNode.Parse(File.ReadAllText(Path.Combine(Dir, "cases.json")))!["cases"]!.AsArray(); + var c = all.Single(n => (string)n!["name"]! == name)!; + var a = Ticket.Value; + var result = ListQueryParser.Parse((string)c["query"]!, a.Rules, a.Sort, a.FieldNames); + var actual = result.Ok ? new JsonObject { ["list"] = ToJson(result.Query!) } : new JsonObject { ["error"] = Reparse(result.Error!.Body()) }; + var expected = c["expect"]!; + Assert.True(JsonNode.DeepEquals(expected, actual), + $"{name} ({c["query"]}):\n expected {expected.ToJsonString()}\n actual {actual.ToJsonString()}"); + } + + private static JsonNode Reparse(object value) => JsonNode.Parse(JsonSerializer.Serialize(value))!; + + private static JsonObject ToJson(ListQuery q) + { + var o = new JsonObject(); + if (q.Filter is not null) o["filter"] = Node(q.Filter); + if (q.Search is not null) o["search"] = Reparse(new { term = q.Search.Term, fields = q.Search.Fields }); + if (q.Sort is not null) o["sort"] = Reparse(new { field = q.Sort.Field, order = q.Sort.Order }); + if (q.Limit is not null) o["limit"] = q.Limit; + if (q.Offset is not null) o["offset"] = q.Offset; + return o; + } + + private static JsonNode Node(FilterNode node) => node switch + { + FilterLeaf l => new JsonObject { ["field"] = l.Field, ["op"] = l.Op, ["value"] = Reparse(l.Value) }, + FilterAnd and => new JsonObject { ["and"] = new JsonArray(and.Nodes.Select(Node).ToArray()) }, + FilterOr or => new JsonObject { ["or"] = new JsonArray(or.Nodes.Select(Node).ToArray()) }, + _ => throw new InvalidOperationException(node.GetType().Name), + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/ReportingInertTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ReportingInertTests.cs index d949379215..f5b52d7cca 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ReportingInertTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ReportingInertTests.cs @@ -139,6 +139,7 @@ private static readonly (string Generator, string File)[] ReportFiles = // Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. #nullable enable using System.Collections.Generic; + using MetaObjects.AspNetCore; namespace MetaObjects.ReportingInert.Generated; @@ -146,6 +147,8 @@ namespace MetaObjects.ReportingInert.Generated; /// GENERATED — per-entity FR-009 filter allowlist for StoreTotals. /// lists the filterable field names; /// constrains the operator vocabulary for each field by its subtype. + /// , and are what + /// ListQueryParser reads a list route's query string against. /// public static class StoreTotalsFilterAllowlist { @@ -162,6 +165,30 @@ public static class StoreTotalsFilterAllowlist ["buyers"] = new(System.StringComparer.Ordinal) { "eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull" }, ["revenue"] = new(System.StringComparer.Ordinal) { "eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull" }, }; + + /// Each filterable field's rule: its operators, how its values are typed and checked. + public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal) + { + ["purchases"] = new(FilterValueKind.Number, "eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull") { Integer = true }, + ["buyers"] = new(FilterValueKind.Number, "eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull") { Integer = true }, + ["revenue"] = new(FilterValueKind.Number, "eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull") { Integer = true }, + }; + + /// The sortable fields, each with its declared @sortableDefaultOrder. + public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal) + { + ["purchases"] = new(), + ["buyers"] = new(), + ["revenue"] = new(), + }; + + /// Every field of the entity, filterable or not, except a credential. + public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal) + { + "purchases", + "buyers", + "revenue", + }; } """; diff --git a/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs index 46effc4e29..67fad041cc 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs @@ -28,6 +28,10 @@ public class FilterAllowlistGenerator : PerEntityGenerator { public override string Name => "filter-allowlist-generator"; + // Where the emitted allowlist imports FilterFieldRule / SortFieldRule from. `dotnet meta eject` + // rewrites this one line to "Codegen.Runtime" and copies the helpers into codegen/runtime/. + private const string HelperRuntimeNamespace = "MetaObjects.AspNetCore"; + public override bool Filter(MetaObject entity) => AppliesTo(entity); /// @@ -92,6 +96,12 @@ protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) WriteFields(w, opsByField); w.Blank(); WriteOpsByField(w, opsByField); + w.Blank(); + WriteRules(w, RulesFrom(entity, opsByField)); + w.Blank(); + WriteSortRules(w, SortRules(entity, ctx.Root)); + w.Blank(); + WriteFieldNames(w, FieldNames(entity, ctx.Root)); // The field -> CLR property map, only when a property-naming resolver renamed a property // beyond case (the runtime matches a field to its property case-insensitively, which // covers every other spelling). Nothing is emitted otherwise, so default output is unchanged. @@ -117,13 +127,16 @@ protected virtual void WriteFileHeader(CsWriter w) { w.GeneratedFileHeader("filter-allowlist-generator"); w.Using("System.Collections.Generic"); + w.Using(HelperRuntimeNamespace); } /// The XML doc on the allowlist class. protected virtual void WriteTypeDoc(CsWriter w, string cls) => w.DocSummary( $"GENERATED — per-entity FR-009 filter allowlist for {cls}.", " lists the filterable field names; ", - "constrains the operator vocabulary for each field by its subtype."); + "constrains the operator vocabulary for each field by its subtype.", + ", and are what", + "ListQueryParser reads a list route's query string against."); /// The Fields set: the filterable field names. Ordinal comparison, because the URL grammar is case-exact. protected virtual void WriteFields(CsWriter w, IReadOnlyDictionary> opsByField) @@ -144,6 +157,66 @@ protected virtual void WriteOpsByField(CsWriter w, IReadOnlyDictionary + /// The Rules dictionary the list query parser (ListQueryParser) reads: per filterable + /// field its operators, value kind and value checks. + /// + protected virtual void WriteRules(CsWriter w, IReadOnlyList<(string Field, FilterRuleSpec Rule)> rules) + { + w.Line("/// Each filterable field's rule: its operators, how its values are typed and checked."); + using (w.Braced("public static readonly IReadOnlyDictionary Rules = new Dictionary(System.StringComparer.Ordinal)", "};")) + { + foreach (var (field, rule) in rules) + { + var init = new List(); + if (rule.Format is not null) init.Add($"Format = FilterValueFormats.{CSharpNaming.Pascal(rule.Format)}"); + if (rule.Instant) init.Add("Instant = true"); + if (rule.Integer) init.Add("Integer = true"); + if (rule.EnumValues is not null) init.Add($"EnumValues = new[] {{ {string.Join(", ", rule.EnumValues.Select(m => $"\"{m}\""))} }}"); + var ops = string.Join(", ", rule.Ops.Select(op => $"\"{op}\"")); + var tail = init.Count == 0 ? "" : $" {{ {string.Join(", ", init)} }}"; + w.Line($"[\"{field}\"] = new(FilterValueKind.{rule.Kind}, {ops}){tail},"); + } + } + } + + /// The Sort dictionary: the sortable fields, each with its declared default order. + protected virtual void WriteSortRules(CsWriter w, IReadOnlyList<(string Field, string? DefaultOrder)> rules) + { + w.Line("/// The sortable fields, each with its declared @sortableDefaultOrder."); + using (w.Braced("public static readonly IReadOnlyDictionary Sort = new Dictionary(System.StringComparer.Ordinal)", "};")) + { + foreach (var (field, order) in rules) + w.Line(order is null ? $"[\"{field}\"] = new()," : $"[\"{field}\"] = new(\"{order}\"),"); + } + } + + /// + /// The FieldNames set: every field of the entity, so a bare ?notes=x for a field that + /// is not filterable is refused with a reason instead of ignored. + /// + protected virtual void WriteFieldNames(CsWriter w, IReadOnlyList names) + { + w.Line("/// Every field of the entity, filterable or not, except a credential."); + using (w.Braced("public static readonly IReadOnlySet FieldNames = new HashSet(System.StringComparer.Ordinal)", "};")) + { + foreach (var name in names) w.Line($"\"{name}\","); + } + } + + /// + /// The names FieldNames lists: every field of but a credential + /// (its own, or a column a sibling TPH subtype marks as one). A bare parameter naming a + /// credential is ignored like any unknown parameter, so the refusal never confirms the column. + /// + public static IReadOnlyList FieldNames(MetaObject entity, MetaRoot root) + { + var hierarchyCredentials = TphPlanBuilder.HierarchyCredentialNames(entity, root); + return entity.Fields() + .Where(f => !InstanceArtifacts.IsCredentialField(f) && !hierarchyCredentials.Contains(f.Name)) + .Select(f => f.Name).ToList(); + } + /// The PropertyByField map, for a field whose CLR property is named beyond case. protected virtual void WritePropertyByField(CsWriter w, IReadOnlyDictionary renamed) { @@ -160,7 +233,9 @@ protected virtual void WritePropertyByField(CsWriter w, IReadOnlyDictionary - protected virtual Dictionary> ComputeFilterableOps(MetaObject entity) + protected virtual Dictionary> ComputeFilterableOps(MetaObject entity) => ComputeOps(entity); + + private static Dictionary> ComputeOps(MetaObject entity) { var out_ = new Dictionary>(System.StringComparer.Ordinal); foreach (var field in entity.Fields()) @@ -177,6 +252,100 @@ protected virtual Dictionary> ComputeFilterableOps return out_; } + /// + /// The filter rules of , as data: what <Entity>FilterAllowlist.Rules + /// carries, in field order. The same derivation as TypeScript's filterAllowlistRules, so both + /// ports hold the shared list-query parse cases. Public so a runner, or an owned generator, derives + /// the allowlist this one emits. + /// + public static IReadOnlyList<(string Field, FilterRuleSpec Rule)> FilterRules(MetaObject entity, MetaRoot root) + { + var hierarchyCredentials = TphPlanBuilder.HierarchyCredentialNames(entity, root); + return RulesFrom(entity, ComputeOps(entity).Where(kv => !hierarchyCredentials.Contains(kv.Key)) + .ToDictionary(kv => kv.Key, kv => kv.Value, System.StringComparer.Ordinal)); + } + + // Each field of the operator map, with its rule; the map is the generator's (overridable) answer. + private static IReadOnlyList<(string Field, FilterRuleSpec Rule)> RulesFrom( + MetaObject entity, IReadOnlyDictionary> opsByField) + { + var fields = new Dictionary(System.StringComparer.Ordinal); + foreach (var f in entity.Fields()) fields.TryAdd(f.Name, f); + return opsByField + .Select(kv => (kv.Key, fields.TryGetValue(kv.Key, out var f) ? RuleFor(f, kv.Value) : new FilterRuleSpec(kv.Value, "String"))) + .ToList(); + } + + /// + /// The sortable fields of and their declared default order: explicit + /// @sortable: true, or no @sortable and @filterable: true. Never a credential, + /// an array, or a field with no scalar column (a value object, a map). + /// + public static IReadOnlyList<(string Field, string? DefaultOrder)> SortRules(MetaObject entity, MetaRoot root) + { + var hierarchyCredentials = TphPlanBuilder.HierarchyCredentialNames(entity, root); + var out_ = new List<(string, string?)>(); + foreach (var f in entity.Fields()) + { + if (f.SubType is FIELD_SUBTYPE_OBJECT or FIELD_SUBTYPE_MAP || f.ResolvedIsArray()) continue; + if (InstanceArtifacts.IsCredentialField(f) || hierarchyCredentials.Contains(f.Name)) continue; + var sortable = AttrBool(f.Attr(FIELD_ATTR_SORTABLE)) ?? IsFilterable(f); + if (!sortable) continue; + var order = f.Attr(FIELD_ATTR_SORTABLE_DEFAULT_ORDER) as string; + out_.Add((f.Name, order is "asc" or "desc" ? order : null)); + } + return out_; + } + + private static bool? AttrBool(object? v) => v switch + { + bool b => b, + string s when string.Equals(s, "true", StringComparison.OrdinalIgnoreCase) => true, + string s when string.Equals(s, "false", StringComparison.OrdinalIgnoreCase) => false, + _ => null, + }; + + private static readonly HashSet NumberSubtypes = new(System.StringComparer.Ordinal) + { + FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, + }; + + private static readonly HashSet IntegerSubtypes = new(System.StringComparer.Ordinal) + { + FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_CURRENCY, + }; + + private static readonly HashSet FormatSubtypes = new(System.StringComparer.Ordinal) + { + FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIME, FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_DURATION, + }; + + private static FilterRuleSpec RuleFor(MetaField f, IReadOnlyList ops) + { + var kind = f.SubType == FIELD_SUBTYPE_BOOLEAN ? "Boolean" + : NumberSubtypes.Contains(f.SubType) ? "Number" + : f.SubType is FIELD_SUBTYPE_DATE or FIELD_SUBTYPE_TIME or FIELD_SUBTYPE_TIMESTAMP ? "Datetime" + : "String"; + // Value checks hold for a scalar field only: an array field's operand is not one element. + if (f.ResolvedIsArray()) return new FilterRuleSpec(ops, kind); + if (IntegerSubtypes.Contains(f.SubType)) return new FilterRuleSpec(ops, kind, Integer: true); + if (FormatSubtypes.Contains(f.SubType)) + return new FilterRuleSpec(ops, kind, Format: f.SubType, Instant: f.SubType == FIELD_SUBTYPE_TIMESTAMP && !CSharpNaming.IsLocalTime(f)); + if (f.SubType == FIELD_SUBTYPE_ENUM) + { + // Member SYMBOLS for string- and int-backed enums alike. + // ADR-0039: resolving — @values may be inherited from an abstract enum base via extends. + var members = f.Attr(FIELD_ATTR_VALUES) switch + { + IReadOnlyList ss => ss, + IReadOnlyList os => os.Select(o => o?.ToString() ?? "").ToList(), + _ => new List(), + }; + if (members.Count > 0) return new FilterRuleSpec(ops, kind, EnumValues: members); + } + return new FilterRuleSpec(ops, kind); + } + /// True iff carries @filterable: true (bool true or case-insensitive "true" — matches Java/Kotlin/Python tolerance). // ADR-0039: resolving — @filterable may be inherited via extends (TS reads field.attr). private static bool IsFilterable(MetaField field) => field.Attr(FIELD_ATTR_FILTERABLE) switch @@ -208,3 +377,16 @@ protected virtual Dictionary> ComputeFilterableOps public static IReadOnlyList OpsForField(MetaField field) => MetaObjects.Core.Query.QueryConstants.OpsForField(field); } + +/// +/// One filterable field's rule as data (the runtime's FilterFieldRule, kept structural so +/// codegen does not depend on the runtime package). names a FilterValueKind +/// member; is the subtype whose wire format values must match. +/// +public sealed record FilterRuleSpec( + IReadOnlyList Ops, + string Kind, + string? Format = null, + bool Instant = false, + bool Integer = false, + IReadOnlyList? EnumValues = null); diff --git a/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md b/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md index 269dea6b8a..6c40143a84 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md +++ b/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md @@ -23,7 +23,7 @@ Update when a gap closes or a new one surfaces. **Contract.** `filter[or]=[...]` and `filter[and]=[...]` keys nest disjunctions / conjunctions. Reference: [`api-contract.md` "Filter operators (8)"](../../../../docs/features/api-contract.md). -**Today.** Out of scope of FR-009 (which ships the flat 9-operator surface). Boolean grouping would need a richer URL grammar; defer until a real consumer demand surfaces. +**Today.** Half closed. Since 1.3.0, `MetaObjects.AspNetCore` has `ListQueryParser`, which parses the whole list query: or/and groups to a depth of five, search, the bare-field and leading-`%` refusals, value-format checks and the named error details. `EfCoreFilterDispatch.Apply` turns the parsed tree into one `Where`. Each generated `FilterAllowlist` carries the `Rules`, `Sort` and `FieldNames` the parser reads. All 95 shared parse cases in `fixtures/list-query-conformance/` pass (`ListQueryConformanceTests`). The generated list routes do not call any of this yet; they still use the flat `FilterParser`. Wiring them up, and turning on the api-contract `list-query/` scenarios the C# runner holds back, closes this gap. ### G3 — Multi-field sort diff --git a/server/csharp/MetaObjects.Codegen/HelperRuntime.cs b/server/csharp/MetaObjects.Codegen/HelperRuntime.cs index 27653512f6..2992a248f8 100644 --- a/server/csharp/MetaObjects.Codegen/HelperRuntime.cs +++ b/server/csharp/MetaObjects.Codegen/HelperRuntime.cs @@ -78,6 +78,9 @@ public static class HelperRuntime "FilterParser.cs", "FilterParseResult.cs", "FilterPredicate.cs", + "FilterRules.cs", + "FilterValueFormat.cs", + "ListQuery.cs", "EfCoreFilterDispatch.cs", "ValueObjectValidator.cs", "ConstraintErrors.cs", diff --git a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj index af5e03e0c4..8ad370cce6 100644 --- a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj +++ b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj @@ -80,6 +80,9 @@ + + + From 96e2ea8fda2e42275c30ce00c28a3719ce92ac1e Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 04:40:12 -0500 Subject: [PATCH 4/9] feat(csharp): wire the generated list routes to ListQueryParser, name invalid_json and invalid_id (R-CS-2) Every generated C# list route (entity, projection, report, TPH base and subtype) reads its query through ListQueryParser and applies it with EfCoreFilterDispatch.Apply: ?search, filter[or]/filter[and] groups, and the bare-field, leading-wildcard and nesting refusals. Sorting reads one route-local SortRules table. A body that is not JSON answers 400 invalid_json and a path id the key cannot hold answers 400 invalid_id, through the new RouteErrors helper that eject copies with the others. The C# generated lane now runs the whole list-query/ sub-corpus, and KNOWN_GAPS G2 is closed. --- .../csharp-default-list-page-of-fifty.md | 4 +- .../csharp-rest-standard-list-routes.md | 18 ++ docs/CONFORMANCE.md | 13 +- docs/features/api-contract.md | 4 +- docs/features/own-your-codegen.md | 10 +- .../.metaobjects/.gen-state/.hashes/acme.json | 2 +- .../generated/csharp/SubscriberRoutes.g.cs | 72 +++-- .../list-query/README.md | 7 +- .../MetaObjects.AspNetCore/FilterRules.cs | 9 +- .../MetaObjects.AspNetCore/RouteErrors.cs | 44 +++ .../EntityGeneratorTests.cs | 62 ++--- .../Golden/pre-rc22-propname/GizmoRoutes.g.cs | 79 +++--- .../Golden/pre-rc22-propname/LineRoutes.g.cs | 68 ++--- .../pre-rc22-propname/LineTotalsRoutes.g.cs | 37 +-- .../Golden/pre-rc22-propname/TagRoutes.g.cs | 68 ++--- .../pre-rc22-propname/VehicleRoutes.g.cs | 194 +++++++------ .../pre-rc22-propname/VehicleTagRoutes.g.cs | 49 ++-- .../WidgetSummaryRoutes.g.cs | 47 ++-- .../HelperRuntimeTests.cs | 12 +- .../PropertyNamingEmitSitesTests.cs | 15 +- .../ReportRowCodegenTests.cs | 13 +- .../SecretFieldsCodegenTests.cs | 4 +- .../TphCodegenTests.cs | 11 +- .../Generators/KNOWN_GAPS.md | 13 +- .../Generators/RoutesGenerator.cs | 258 ++++++++---------- .../MetaObjects.Codegen/HelperRuntime.cs | 2 + .../MetaObjects.Codegen.csproj | 1 + .../ApiContractApiSettingsConformanceTest.cs | 7 +- .../ApiContractListQueryConformanceTest.cs | 38 +-- .../Api/DecimalWireGeneratedApiTests.cs | 9 +- 30 files changed, 540 insertions(+), 630 deletions(-) create mode 100644 changelog.d/csharp-rest-standard-list-routes.md create mode 100644 server/csharp/MetaObjects.AspNetCore/RouteErrors.cs diff --git a/changelog.d/csharp-default-list-page-of-fifty.md b/changelog.d/csharp-default-list-page-of-fifty.md index 48ea2b5d5d..2ca9eb2ca6 100644 --- a/changelog.d/csharp-default-list-page-of-fifty.md +++ b/changelog.d/csharp-default-list-page-of-fifty.md @@ -6,7 +6,5 @@ not a non-negative integer is now `400 pagination.invalid_value` instead of being ignored, and `limit=0` is a page of zero rows. The `dotnet meta verify --codegen` advisory `unbounded-list-pages` is retired. Generated-output change — regenerate to pick it up; three-way merge preserves hand - edits. The C# generated lane now runs the shared `list-query/` sub-corpus: the paging and - refusal scenarios its routes answer today, with search and `or`/`and` to follow. Regenerate, and - check any client that reads a whole list without a `limit`: + edits. Check any client that reads a whole list without a `limit`: [docs/features/migrations/default-list-page-of-fifty.md](docs/features/migrations/default-list-page-of-fifty.md). diff --git a/changelog.d/csharp-rest-standard-list-routes.md b/changelog.d/csharp-rest-standard-list-routes.md new file mode 100644 index 0000000000..c50d831840 --- /dev/null +++ b/changelog.d/csharp-rest-standard-list-routes.md @@ -0,0 +1,18 @@ +- **C#: the generated list routes speak the REST standard.** Every entity, projection, report and + single-table-hierarchy list route now reads its query through `ListQueryParser`: `?search=` + (case-insensitive, over the filterable text fields), `filter[or][i]` / `filter[and][i]` groups + five levels deep, and the named refusals `filter.bare_field` (a `?name=` outside `filter[...]`, + which used to answer every row), `filter.leading_wildcard_disallowed`, `filter.nesting_too_deep` + and `invalid_filter_value` for a value of the wrong format. A refusal's body carries the shared + details (`field`, `expected`, `allowed`), so an `invalid_sort` lists the sortable fields. A body + that is not JSON is now `400 {"error": "invalid_json"}` (it was the `validation` body), and a + path id the key cannot hold is `400 {"error": "invalid_id"}` on every item route (it was an + empty 400 from ASP.NET Core's binding). The sortable set is unchanged. The routes read the new + `RouteErrors` helper in `MetaObjects.AspNetCore`, and `dotnet meta eject routes` copies it with + the others. The C# generated lane now runs the whole `list-query/` sub-corpus, closing the C# + routes' `KNOWN_GAPS.md` G2. Generated-output change — regenerate to pick it up; three-way merge + preserves hand edits. + + Upgrading: a client that sent a bare `?field=value` and read every row back now gets a 400; + send `filter[field][eq]=value`. A client that matched the `validation` body of a malformed JSON + request should match `invalid_json`. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 5aaecd9c3d..340c477b5c 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -36,7 +36,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`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/) | 68 (56 query + 12 migration) | all 68; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` and `guarded-update` also on MySQL (a scenario's `engines:` key is exact) | 55 query (migrations TS-only, ADR-0015; `guarded-update` deferred to L-JV-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (via Exposed; `guarded-update` deferred to L-KT-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (`guarded-update` deferred to L-CS-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (pg8000; `guarded-update` deferred to L-PY-2); the `report-*` and `engines:` scenarios also on SQLite (`sqlite3`) and MySQL (PyMySQL) | -| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 179 (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 + 21 list-query + 17 rules) | ✓ (Fastify reference + generated lane; service lanes on Fastify and Hono for the entity, `projection/`, `report/`, `write-through/`, `tph/`, `m2m/`, `decimal/` and `secret-fields/` sub-corpora, see the [api-contract README](../fixtures/api-contract-conformance/README.md#ts-lanes-illustrative-detail)); `report/`, `decimal/` and `duration/` also on SQLite, MySQL and D1; `list-query/` runs in full in TypeScript and in part in C# (the paging and refusal scenarios its routes answer today; the rest with its 1.3.0 REST-standard work), and in no other port until that port's 1.3.0 REST-standard work; `rules/` is TypeScript-only until each port's 1.3.0 service 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/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 179 (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 + 21 list-query + 17 rules) | ✓ (Fastify reference + generated lane; service lanes on Fastify and Hono for the entity, `projection/`, `report/`, `write-through/`, `tph/`, `m2m/`, `decimal/` and `secret-fields/` sub-corpora, see the [api-contract README](../fixtures/api-contract-conformance/README.md#ts-lanes-illustrative-detail)); `report/`, `decimal/` and `duration/` also on SQLite, MySQL and D1; `list-query/` runs in full in TypeScript and C#, and in no other port until that port's 1.3.0 REST-standard work; `rules/` is TypeScript-only until each port's 1.3.0 service 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`) | @@ -54,7 +54,7 @@ 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/) | 6 | ✓ (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/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) | ✓ (`ListQueryConformanceTests`) | 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 | | [`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 | ✓ | ✓ | @@ -582,7 +582,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`), `rules/` (17, ADR-0066 through a generated service: derived and declared commands, a query, permission points, the three 409 codes, a declared error and a refusal rolling back, under the default settings and three `rules.*` variants; generated lane, TypeScript only until each port's 1.3.0 service work), `list-query/` (21, 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, a default page of 50, paging past 50, and the `invalid_json`, `invalid_id`, `pagination.invalid_value` and `constraint_violation` refusals; generated lane, TypeScript in full and C# in part until each port's 1.3.0 REST-standard work) and `report/` (37, +`api.unknownFields: drop`), `rules/` (17, ADR-0066 through a generated service: derived and declared commands, a query, permission points, the three 409 codes, a declared error and a refusal rolling back, under the default settings and three `rules.*` variants; generated lane, TypeScript only until each port's 1.3.0 service work), `list-query/` (21, 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, a default page of 50, paging past 50, and the `invalid_json`, `invalid_id`, `pagination.invalid_value` and `constraint_violation` refusals; generated lane, TypeScript and C# 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, @@ -828,9 +828,10 @@ generator does, so a port that derives a different allowlist fails here. What a 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 +(the source of the expected answers) and +`server/csharp/MetaObjects.Codegen.Tests/ListQueryConformanceTests.cs`. **Conformance status:** +TypeScript and C# pass; 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) diff --git a/docs/features/api-contract.md b/docs/features/api-contract.md index 80b2ecc66e..19f42c84f5 100644 --- a/docs/features/api-contract.md +++ b/docs/features/api-contract.md @@ -197,8 +197,8 @@ TypeScript's wire names unchanged. Two corpora hold every port to them: 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 +**Conformance status:** TypeScript and C# pass both corpora; 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. diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index d86fe54572..2fe0612360 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -1706,10 +1706,12 @@ generated routes calls them, so an owned routes generator comes with owned copie Otherwise a bug in the filter parser would still mean waiting for a MetaObjects release. `dotnet meta eject routes` therefore also writes their source to `codegen/runtime/`: -`FilterParser.cs`, `FilterParseResult.cs`, `FilterPredicate.cs`, -`EfCoreFilterDispatch.cs`, `ValueObjectValidator.cs`, `ValidationIssues.cs`, `UnknownFieldCheck.cs`, `ConstraintErrors.cs` and -`Iso8601TimestampConverter.cs`, the converter your host registers for the api contract's -timestamp spelling. Each file is the packaged source with one change: its namespace becomes +`FilterParser.cs`, `FilterParseResult.cs`, `FilterPredicate.cs`, `FilterRules.cs`, +`FilterValueFormat.cs`, `ListQuery.cs`, `EfCoreFilterDispatch.cs`, `ValueObjectValidator.cs`, +`ConstraintErrors.cs`, `ValidationIssues.cs`, `UnknownFieldCheck.cs`, `DecimalWire.cs`, +`DurationWire.cs`, `DecimalRangeEndpointFilter.cs`, `ReportExportHttp.cs`, `SerializerKeys.cs`, +`RouteErrors.cs` and `Iso8601TimestampConverter.cs`, the converter your host registers for the +api contract's timestamp spelling. Each file is the packaged source with one change: its namespace becomes `Codegen.Runtime`, matching the folder the way `codegen/generators/` matches `Codegen.Generators`. The ejected `RoutesGenerator.cs` differs from the reference in one more line, its `HelperRuntimeNamespace` constant, so its output says diff --git a/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json index 6983ab325a..c9a69bb2f5 100644 --- a/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json +++ b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json @@ -3,7 +3,7 @@ "generated/csharp/SubscriberBlurbPayload.g.cs": "29eb3a6ce64496ffe734cba55d0213994316b4281d3fa6791917393bae36c9ed", "generated/csharp/SubscriberFilterAllowlist.g.cs": "9adb22081b65d6f29aa303f84e632f051bc19e85fefc2c93701c137bceb17da5", "generated/csharp/SubscriberNames.g.cs": "c2cf0248c2ecde155ec2623604771e39bed23783603d6f18a2ed82967227a732", - "generated/csharp/SubscriberRoutes.g.cs": "59cab9100550a5f947828adbed92f5f32d5f2207459a3a03180f8e761881dbee", + "generated/csharp/SubscriberRoutes.g.cs": "aa0f84ecfd31ee5a72773cc919d5c0b5bddaca991394c619b3f377e9770bb53c", "generated/python/Subscriber.py": "f56ff38ba40240ca6a3c1284d2928d76ba42fa06dd18fc6b824c418ee78b73f9", "generated/python/SubscriberBlurbPayload.py": "0ab9c17c4acc8c8b63803f4946bb1c1e30dbaf04581cc5ff60d07f563b6c3266", "generated/python/subscriber_filter_allowlist.py": "1762fb8b41516c9ca4d4384563046b73c25ed681e4e5da3db19d7d290f9e8b25", diff --git a/examples/showcase/generated/csharp/SubscriberRoutes.g.cs b/examples/showcase/generated/csharp/SubscriberRoutes.g.cs index 66434bbb94..118ec62e35 100644 --- a/examples/showcase/generated/csharp/SubscriberRoutes.g.cs +++ b/examples/showcase/generated/csharp/SubscriberRoutes.g.cs @@ -12,16 +12,12 @@ namespace Acme; public static class SubscriberRoutes { - private static readonly System.Collections.Generic.HashSet SortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) - { - "Id", - "Email", - "Name", - "CreatedAt", - }; - - private static readonly System.Collections.Generic.Dictionary SortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly System.Collections.Generic.Dictionary SortRules = new(System.StringComparer.OrdinalIgnoreCase) { + ["Id"] = new SortFieldRule(property: "Id"), + ["Email"] = new SortFieldRule(property: "Email"), + ["Name"] = new SortFieldRule(property: "Name"), + ["CreatedAt"] = new SortFieldRule(property: "CreatedAt"), }; // api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400. @@ -50,37 +46,26 @@ public static IEndpointRouteBuilder MapSubscriberRoutes(this IEndpointRouteBuild var qs = http.Request.Query; IQueryable q = db.Subscribers.AsNoTracking(); - // Filter: ?filter[][]= against the per-entity allowlist. - var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, SubscriberFilterAllowlist.Fields, SubscriberFilterAllowlist.OpsByField)); - if (filter.ErrorEnvelope is not null) - return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); - q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); - - // Sort: ?sort=field:asc|desc against the static allowlist. - if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + // ?filter[...] (or/and groups), ?search, ?sort and the page bounds, against the allowlist. + var __parsed = ListQueryParser.Parse(http.Request.QueryString.Value, SubscriberFilterAllowlist.Rules, SortRules, SubscriberFilterAllowlist.FieldNames); + if (__parsed.Error is { } __refused) return Results.BadRequest(__refused.Body()); + var listQuery = __parsed.Query!; + if (EfCoreFilterDispatch.Validate(listQuery) is { } __invalid) return Results.BadRequest(__invalid.Body()); + q = EfCoreFilterDispatch.Apply(q, listQuery, SubscriberFilterAllowlist.Rules); + if (listQuery.Sort is { } __sort && SortRules[__sort.Field].Property is { } __sortProp) { - var parts = sortRaw.ToString().Split(':', 2); - var field = parts[0]; - if (!SortAllowlist.TryGetValue(field, out var resolved)) - return Results.BadRequest(new { error = "invalid_sort", field }); - var desc = parts.Length > 1 - ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) - : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; - q = ApplySortSubscriber(q, resolved, desc); + var desc = __sort.Descending; + q = ApplySortSubscriber(q, __sortProp, desc); } // Pagination: ?offset=N first (skip), then ?limit=N (take). - if (qs.TryGetValue("offset", out var offsetRawBad) && !(int.TryParse(offsetRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offsetBad) && offsetBad >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offsetRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); - if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) - q = q.Skip(offset); - if (qs.TryGetValue("limit", out var limitRawNeg) && !(long.TryParse(limitRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limitNeg) && limitNeg >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limitRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + if (listQuery.Offset is { } __offset && __offset > 0) + q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; - if (qs.TryGetValue("limit", out var limitRaw) && long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit >= 0) + if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(limit, int.MaxValue); + __take = (int)System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); @@ -89,15 +74,18 @@ public static IEndpointRouteBuilder MapSubscriberRoutes(this IEndpointRouteBuild // withCount=1 → { rows, total } envelope; otherwise bare row array. var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return Results.Ok(rows); - var totalQ = EfCoreFilterDispatch.ApplyFilter(db.Subscribers.AsNoTracking(), filter.Predicates); + var totalQ = EfCoreFilterDispatch.Apply(db.Subscribers.AsNoTracking(), listQuery, SubscriberFilterAllowlist.Rules); var total = await totalQ.CountAsync(); return Results.Ok(new { rows, total }); }); - app.MapGet(prefix + "/subscribers/{id}", async (long id, AppDbContext db) => - await db.Subscribers.FindAsync(id) is { } found + app.MapGet(prefix + "/subscribers/{id}", async (HttpContext http, AppDbContext db) => + { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); + return await db.Subscribers.FindAsync(id) is { } found ? Results.Ok(found) - : Results.NotFound(new { error = "not_found" })); + : Results.NotFound(new { error = "not_found" }); + }); app.MapPost(prefix + "/subscribers", async (HttpContext http, AppDbContext db) => { @@ -106,7 +94,7 @@ await db.Subscribers.FindAsync(id) is { } found .Value.SerializerOptions; System.Text.Json.JsonDocument __body; try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var __bodyScope = __body; if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); @@ -139,13 +127,14 @@ await db.Subscribers.FindAsync(id) is { } found return Results.Created(prefix + "/subscribers", input); }); - async System.Threading.Tasks.Task UpdateSubscriber(long id, HttpContext http, AppDbContext db) + async System.Threading.Tasks.Task UpdateSubscriber(HttpContext http, AppDbContext db) { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Subscribers.FindAsync(id); if (existing is null) return Results.NotFound(new { error = "not_found" }); System.Text.Json.JsonDocument body; try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var bodyScope = body; if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown; @@ -201,8 +190,9 @@ async System.Threading.Tasks.Task UpdateSubscriber(long id, HttpContext app.MapPatch(prefix + "/subscribers/{id}", UpdateSubscriber); app.MapPut(prefix + "/subscribers/{id}", UpdateSubscriber); - app.MapDelete(prefix + "/subscribers/{id}", async (long id, AppDbContext db) => + app.MapDelete(prefix + "/subscribers/{id}", async (HttpContext http, AppDbContext db) => { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Subscribers.FindAsync(id); if (existing is null) return Results.NotFound(new { error = "not_found" }); db.Subscribers.Remove(existing); diff --git a/fixtures/api-contract-conformance/list-query/README.md b/fixtures/api-contract-conformance/list-query/README.md index b6f7d3ee64..9571d650e5 100644 --- a/fixtures/api-contract-conformance/list-query/README.md +++ b/fixtures/api-contract-conformance/list-query/README.md @@ -51,8 +51,5 @@ 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), and C# `server/csharp/MetaObjects.IntegrationTests/Api/ApiContractListQueryConformanceTest.cs` (the -generated routes on Kestrel against Postgres). The C# runner names the scenarios its routes do -not answer yet (`NotYetInCSharp`: search, `or`/`and`, the bare-field and leading-`%` refusals, -`invalid_json` and `invalid_id`, which land with its 1.3.0 REST-standard work) and runs every -other one, the paging scenarios included. The other ports' runners arrive with their 1.3.0 -REST-standard work. +generated routes on Kestrel against Postgres). Both run every scenario. The other ports' +runners arrive with their 1.3.0 REST-standard work. diff --git a/server/csharp/MetaObjects.AspNetCore/FilterRules.cs b/server/csharp/MetaObjects.AspNetCore/FilterRules.cs index 965d055ce0..942401149c 100644 --- a/server/csharp/MetaObjects.AspNetCore/FilterRules.cs +++ b/server/csharp/MetaObjects.AspNetCore/FilterRules.cs @@ -75,8 +75,15 @@ public FilterFieldRule(FilterValueKind kind, params string[] ops) /// One sortable field's rule. public sealed class SortFieldRule { - public SortFieldRule(string? defaultOrder = null) => DefaultOrder = defaultOrder; + public SortFieldRule(string? defaultOrder = null, string? property = null) + { + DefaultOrder = defaultOrder; + Property = property; + } /// The DECLARED @sortableDefaultOrder (asc/desc), or null for none. public string? DefaultOrder { get; } + + /// The CLR property a generated route sorts on, or null when the caller resolves it. + public string? Property { get; } } diff --git a/server/csharp/MetaObjects.AspNetCore/RouteErrors.cs b/server/csharp/MetaObjects.AspNetCore/RouteErrors.cs new file mode 100644 index 0000000000..7fc5076c68 --- /dev/null +++ b/server/csharp/MetaObjects.AspNetCore/RouteErrors.cs @@ -0,0 +1,44 @@ +// RouteErrors — the two request refusals a generated route names before it touches the store. +// +// 400 { "error": "invalid_json" } a body that is not JSON at all +// 400 { "error": "invalid_id" } a path id the key's type cannot hold +// +// The REST standard (docs/features/api-contract.md) answers both with a named body, where ASP.NET +// Core's own binding would answer an empty 400 for the id and the route a validation body for the +// JSON. A body that is JSON but not an object is still the validation answer (`invalid_type`). + +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using Microsoft.AspNetCore.Http; + +namespace MetaObjects.AspNetCore; + +/// The invalid_json and invalid_id answers of a generated route. +public static class RouteErrors +{ + /// The wire code of a body that is not JSON. + public const string InvalidJsonCode = "invalid_json"; + + /// The wire code of a path id the key cannot hold. + public const string InvalidIdCode = "invalid_id"; + + /// 400 {"error": "invalid_json"}. + public static IResult InvalidJson() => Results.BadRequest(new Dictionary { ["error"] = InvalidJsonCode }); + + /// 400 {"error": "invalid_id"}. + public static IResult InvalidId() => Results.BadRequest(new Dictionary { ["error"] = InvalidIdCode }); + + /// + /// Read the route value as the key type , with the + /// invariant culture (the parse ASP.NET Core's own binding uses). False when the text is absent + /// or no value of the type; the route then answers . + /// + public static bool TryReadId(HttpContext http, [MaybeNullWhen(false)] out T id, string name = "id") where T : IParsable + { + if (http.Request.RouteValues.TryGetValue(name, out var raw) && raw?.ToString() is { } text + && T.TryParse(text, CultureInfo.InvariantCulture, out id)) + return true; + id = default; + return false; + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs index 4f22d94f01..a3c34f379d 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EntityGeneratorTests.cs @@ -115,7 +115,9 @@ public void Routes_generator_emits_crud_endpoints() Assert.Contains("return mount;", src); // GET list now takes HttpContext (for qs parsing: limit/offset/sort/withCount). Assert.Contains("app.MapGet(prefix + \"/subscribers\", async (HttpContext http, AppDbContext db) =>", src); - Assert.Contains("app.MapGet(prefix + \"/subscribers/{id}\", async (long id, AppDbContext db) =>", src); + // Item routes read the {id} themselves: an id the key cannot hold is 400 invalid_id. + Assert.Contains("app.MapGet(prefix + \"/subscribers/{id}\", async (HttpContext http, AppDbContext db) =>", src); + Assert.Contains("if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId();", src); Assert.Contains("db.Subscribers.FindAsync(id)", src); // FR-036 #4 — an entity with a @required field (Subscriber.email) gets the // presence-checking create handler: it reads the raw JSON body (HttpContext), @@ -132,33 +134,32 @@ public void Routes_generator_emits_crud_endpoints() // PATCH + PUT share the same update handler (matches TS reference). It takes the raw // HttpContext (not a bound DTO) and PARTIAL-merges only the properties present in the // JSON body — a bound DTO would fill omitted fields with CLR defaults and clobber them. - Assert.Contains("async System.Threading.Tasks.Task UpdateSubscriber(long id, HttpContext http, AppDbContext db)", src); + Assert.Contains("async System.Threading.Tasks.Task UpdateSubscriber(HttpContext http, AppDbContext db)", src); Assert.Contains("foreach (var prop in body.RootElement.EnumerateObject())", src); Assert.Contains("app.MapPatch(prefix + \"/subscribers/{id}\", UpdateSubscriber);", src); Assert.Contains("app.MapPut(prefix + \"/subscribers/{id}\", UpdateSubscriber);", src); - Assert.Contains("app.MapDelete(prefix + \"/subscribers/{id}\", async (long id, AppDbContext db) =>", src); + Assert.Contains("app.MapDelete(prefix + \"/subscribers/{id}\", async (HttpContext http, AppDbContext db) =>", src); + // A body that is not JSON is 400 invalid_json. + Assert.Contains("catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); }", src); } [Fact] - public void Routes_generator_list_handler_calls_FilterParser() + public void Routes_generator_list_handler_calls_ListQueryParser() { - // FR-009: the generated list handler must parse filter[...] qs against - // the per-entity allowlist + dispatch via EfCoreFilterDispatch. Both - // are runtime helpers shipped in the MetaObjects.AspNetCore package. + // The REST standard: the generated list handler parses the whole query (filter tree, search, + // sort, page bounds) against the per-entity allowlist and applies it via EfCoreFilterDispatch. + // Both are runtime helpers shipped in the MetaObjects.AspNetCore package. var ctx = Ctx(Load()); var src = Assert.Single(new RoutesGenerator().Generate(ctx)).Content; - // Imports the runtime namespace. Assert.Contains("using MetaObjects.AspNetCore;", src); - // Parses filter against the per-entity allowlist. - Assert.Contains("FilterParser.Parse(qs, SubscriberFilterAllowlist.Fields, SubscriberFilterAllowlist.OpsByField)", src); - // 400 envelope on parse error — carries `field`, which every filter envelope - // names cross-port so a caller with several filters knows which one was rejected. - Assert.Contains("Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field })", src); - // Dispatches predicates onto the IQueryable. - Assert.Contains("EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates)", src); - // The withCount query is also filtered so total reflects the filtered count. - Assert.Contains("EfCoreFilterDispatch.ApplyFilter(db.Subscribers.AsNoTracking(), filter.Predicates)", src); + Assert.Contains("ListQueryParser.Parse(http.Request.QueryString.Value, SubscriberFilterAllowlist.Rules, SortRules, SubscriberFilterAllowlist.FieldNames)", src); + // A refusal answers its named body (error plus the details the shared corpus pins). + Assert.Contains("if (__parsed.Error is { } __refused) return Results.BadRequest(__refused.Body());", src); + Assert.Contains("if (EfCoreFilterDispatch.Validate(listQuery) is { } __invalid) return Results.BadRequest(__invalid.Body());", src); + Assert.Contains("q = EfCoreFilterDispatch.Apply(q, listQuery, SubscriberFilterAllowlist.Rules);", src); + // The withCount query is filtered and searched too, so total counts what matched. + Assert.Contains("EfCoreFilterDispatch.Apply(db.Subscribers.AsNoTracking(), listQuery, SubscriberFilterAllowlist.Rules)", src); } [Fact] @@ -186,17 +187,17 @@ public void Routes_generator_emits_api_contract_qs_handling() var ctx = Ctx(Load()); var src = Assert.Single(new RoutesGenerator().Generate(ctx)).Content; - // Sort allowlist contains the entity's scalar fields (Pascal-cased). - Assert.Contains("SortAllowlist", src); - Assert.Contains("\"Id\",", src); - Assert.Contains("\"Email\",", src); - Assert.Contains("\"Subscribed\",", src); - Assert.Contains("\"CreatedAt\",", src); + // Sort rules carry the entity's scalar fields (Pascal-cased), each naming its property. + Assert.Contains("Dictionary SortRules", src); + Assert.Contains("[\"Id\"] = new SortFieldRule(property: \"Id\"),", src); + Assert.Contains("[\"Email\"] = new SortFieldRule(property: \"Email\"),", src); + Assert.Contains("[\"Subscribed\"] = new SortFieldRule(property: \"Subscribed\"),", src); + Assert.Contains("[\"CreatedAt\"] = new SortFieldRule(property: \"CreatedAt\"),", src); - // Pagination + sort dispatch. - Assert.Contains("qs.TryGetValue(\"sort\"", src); - Assert.Contains("qs.TryGetValue(\"limit\"", src); - Assert.Contains("qs.TryGetValue(\"offset\"", src); + // Pagination + sort dispatch, over the parsed query. + Assert.Contains("if (listQuery.Sort is { } __sort && SortRules[__sort.Field].Property is { } __sortProp)", src); + Assert.Contains("if (listQuery.Limit is { } __limit)", src); + Assert.Contains("if (listQuery.Offset is { } __offset && __offset > 0)", src); // withCount envelope: { rows, total }. Assert.Contains("qs.TryGetValue(\"withCount\"", src); @@ -205,11 +206,8 @@ public void Routes_generator_emits_api_contract_qs_handling() // 404 error envelope. Assert.Contains("Results.NotFound(new { error = \"not_found\" })", src); - // Invalid-sort error envelope (unknown sort field → 400). The cross-port - // api-contract uses the `invalid_sort` code (verified end-to-end by the - // SP-F generated-server lane against the corpus), not a generic "validation", - // and names the offending field. - Assert.Contains("Results.BadRequest(new { error = \"invalid_sort\", field })", src); + // An unknown sort field is ListQueryParser's `invalid_sort` refusal, answered through + // __refused.Body() (verified end-to-end by the generated-server lane against the corpus). // Sort dispatch uses EF.Property (no runtime reflection). Assert.Contains("EF.Property", src); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs index 2e6da47f10..03133e4e7d 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs @@ -12,20 +12,15 @@ namespace Acme.Shop; public static class GizmoRoutes { - private static readonly System.Collections.Generic.HashSet SortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly System.Collections.Generic.Dictionary SortRules = new(System.StringComparer.OrdinalIgnoreCase) { - "Id", - "Title", - "Stamp", - "Serial", - "TokenHash", - "CreatedAt", - "UpdatedAt", - }; - - private static readonly System.Collections.Generic.Dictionary SortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) - { - ["Title"] = true, + ["Id"] = new SortFieldRule(property: "Id"), + ["Title"] = new SortFieldRule("desc", "Title"), + ["Stamp"] = new SortFieldRule(property: "Stamp"), + ["Serial"] = new SortFieldRule(property: "Serial"), + ["TokenHash"] = new SortFieldRule(property: "TokenHash"), + ["CreatedAt"] = new SortFieldRule(property: "CreatedAt"), + ["UpdatedAt"] = new SortFieldRule(property: "UpdatedAt"), }; // api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400. @@ -60,37 +55,26 @@ public static IEndpointRouteBuilder MapGizmoRoutes(this IEndpointRouteBuilder ap var qs = http.Request.Query; IQueryable q = db.Gizmos.AsNoTracking(); - // Filter: ?filter[][]= against the per-entity allowlist. - var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, GizmoFilterAllowlist.Fields, GizmoFilterAllowlist.OpsByField)); - if (filter.ErrorEnvelope is not null) - return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); - q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); - - // Sort: ?sort=field:asc|desc against the static allowlist. - if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + // ?filter[...] (or/and groups), ?search, ?sort and the page bounds, against the allowlist. + var __parsed = ListQueryParser.Parse(http.Request.QueryString.Value, GizmoFilterAllowlist.Rules, SortRules, GizmoFilterAllowlist.FieldNames); + if (__parsed.Error is { } __refused) return Results.BadRequest(__refused.Body()); + var listQuery = __parsed.Query!; + if (EfCoreFilterDispatch.Validate(listQuery) is { } __invalid) return Results.BadRequest(__invalid.Body()); + q = EfCoreFilterDispatch.Apply(q, listQuery, GizmoFilterAllowlist.Rules); + if (listQuery.Sort is { } __sort && SortRules[__sort.Field].Property is { } __sortProp) { - var parts = sortRaw.ToString().Split(':', 2); - var field = parts[0]; - if (!SortAllowlist.TryGetValue(field, out var resolved)) - return Results.BadRequest(new { error = "invalid_sort", field }); - var desc = parts.Length > 1 - ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) - : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; - q = ApplySortGizmo(q, resolved, desc); + var desc = __sort.Descending; + q = ApplySortGizmo(q, __sortProp, desc); } // Pagination: ?offset=N first (skip), then ?limit=N (take). - if (qs.TryGetValue("offset", out var offsetRawBad) && !(int.TryParse(offsetRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offsetBad) && offsetBad >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offsetRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); - if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) - q = q.Skip(offset); - if (qs.TryGetValue("limit", out var limitRawNeg) && !(long.TryParse(limitRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limitNeg) && limitNeg >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limitRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + if (listQuery.Offset is { } __offset && __offset > 0) + q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; - if (qs.TryGetValue("limit", out var limitRaw) && long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit >= 0) + if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(limit, int.MaxValue); + __take = (int)System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); @@ -99,15 +83,18 @@ public static IEndpointRouteBuilder MapGizmoRoutes(this IEndpointRouteBuilder ap // withCount=1 → { rows, total } envelope; otherwise bare row array. var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "PinHash" }); - var totalQ = EfCoreFilterDispatch.ApplyFilter(db.Gizmos.AsNoTracking(), filter.Predicates); + var totalQ = EfCoreFilterDispatch.Apply(db.Gizmos.AsNoTracking(), listQuery, GizmoFilterAllowlist.Rules); var total = await totalQ.CountAsync(); return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "PinHash" }, envelope: true); }); - app.MapGet(prefix + "/gizmos/{id}", async (long id, global::Acme.Generated.AppDbContext db) => - await db.Gizmos.FindAsync(id) is { } found + app.MapGet(prefix + "/gizmos/{id}", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); + return await db.Gizmos.FindAsync(id) is { } found ? (IResult)new CredentialOmittingResult(found, new string[] { "PinHash" }) - : Results.NotFound(new { error = "not_found" })); + : Results.NotFound(new { error = "not_found" }); + }); app.MapPost(prefix + "/gizmos", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { @@ -116,7 +103,7 @@ await db.Gizmos.FindAsync(id) is { } found .Value.SerializerOptions; System.Text.Json.JsonDocument __body; try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var __bodyScope = __body; if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); @@ -153,13 +140,14 @@ await db.Gizmos.FindAsync(id) is { } found return (IResult)new CredentialOmittingResult(input, new string[] { "PinHash" }, status: 201, location: prefix + "/gizmos"); }); - async System.Threading.Tasks.Task UpdateGizmo(long id, HttpContext http, global::Acme.Generated.AppDbContext db) + async System.Threading.Tasks.Task UpdateGizmo(HttpContext http, global::Acme.Generated.AppDbContext db) { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Gizmos.FindAsync(id); if (existing is null) return Results.NotFound(new { error = "not_found" }); System.Text.Json.JsonDocument body; try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var bodyScope = body; if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown; @@ -247,8 +235,9 @@ async System.Threading.Tasks.Task UpdateGizmo(long id, HttpContext http app.MapPatch(prefix + "/gizmos/{id}", UpdateGizmo); app.MapPut(prefix + "/gizmos/{id}", UpdateGizmo); - app.MapDelete(prefix + "/gizmos/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + app.MapDelete(prefix + "/gizmos/{id}", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Gizmos.FindAsync(id); if (existing is null) return Results.NotFound(new { error = "not_found" }); db.Gizmos.Remove(existing); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs index d5a65005f9..3f9f7a9106 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs @@ -12,14 +12,10 @@ namespace Acme.Shop; public static class LineRoutes { - private static readonly System.Collections.Generic.HashSet SortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) - { - "Id", - "Label", - }; - - private static readonly System.Collections.Generic.Dictionary SortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly System.Collections.Generic.Dictionary SortRules = new(System.StringComparer.OrdinalIgnoreCase) { + ["Id"] = new SortFieldRule(property: "Id"), + ["Label"] = new SortFieldRule(property: "Label"), }; // api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400. @@ -45,37 +41,26 @@ public static IEndpointRouteBuilder MapLineRoutes(this IEndpointRouteBuilder app var qs = http.Request.Query; IQueryable q = db.Lines.AsNoTracking(); - // Filter: ?filter[][]= against the per-entity allowlist. - var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, LineFilterAllowlist.Fields, LineFilterAllowlist.OpsByField)); - if (filter.ErrorEnvelope is not null) - return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); - q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); - - // Sort: ?sort=field:asc|desc against the static allowlist. - if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + // ?filter[...] (or/and groups), ?search, ?sort and the page bounds, against the allowlist. + var __parsed = ListQueryParser.Parse(http.Request.QueryString.Value, LineFilterAllowlist.Rules, SortRules, LineFilterAllowlist.FieldNames); + if (__parsed.Error is { } __refused) return Results.BadRequest(__refused.Body()); + var listQuery = __parsed.Query!; + if (EfCoreFilterDispatch.Validate(listQuery) is { } __invalid) return Results.BadRequest(__invalid.Body()); + q = EfCoreFilterDispatch.Apply(q, listQuery, LineFilterAllowlist.Rules); + if (listQuery.Sort is { } __sort && SortRules[__sort.Field].Property is { } __sortProp) { - var parts = sortRaw.ToString().Split(':', 2); - var field = parts[0]; - if (!SortAllowlist.TryGetValue(field, out var resolved)) - return Results.BadRequest(new { error = "invalid_sort", field }); - var desc = parts.Length > 1 - ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) - : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; - q = ApplySortLine(q, resolved, desc); + var desc = __sort.Descending; + q = ApplySortLine(q, __sortProp, desc); } // Pagination: ?offset=N first (skip), then ?limit=N (take). - if (qs.TryGetValue("offset", out var offsetRawBad) && !(int.TryParse(offsetRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offsetBad) && offsetBad >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offsetRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); - if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) - q = q.Skip(offset); - if (qs.TryGetValue("limit", out var limitRawNeg) && !(long.TryParse(limitRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limitNeg) && limitNeg >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limitRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + if (listQuery.Offset is { } __offset && __offset > 0) + q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; - if (qs.TryGetValue("limit", out var limitRaw) && long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit >= 0) + if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(limit, int.MaxValue); + __take = (int)System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); @@ -84,15 +69,18 @@ public static IEndpointRouteBuilder MapLineRoutes(this IEndpointRouteBuilder app // withCount=1 → { rows, total } envelope; otherwise bare row array. var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return Results.Ok(rows); - var totalQ = EfCoreFilterDispatch.ApplyFilter(db.Lines.AsNoTracking(), filter.Predicates); + var totalQ = EfCoreFilterDispatch.Apply(db.Lines.AsNoTracking(), listQuery, LineFilterAllowlist.Rules); var total = await totalQ.CountAsync(); return Results.Ok(new { rows, total }); }); - app.MapGet(prefix + "/lines/{id}", async (long id, global::Acme.Generated.AppDbContext db) => - await db.Lines.FindAsync(id) is { } found + app.MapGet(prefix + "/lines/{id}", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); + return await db.Lines.FindAsync(id) is { } found ? Results.Ok(found) - : Results.NotFound(new { error = "not_found" })); + : Results.NotFound(new { error = "not_found" }); + }); app.MapPost(prefix + "/lines", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { @@ -101,7 +89,7 @@ await db.Lines.FindAsync(id) is { } found .Value.SerializerOptions; System.Text.Json.JsonDocument __body; try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var __bodyScope = __body; if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); @@ -126,13 +114,14 @@ await db.Lines.FindAsync(id) is { } found return Results.Created(prefix + "/lines", input); }); - async System.Threading.Tasks.Task UpdateLine(long id, HttpContext http, global::Acme.Generated.AppDbContext db) + async System.Threading.Tasks.Task UpdateLine(HttpContext http, global::Acme.Generated.AppDbContext db) { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Lines.FindAsync(id); if (existing is null) return Results.NotFound(new { error = "not_found" }); System.Text.Json.JsonDocument body; try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var bodyScope = body; if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown; @@ -187,8 +176,9 @@ async System.Threading.Tasks.Task UpdateLine(long id, HttpContext http, app.MapPatch(prefix + "/lines/{id}", UpdateLine); app.MapPut(prefix + "/lines/{id}", UpdateLine); - app.MapDelete(prefix + "/lines/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + app.MapDelete(prefix + "/lines/{id}", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Lines.FindAsync(id); if (existing is null) return Results.NotFound(new { error = "not_found" }); db.Lines.Remove(existing); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs index b205dcd0e2..1423cf044e 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs @@ -12,14 +12,10 @@ namespace Acme.Shop; public static class LineTotalsRoutes { - private static readonly System.Collections.Generic.HashSet SortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) - { - "Label", - "Lines", - }; - - private static readonly System.Collections.Generic.Dictionary SortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly System.Collections.Generic.Dictionary SortRules = new(System.StringComparer.OrdinalIgnoreCase) { + ["Label"] = new SortFieldRule(property: "Label"), + ["Lines"] = new SortFieldRule(property: "Lines"), }; /// Maps LineTotals REST routes. Unauthenticated — see remarks. @@ -38,23 +34,16 @@ public static IEndpointRouteBuilder MapLineTotalsRoutes(this IEndpointRouteBuild var qs = http.Request.Query; IQueryable q = db.LineTotals.AsNoTracking(); - // Filter: ?filter[][]= against the per-entity allowlist. - var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, LineTotalsFilterAllowlist.Fields, LineTotalsFilterAllowlist.OpsByField)); - if (filter.ErrorEnvelope is not null) - return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); - q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); - - // Sort: ?sort=field:asc|desc against the static allowlist. - if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + // ?filter[...] (or/and groups), ?search, ?sort and the page bounds, against the allowlist. + var __parsed = ListQueryParser.Parse(http.Request.QueryString.Value, LineTotalsFilterAllowlist.Rules, SortRules, LineTotalsFilterAllowlist.FieldNames); + if (__parsed.Error is { } __refused) return Results.BadRequest(__refused.Body()); + var listQuery = __parsed.Query!; + if (EfCoreFilterDispatch.Validate(listQuery) is { } __invalid) return Results.BadRequest(__invalid.Body()); + q = EfCoreFilterDispatch.Apply(q, listQuery, LineTotalsFilterAllowlist.Rules); + if (listQuery.Sort is { } __sort && SortRules[__sort.Field].Property is { } __sortProp) { - var parts = sortRaw.ToString().Split(':', 2); - var field = parts[0]; - if (!SortAllowlist.TryGetValue(field, out var resolved)) - return Results.BadRequest(new { error = "invalid_sort", field }); - var desc = parts.Length > 1 - ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) - : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; - q = ApplySortLineTotals(q, resolved, desc); + var desc = __sort.Descending; + q = ApplySortLineTotals(q, __sortProp, desc); } // Pagination (report): every row up to the cap, refused above it. @@ -82,7 +71,7 @@ public static IEndpointRouteBuilder MapLineTotalsRoutes(this IEndpointRouteBuild // withCount=1 → { rows, total } envelope; otherwise bare row array. var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return Results.Ok(rows); - var totalQ = EfCoreFilterDispatch.ApplyFilter(db.LineTotals.AsNoTracking(), filter.Predicates); + var totalQ = EfCoreFilterDispatch.Apply(db.LineTotals.AsNoTracking(), listQuery, LineTotalsFilterAllowlist.Rules); var total = await totalQ.CountAsync(); return Results.Ok(new { rows, total }); }); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs index 425fb24538..49db8d4dd5 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs @@ -12,14 +12,10 @@ namespace Acme.Shop; public static class TagRoutes { - private static readonly System.Collections.Generic.HashSet SortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) - { - "Id", - "Name", - }; - - private static readonly System.Collections.Generic.Dictionary SortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly System.Collections.Generic.Dictionary SortRules = new(System.StringComparer.OrdinalIgnoreCase) { + ["Id"] = new SortFieldRule(property: "Id"), + ["Name"] = new SortFieldRule(property: "Name"), }; // api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400. @@ -45,37 +41,26 @@ public static IEndpointRouteBuilder MapTagRoutes(this IEndpointRouteBuilder app, var qs = http.Request.Query; IQueryable q = db.Tags.AsNoTracking(); - // Filter: ?filter[][]= against the per-entity allowlist. - var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, TagFilterAllowlist.Fields, TagFilterAllowlist.OpsByField)); - if (filter.ErrorEnvelope is not null) - return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); - q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); - - // Sort: ?sort=field:asc|desc against the static allowlist. - if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + // ?filter[...] (or/and groups), ?search, ?sort and the page bounds, against the allowlist. + var __parsed = ListQueryParser.Parse(http.Request.QueryString.Value, TagFilterAllowlist.Rules, SortRules, TagFilterAllowlist.FieldNames); + if (__parsed.Error is { } __refused) return Results.BadRequest(__refused.Body()); + var listQuery = __parsed.Query!; + if (EfCoreFilterDispatch.Validate(listQuery) is { } __invalid) return Results.BadRequest(__invalid.Body()); + q = EfCoreFilterDispatch.Apply(q, listQuery, TagFilterAllowlist.Rules); + if (listQuery.Sort is { } __sort && SortRules[__sort.Field].Property is { } __sortProp) { - var parts = sortRaw.ToString().Split(':', 2); - var field = parts[0]; - if (!SortAllowlist.TryGetValue(field, out var resolved)) - return Results.BadRequest(new { error = "invalid_sort", field }); - var desc = parts.Length > 1 - ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) - : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; - q = ApplySortTag(q, resolved, desc); + var desc = __sort.Descending; + q = ApplySortTag(q, __sortProp, desc); } // Pagination: ?offset=N first (skip), then ?limit=N (take). - if (qs.TryGetValue("offset", out var offsetRawBad) && !(int.TryParse(offsetRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offsetBad) && offsetBad >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offsetRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); - if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) - q = q.Skip(offset); - if (qs.TryGetValue("limit", out var limitRawNeg) && !(long.TryParse(limitRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limitNeg) && limitNeg >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limitRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + if (listQuery.Offset is { } __offset && __offset > 0) + q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; - if (qs.TryGetValue("limit", out var limitRaw) && long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit >= 0) + if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(limit, int.MaxValue); + __take = (int)System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); @@ -84,15 +69,18 @@ public static IEndpointRouteBuilder MapTagRoutes(this IEndpointRouteBuilder app, // withCount=1 → { rows, total } envelope; otherwise bare row array. var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return Results.Ok(rows); - var totalQ = EfCoreFilterDispatch.ApplyFilter(db.Tags.AsNoTracking(), filter.Predicates); + var totalQ = EfCoreFilterDispatch.Apply(db.Tags.AsNoTracking(), listQuery, TagFilterAllowlist.Rules); var total = await totalQ.CountAsync(); return Results.Ok(new { rows, total }); }); - app.MapGet(prefix + "/tags/{id}", async (long id, global::Acme.Generated.AppDbContext db) => - await db.Tags.FindAsync(id) is { } found + app.MapGet(prefix + "/tags/{id}", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); + return await db.Tags.FindAsync(id) is { } found ? Results.Ok(found) - : Results.NotFound(new { error = "not_found" })); + : Results.NotFound(new { error = "not_found" }); + }); app.MapPost(prefix + "/tags", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { @@ -101,7 +89,7 @@ await db.Tags.FindAsync(id) is { } found .Value.SerializerOptions; System.Text.Json.JsonDocument __body; try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var __bodyScope = __body; if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); @@ -128,13 +116,14 @@ await db.Tags.FindAsync(id) is { } found return Results.Created(prefix + "/tags", input); }); - async System.Threading.Tasks.Task UpdateTag(long id, HttpContext http, global::Acme.Generated.AppDbContext db) + async System.Threading.Tasks.Task UpdateTag(HttpContext http, global::Acme.Generated.AppDbContext db) { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Tags.FindAsync(id); if (existing is null) return Results.NotFound(new { error = "not_found" }); System.Text.Json.JsonDocument body; try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var bodyScope = body; if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown; @@ -189,8 +178,9 @@ async System.Threading.Tasks.Task UpdateTag(long id, HttpContext http, app.MapPatch(prefix + "/tags/{id}", UpdateTag); app.MapPut(prefix + "/tags/{id}", UpdateTag); - app.MapDelete(prefix + "/tags/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + app.MapDelete(prefix + "/tags/{id}", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Tags.FindAsync(id); if (existing is null) return Results.NotFound(new { error = "not_found" }); db.Tags.Remove(existing); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs index 85d49e8ff9..70779c13a5 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs @@ -12,14 +12,10 @@ namespace Acme.Shop; public static class VehicleRoutes { - private static readonly System.Collections.Generic.HashSet SortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) - { - "Id", - "Plate", - }; - - private static readonly System.Collections.Generic.Dictionary SortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly System.Collections.Generic.Dictionary SortRules = new(System.StringComparer.OrdinalIgnoreCase) { + ["Id"] = new SortFieldRule(property: "Id"), + ["Plate"] = new SortFieldRule(property: "Plate"), }; // api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400. @@ -34,27 +30,19 @@ public static class VehicleRoutes "vinHash", }; - private static readonly System.Collections.Generic.HashSet CarSortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) - { - "Id", - "Plate", - "SeatCount", - "RegNo", - }; - - private static readonly System.Collections.Generic.Dictionary CarSortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly System.Collections.Generic.Dictionary CarSortRules = new(System.StringComparer.OrdinalIgnoreCase) { + ["Id"] = new SortFieldRule(property: "Id"), + ["Plate"] = new SortFieldRule(property: "Plate"), + ["SeatCount"] = new SortFieldRule(property: "SeatCount"), + ["RegNo"] = new SortFieldRule(property: "RegNo"), }; - private static readonly System.Collections.Generic.HashSet VanSortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) - { - "Id", - "Plate", - "PayloadKg", - }; - - private static readonly System.Collections.Generic.Dictionary VanSortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly System.Collections.Generic.Dictionary VanSortRules = new(System.StringComparer.OrdinalIgnoreCase) { + ["Id"] = new SortFieldRule(property: "Id"), + ["Plate"] = new SortFieldRule(property: "Plate"), + ["PayloadKg"] = new SortFieldRule(property: "PayloadKg"), }; /// Maps Vehicle REST routes. Unauthenticated — see remarks. @@ -73,45 +61,45 @@ public static IEndpointRouteBuilder MapVehicleRoutes(this IEndpointRouteBuilder { var qs = http.Request.Query; IQueryable q = db.Vehicles.AsNoTracking(); - var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, VehicleFilterAllowlist.Fields, VehicleFilterAllowlist.OpsByField)); - if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); - q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); - if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + // ?filter[...] (or/and groups), ?search, ?sort and the page bounds, against the allowlist. + var __parsed = ListQueryParser.Parse(http.Request.QueryString.Value, VehicleFilterAllowlist.Rules, SortRules, VehicleFilterAllowlist.FieldNames); + if (__parsed.Error is { } __refused) return Results.BadRequest(__refused.Body()); + var listQuery = __parsed.Query!; + if (EfCoreFilterDispatch.Validate(listQuery) is { } __invalid) return Results.BadRequest(__invalid.Body()); + q = EfCoreFilterDispatch.Apply(q, listQuery, VehicleFilterAllowlist.Rules); + if (listQuery.Sort is { } __sort && SortRules[__sort.Field].Property is { } __sortProp) { - var parts = sortRaw.ToString().Split(':', 2); - if (!SortAllowlist.TryGetValue(parts[0], out var resolved)) return Results.BadRequest(new { error = "invalid_sort", field = parts[0] }); - var desc = parts.Length > 1 - ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) - : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; - q = ApplySort(q, resolved, desc); + var desc = __sort.Descending; + q = ApplySort(q, __sortProp, desc); } - if (qs.TryGetValue("offset", out var offRawBad) && !(int.TryParse(offRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offBad) && offBad >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); - if (qs.TryGetValue("offset", out var offRaw) && int.TryParse(offRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var off) && off > 0) - q = q.Skip(off); - if (qs.TryGetValue("limit", out var limRawNeg) && !(long.TryParse(limRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limNeg) && limNeg >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (listQuery.Offset is { } __offset && __offset > 0) + q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; - if (qs.TryGetValue("limit", out var limRaw) && long.TryParse(limRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim >= 0) + if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(lim, int.MaxValue); + __take = (int)System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); var rows = await q.ToListAsync(); var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "VinHash" }); - var total = await EfCoreFilterDispatch.ApplyFilter(db.Vehicles.AsNoTracking(), filter.Predicates).CountAsync(); + var total = await EfCoreFilterDispatch.Apply(db.Vehicles.AsNoTracking(), listQuery, VehicleFilterAllowlist.Rules).CountAsync(); return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "VinHash" }, envelope: true); }); - app.MapGet(prefix + "/vehicles/{id}", async (long id, global::Acme.Generated.AppDbContext db) => - await db.Vehicles.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } found + app.MapGet(prefix + "/vehicles/{id}", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); + return await db.Vehicles.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } found ? (IResult)new CredentialOmittingResult(found, new string[] { "VinHash" }) - : Results.NotFound(new { error = "not_found" })); + : Results.NotFound(new { error = "not_found" }); + }); - app.MapGet(prefix + "/vehicles/{id}/tags", async (long id, global::Acme.Generated.AppDbContext db) => + app.MapGet(prefix + "/vehicles/{id}/tags", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var relatedIds = (await db.VehicleTags.AsNoTracking() .Where(j => EF.Property(j, "VehicleId").Equals(id)) .Select(j => EF.Property(j, "TagId")) @@ -127,42 +115,41 @@ await db.Vehicles.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } fou { var qs = http.Request.Query; IQueryable q = db.Vehicles.OfType().AsNoTracking(); - var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, global::Acme.Shop.CarFilterAllowlist.Fields, global::Acme.Shop.CarFilterAllowlist.OpsByField)); - if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); - q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); - if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + // ?filter[...] (or/and groups), ?search, ?sort and the page bounds, against the allowlist. + var __parsed = ListQueryParser.Parse(http.Request.QueryString.Value, global::Acme.Shop.CarFilterAllowlist.Rules, CarSortRules, global::Acme.Shop.CarFilterAllowlist.FieldNames); + if (__parsed.Error is { } __refused) return Results.BadRequest(__refused.Body()); + var listQuery = __parsed.Query!; + if (EfCoreFilterDispatch.Validate(listQuery) is { } __invalid) return Results.BadRequest(__invalid.Body()); + q = EfCoreFilterDispatch.Apply(q, listQuery, global::Acme.Shop.CarFilterAllowlist.Rules); + if (listQuery.Sort is { } __sort && CarSortRules[__sort.Field].Property is { } __sortProp) { - var parts = sortRaw.ToString().Split(':', 2); - if (!CarSortAllowlist.TryGetValue(parts[0], out var resolved)) return Results.BadRequest(new { error = "invalid_sort", field = parts[0] }); - var desc = parts.Length > 1 - ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) - : CarSortDefaultDesc.TryGetValue(resolved, out var dd) && dd; - q = desc ? q.OrderByDescending(x => EF.Property(x!, resolved) == null).ThenByDescending(x => EF.Property(x!, resolved)) : q.OrderBy(x => EF.Property(x!, resolved) == null).ThenBy(x => EF.Property(x!, resolved)); + var desc = __sort.Descending; + q = desc ? q.OrderByDescending(x => EF.Property(x!, __sortProp) == null).ThenByDescending(x => EF.Property(x!, __sortProp)) : q.OrderBy(x => EF.Property(x!, __sortProp) == null).ThenBy(x => EF.Property(x!, __sortProp)); } - if (qs.TryGetValue("offset", out var offRawBad) && !(int.TryParse(offRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offBad) && offBad >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); - if (qs.TryGetValue("offset", out var offRaw) && int.TryParse(offRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var off) && off > 0) - q = q.Skip(off); - if (qs.TryGetValue("limit", out var limRawNeg) && !(long.TryParse(limRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limNeg) && limNeg >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (listQuery.Offset is { } __offset && __offset > 0) + q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; - if (qs.TryGetValue("limit", out var limRaw) && long.TryParse(limRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim >= 0) + if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(lim, int.MaxValue); + __take = (int)System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); var rows = await q.ToListAsync(); var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "VinHash" }); - var total = await EfCoreFilterDispatch.ApplyFilter(db.Vehicles.OfType().AsNoTracking(), filter.Predicates).CountAsync(); + var total = await EfCoreFilterDispatch.Apply(db.Vehicles.OfType().AsNoTracking(), listQuery, global::Acme.Shop.CarFilterAllowlist.Rules).CountAsync(); return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "VinHash" }, envelope: true); }); - app.MapGet(prefix + "/vehicles/car/{id}", async (long id, global::Acme.Generated.AppDbContext db) => - await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } found + app.MapGet(prefix + "/vehicles/car/{id}", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); + return await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } found ? (IResult)new CredentialOmittingResult(found, new string[] { "VinHash" }) - : Results.NotFound(new { error = "not_found" })); + : Results.NotFound(new { error = "not_found" }); + }); app.MapPost(prefix + "/vehicles/car", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { @@ -171,7 +158,7 @@ await db.Vehicles.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } fou .Value.SerializerOptions; System.Text.Json.JsonDocument __body; try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var __bodyScope = __body; if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); @@ -202,13 +189,14 @@ await db.Vehicles.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } fou return (IResult)new CredentialOmittingResult(input, new string[] { "VinHash" }, status: 201, location: prefix + "/vehicles/car/" + input.Id); }); - async System.Threading.Tasks.Task UpdateCar(long id, HttpContext http, global::Acme.Generated.AppDbContext db) + async System.Threading.Tasks.Task UpdateCar(HttpContext http, global::Acme.Generated.AppDbContext db) { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Vehicles.OfType().FirstOrDefaultAsync(x => x.Id == id); if (existing is null) return Results.NotFound(new { error = "not_found" }); System.Text.Json.JsonDocument body; try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var bodyScope = body; if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown; @@ -266,8 +254,9 @@ async System.Threading.Tasks.Task UpdateCar(long id, HttpContext http, app.MapPatch(prefix + "/vehicles/car/{id}", UpdateCar); app.MapPut(prefix + "/vehicles/car/{id}", UpdateCar); - app.MapDelete(prefix + "/vehicles/car/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + app.MapDelete(prefix + "/vehicles/car/{id}", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Vehicles.OfType().FirstOrDefaultAsync(x => x.Id == id); if (existing is null) return Results.NotFound(new { error = "not_found" }); db.Vehicles.Remove(existing); @@ -283,8 +272,9 @@ async System.Threading.Tasks.Task UpdateCar(long id, HttpContext http, return Results.NoContent(); }); - app.MapGet(prefix + "/vehicles/car/{id}/tags", async (long id, global::Acme.Generated.AppDbContext db) => + app.MapGet(prefix + "/vehicles/car/{id}/tags", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); if (!await db.Vehicles.OfType().AnyAsync(x => x.Id == id)) return Results.Ok(new System.Collections.Generic.List()); var relatedIds = (await db.VehicleTags.AsNoTracking() @@ -302,42 +292,41 @@ async System.Threading.Tasks.Task UpdateCar(long id, HttpContext http, { var qs = http.Request.Query; IQueryable q = db.Vehicles.OfType().AsNoTracking(); - var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, global::Acme.Shop.VanFilterAllowlist.Fields, global::Acme.Shop.VanFilterAllowlist.OpsByField)); - if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); - q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); - if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + // ?filter[...] (or/and groups), ?search, ?sort and the page bounds, against the allowlist. + var __parsed = ListQueryParser.Parse(http.Request.QueryString.Value, global::Acme.Shop.VanFilterAllowlist.Rules, VanSortRules, global::Acme.Shop.VanFilterAllowlist.FieldNames); + if (__parsed.Error is { } __refused) return Results.BadRequest(__refused.Body()); + var listQuery = __parsed.Query!; + if (EfCoreFilterDispatch.Validate(listQuery) is { } __invalid) return Results.BadRequest(__invalid.Body()); + q = EfCoreFilterDispatch.Apply(q, listQuery, global::Acme.Shop.VanFilterAllowlist.Rules); + if (listQuery.Sort is { } __sort && VanSortRules[__sort.Field].Property is { } __sortProp) { - var parts = sortRaw.ToString().Split(':', 2); - if (!VanSortAllowlist.TryGetValue(parts[0], out var resolved)) return Results.BadRequest(new { error = "invalid_sort", field = parts[0] }); - var desc = parts.Length > 1 - ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) - : VanSortDefaultDesc.TryGetValue(resolved, out var dd) && dd; - q = desc ? q.OrderByDescending(x => EF.Property(x!, resolved) == null).ThenByDescending(x => EF.Property(x!, resolved)) : q.OrderBy(x => EF.Property(x!, resolved) == null).ThenBy(x => EF.Property(x!, resolved)); + var desc = __sort.Descending; + q = desc ? q.OrderByDescending(x => EF.Property(x!, __sortProp) == null).ThenByDescending(x => EF.Property(x!, __sortProp)) : q.OrderBy(x => EF.Property(x!, __sortProp) == null).ThenBy(x => EF.Property(x!, __sortProp)); } - if (qs.TryGetValue("offset", out var offRawBad) && !(int.TryParse(offRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offBad) && offBad >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); - if (qs.TryGetValue("offset", out var offRaw) && int.TryParse(offRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var off) && off > 0) - q = q.Skip(off); - if (qs.TryGetValue("limit", out var limRawNeg) && !(long.TryParse(limRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limNeg) && limNeg >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (listQuery.Offset is { } __offset && __offset > 0) + q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; - if (qs.TryGetValue("limit", out var limRaw) && long.TryParse(limRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim >= 0) + if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(lim, int.MaxValue); + __take = (int)System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); var rows = await q.ToListAsync(); var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "VinHash" }); - var total = await EfCoreFilterDispatch.ApplyFilter(db.Vehicles.OfType().AsNoTracking(), filter.Predicates).CountAsync(); + var total = await EfCoreFilterDispatch.Apply(db.Vehicles.OfType().AsNoTracking(), listQuery, global::Acme.Shop.VanFilterAllowlist.Rules).CountAsync(); return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "VinHash" }, envelope: true); }); - app.MapGet(prefix + "/vehicles/van/{id}", async (long id, global::Acme.Generated.AppDbContext db) => - await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } found + app.MapGet(prefix + "/vehicles/van/{id}", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); + return await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } found ? (IResult)new CredentialOmittingResult(found, new string[] { "VinHash" }) - : Results.NotFound(new { error = "not_found" })); + : Results.NotFound(new { error = "not_found" }); + }); app.MapPost(prefix + "/vehicles/van", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { @@ -346,7 +335,7 @@ async System.Threading.Tasks.Task UpdateCar(long id, HttpContext http, .Value.SerializerOptions; System.Text.Json.JsonDocument __body; try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var __bodyScope = __body; if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); @@ -377,13 +366,14 @@ async System.Threading.Tasks.Task UpdateCar(long id, HttpContext http, return (IResult)new CredentialOmittingResult(input, new string[] { "VinHash" }, status: 201, location: prefix + "/vehicles/van/" + input.Id); }); - async System.Threading.Tasks.Task UpdateVan(long id, HttpContext http, global::Acme.Generated.AppDbContext db) + async System.Threading.Tasks.Task UpdateVan(HttpContext http, global::Acme.Generated.AppDbContext db) { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Vehicles.OfType().FirstOrDefaultAsync(x => x.Id == id); if (existing is null) return Results.NotFound(new { error = "not_found" }); System.Text.Json.JsonDocument body; try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } - catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); } + catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); } using var bodyScope = body; if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable(); if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown; @@ -440,8 +430,9 @@ async System.Threading.Tasks.Task UpdateVan(long id, HttpContext http, app.MapPatch(prefix + "/vehicles/van/{id}", UpdateVan); app.MapPut(prefix + "/vehicles/van/{id}", UpdateVan); - app.MapDelete(prefix + "/vehicles/van/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + app.MapDelete(prefix + "/vehicles/van/{id}", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); var existing = await db.Vehicles.OfType().FirstOrDefaultAsync(x => x.Id == id); if (existing is null) return Results.NotFound(new { error = "not_found" }); db.Vehicles.Remove(existing); @@ -457,8 +448,9 @@ async System.Threading.Tasks.Task UpdateVan(long id, HttpContext http, return Results.NoContent(); }); - app.MapGet(prefix + "/vehicles/van/{id}/tags", async (long id, global::Acme.Generated.AppDbContext db) => + app.MapGet(prefix + "/vehicles/van/{id}/tags", async (HttpContext http, global::Acme.Generated.AppDbContext db) => { + if (!RouteErrors.TryReadId(http, out var id)) return RouteErrors.InvalidId(); if (!await db.Vehicles.OfType().AnyAsync(x => x.Id == id)) return Results.Ok(new System.Collections.Generic.List()); var relatedIds = (await db.VehicleTags.AsNoTracking() diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs index 6ebc47934f..45008205b9 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs @@ -12,14 +12,10 @@ namespace Acme.Shop; public static class VehicleTagRoutes { - private static readonly System.Collections.Generic.HashSet SortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) - { - "VehicleId", - "TagId", - }; - - private static readonly System.Collections.Generic.Dictionary SortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly System.Collections.Generic.Dictionary SortRules = new(System.StringComparer.OrdinalIgnoreCase) { + ["VehicleId"] = new SortFieldRule(property: "VehicleId"), + ["TagId"] = new SortFieldRule(property: "TagId"), }; /// Maps VehicleTag REST routes. Unauthenticated — see remarks. @@ -38,37 +34,26 @@ public static IEndpointRouteBuilder MapVehicleTagRoutes(this IEndpointRouteBuild var qs = http.Request.Query; IQueryable q = db.VehicleTags.AsNoTracking(); - // Filter: ?filter[][]= against the per-entity allowlist. - var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, VehicleTagFilterAllowlist.Fields, VehicleTagFilterAllowlist.OpsByField)); - if (filter.ErrorEnvelope is not null) - return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); - q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); - - // Sort: ?sort=field:asc|desc against the static allowlist. - if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + // ?filter[...] (or/and groups), ?search, ?sort and the page bounds, against the allowlist. + var __parsed = ListQueryParser.Parse(http.Request.QueryString.Value, VehicleTagFilterAllowlist.Rules, SortRules, VehicleTagFilterAllowlist.FieldNames); + if (__parsed.Error is { } __refused) return Results.BadRequest(__refused.Body()); + var listQuery = __parsed.Query!; + if (EfCoreFilterDispatch.Validate(listQuery) is { } __invalid) return Results.BadRequest(__invalid.Body()); + q = EfCoreFilterDispatch.Apply(q, listQuery, VehicleTagFilterAllowlist.Rules); + if (listQuery.Sort is { } __sort && SortRules[__sort.Field].Property is { } __sortProp) { - var parts = sortRaw.ToString().Split(':', 2); - var field = parts[0]; - if (!SortAllowlist.TryGetValue(field, out var resolved)) - return Results.BadRequest(new { error = "invalid_sort", field }); - var desc = parts.Length > 1 - ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) - : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; - q = ApplySortVehicleTag(q, resolved, desc); + var desc = __sort.Descending; + q = ApplySortVehicleTag(q, __sortProp, desc); } // Pagination: ?offset=N first (skip), then ?limit=N (take). - if (qs.TryGetValue("offset", out var offsetRawBad) && !(int.TryParse(offsetRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offsetBad) && offsetBad >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offsetRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); - if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) - q = q.Skip(offset); - if (qs.TryGetValue("limit", out var limitRawNeg) && !(long.TryParse(limitRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limitNeg) && limitNeg >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limitRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + if (listQuery.Offset is { } __offset && __offset > 0) + q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; - if (qs.TryGetValue("limit", out var limitRaw) && long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit >= 0) + if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(limit, int.MaxValue); + __take = (int)System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); @@ -77,7 +62,7 @@ public static IEndpointRouteBuilder MapVehicleTagRoutes(this IEndpointRouteBuild // withCount=1 → { rows, total } envelope; otherwise bare row array. var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return Results.Ok(rows); - var totalQ = EfCoreFilterDispatch.ApplyFilter(db.VehicleTags.AsNoTracking(), filter.Predicates); + var totalQ = EfCoreFilterDispatch.Apply(db.VehicleTags.AsNoTracking(), listQuery, VehicleTagFilterAllowlist.Rules); var total = await totalQ.CountAsync(); return Results.Ok(new { rows, total }); }); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs index bceb3090a7..62236b461f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs @@ -12,13 +12,9 @@ namespace Acme.Shop; public static class WidgetSummaryRoutes { - private static readonly System.Collections.Generic.HashSet SortAllowlist = new(System.StringComparer.OrdinalIgnoreCase) - { - "WidgetId", - }; - - private static readonly System.Collections.Generic.Dictionary SortDefaultDesc = new(System.StringComparer.OrdinalIgnoreCase) + private static readonly System.Collections.Generic.Dictionary SortRules = new(System.StringComparer.OrdinalIgnoreCase) { + ["WidgetId"] = new SortFieldRule(property: "WidgetId"), }; /// Maps WidgetSummary REST routes. Unauthenticated — see remarks. @@ -37,37 +33,26 @@ public static IEndpointRouteBuilder MapWidgetSummaryRoutes(this IEndpointRouteBu var qs = http.Request.Query; IQueryable q = db.WidgetSummaries.AsNoTracking(); - // Filter: ?filter[][]= against the per-entity allowlist. - var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, WidgetSummaryFilterAllowlist.Fields, WidgetSummaryFilterAllowlist.OpsByField)); - if (filter.ErrorEnvelope is not null) - return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); - q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); - - // Sort: ?sort=field:asc|desc against the static allowlist. - if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + // ?filter[...] (or/and groups), ?search, ?sort and the page bounds, against the allowlist. + var __parsed = ListQueryParser.Parse(http.Request.QueryString.Value, WidgetSummaryFilterAllowlist.Rules, SortRules, WidgetSummaryFilterAllowlist.FieldNames); + if (__parsed.Error is { } __refused) return Results.BadRequest(__refused.Body()); + var listQuery = __parsed.Query!; + if (EfCoreFilterDispatch.Validate(listQuery) is { } __invalid) return Results.BadRequest(__invalid.Body()); + q = EfCoreFilterDispatch.Apply(q, listQuery, WidgetSummaryFilterAllowlist.Rules); + if (listQuery.Sort is { } __sort && SortRules[__sort.Field].Property is { } __sortProp) { - var parts = sortRaw.ToString().Split(':', 2); - var field = parts[0]; - if (!SortAllowlist.TryGetValue(field, out var resolved)) - return Results.BadRequest(new { error = "invalid_sort", field }); - var desc = parts.Length > 1 - ? string.Equals(parts[1], "desc", System.StringComparison.OrdinalIgnoreCase) - : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; - q = ApplySortWidgetSummary(q, resolved, desc); + var desc = __sort.Descending; + q = ApplySortWidgetSummary(q, __sortProp, desc); } // Pagination: ?offset=N first (skip), then ?limit=N (take). - if (qs.TryGetValue("offset", out var offsetRawBad) && !(int.TryParse(offsetRawBad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offsetBad) && offsetBad >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offsetRawBad.ToString(), expected = "a non-negative integer (0 or more)" }); - if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) - q = q.Skip(offset); - if (qs.TryGetValue("limit", out var limitRawNeg) && !(long.TryParse(limitRawNeg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limitNeg) && limitNeg >= 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limitRawNeg.ToString(), expected = "a non-negative integer (0 or more)" }); + if (listQuery.Offset is { } __offset && __offset > 0) + q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); // No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked. var __take = 50; - if (qs.TryGetValue("limit", out var limitRaw) && long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit >= 0) + if (listQuery.Limit is { } __limit) { - __take = (int)System.Math.Min(limit, int.MaxValue); + __take = (int)System.Math.Min(__limit, int.MaxValue); } q = q.Take(__take); @@ -76,7 +61,7 @@ public static IEndpointRouteBuilder MapWidgetSummaryRoutes(this IEndpointRouteBu // withCount=1 → { rows, total } envelope; otherwise bare row array. var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", System.StringComparison.OrdinalIgnoreCase)); if (!withCount) return Results.Ok(rows); - var totalQ = EfCoreFilterDispatch.ApplyFilter(db.WidgetSummaries.AsNoTracking(), filter.Predicates); + var totalQ = EfCoreFilterDispatch.Apply(db.WidgetSummaries.AsNoTracking(), listQuery, WidgetSummaryFilterAllowlist.Rules); var total = await totalQ.CountAsync(); return Results.Ok(new { rows, total }); }); diff --git a/server/csharp/MetaObjects.Codegen.Tests/HelperRuntimeTests.cs b/server/csharp/MetaObjects.Codegen.Tests/HelperRuntimeTests.cs index 7ec67bd486..423e80aea9 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/HelperRuntimeTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/HelperRuntimeTests.cs @@ -194,18 +194,20 @@ public void Ejected_routes_output_compiles_against_the_owned_runtime_with_no_Met [Fact] public void Generated_routes_bind_to_the_owned_copy_an_edit_there_is_what_they_compile_against() { - // Rename the owned FilterParser.Parse. If the generated routes bound to anything but + // Rename the owned ListQueryParser.Parse. If the generated routes bound to anything but // the owned copy (the package, say), this would not touch them; instead every list // handler stops compiling, at the call site in the generated routes file. var files = GenerateWithEjectedRoutes(); - var edited = OwnedRuntime((file, text) => file == "FilterParser.cs" - ? text.Replace("public static FilterParseResult Parse(", "public static FilterParseResult ParseEdited(", StringComparison.Ordinal) + var edited = OwnedRuntime((file, text) => file == "ListQuery.cs" + ? text.Replace("public static ListQueryResult Parse(", "public static ListQueryResult ParseEdited(", StringComparison.Ordinal) : text); var errors = CompileErrors( files.Select(f => (f.Path, f.Content)).Concat(edited).Append(("GlobalUsings.g.cs", ImplicitUsings))); Assert.NotEmpty(errors); - Assert.All(errors, e => Assert.Contains("FilterParser", e)); - Assert.Contains(errors, e => e.Contains("Routes", StringComparison.Ordinal)); + // The missing Parse is named, and the knock-on errors (its result has no type) are all at the + // call sites in the generated routes. + Assert.Contains(errors, e => e.Contains("ListQueryParser", StringComparison.Ordinal)); + Assert.All(errors, e => Assert.Contains("Routes.g.cs", e)); } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs index 48ab09a310..be571b135a 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs @@ -309,16 +309,15 @@ public void Sort_and_EF_property_names_are_the_resolved_names_at_every_site() var vehicle = One(files, "VehicleRoutes.g.cs"); Assert.Contains("\"XTitle\" =>", gizmo); Assert.Contains("EF.Property(x!, \"XTitle\")", gizmo); - Assert.Contains("[\"XTitle\"] = true", gizmo); // @sortableDefaultOrder keys + Assert.Contains("[\"XTitle\"] = new SortFieldRule(\"desc\", \"XTitle\"),", gizmo); // @sortableDefaultOrder keys Assert.DoesNotContain("\"Title\"", gizmo); Assert.Contains("EF.Property(x!, \"XPlate\")", vehicle); // TPH base - Assert.Contains("[\"XSeatCount\"] = \"XSeatCount\",", vehicle); // per-subtype sort allowlist + Assert.Contains("[\"XSeatCount\"] = new SortFieldRule(property: \"XSeatCount\"),", vehicle); // per-subtype sort rules // A rename beyond case: ?sort= also takes the field name (the key ?filter[...] takes), resolved to the property. - Assert.Contains("Dictionary SortAllowlist", gizmo); - Assert.Contains("[\"title\"] = \"XTitle\",", gizmo); - Assert.Contains("[\"XTitle\"] = \"XTitle\",", gizmo); - Assert.Contains("[\"seatCount\"] = \"XSeatCount\",", vehicle); - Assert.Contains("[\"plate\"] = \"XPlate\",", vehicle); + Assert.Contains("Dictionary SortRules", gizmo); + Assert.Contains("[\"title\"] = new SortFieldRule(\"desc\", \"XTitle\"),", gizmo); + Assert.Contains("[\"seatCount\"] = new SortFieldRule(property: \"XSeatCount\"),", vehicle); + Assert.Contains("[\"plate\"] = new SortFieldRule(property: \"XPlate\"),", vehicle); Assert.DoesNotContain("\"Plate\"", vehicle); // M:N junction: the FK properties and the target key, by their resolved names. Assert.Contains("EF.Property(j, \"XVehicleId\")", vehicle); @@ -355,7 +354,7 @@ public void The_filter_dispatch_is_given_the_property_map_when_a_rename_goes_bey Assert.Contains("[\"title\"] = \"XTitle\"", allowlist); var gizmo = One(files, "GizmoRoutes.g.cs"); Assert.Contains("GizmoFilterAllowlist.PropertyByField", gizmo); - Assert.Contains("EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates, GizmoFilterAllowlist.PropertyByField)", gizmo); + Assert.Contains("EfCoreFilterDispatch.Apply(q, listQuery, GizmoFilterAllowlist.Rules, GizmoFilterAllowlist.PropertyByField)", gizmo); } private sealed class FilterRow diff --git a/server/csharp/MetaObjects.Codegen.Tests/ReportRowCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ReportRowCodegenTests.cs index d8f5e79fc2..e45b48f3f2 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ReportRowCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ReportRowCodegenTests.cs @@ -259,10 +259,11 @@ public void A_served_report_gets_a_routes_file_with_the_list_route_and_a_405_and Assert.DoesNotContain("projection", routes); // It reads the report's own DbSet and names the report's own allowlist. Assert.Contains("IQueryable q = db.StoreTotals.AsNoTracking();", routes); - Assert.Contains("EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, StoreTotalsFilterAllowlist.Fields, StoreTotalsFilterAllowlist.OpsByField));", routes); + Assert.Contains("ListQueryParser.Parse(http.Request.QueryString.Value, StoreTotalsFilterAllowlist.Rules, SortRules, StoreTotalsFilterAllowlist.FieldNames);", routes); + Assert.Contains("EfCoreFilterDispatch.Validate(listQuery)", routes); // Every derived scalar is sortable. foreach (var field in new[] { "Purchases", "Buyers", "Revenue" }) - Assert.Contains($" \"{field}\",", routes); + Assert.Contains($" [\"{field}\"] = new SortFieldRule(property: \"{field}\"),", routes); } [Fact] @@ -351,14 +352,14 @@ public void An_enum_dimension_of_a_report_is_sortable() // only, which leaves an enum out; a report's enum dimension is in. var routes = Emit(RunnerContext(Cube()), new RoutesGenerator())["SalesCubeRoutes.g.cs"]; string allowlist = routes[ - routes.IndexOf("SortAllowlist =", StringComparison.Ordinal)..routes.IndexOf("SortDefaultDesc =", StringComparison.Ordinal)]; - Assert.Contains(" \"Status\",\n", allowlist.ReplaceLineEndings("\n")); + routes.IndexOf("SortRules =", StringComparison.Ordinal)..routes.IndexOf("public static IEndpointRouteBuilder", StringComparison.Ordinal)]; + Assert.Contains(" [\"Status\"] = new SortFieldRule(property: \"Status\"),\n", allowlist.ReplaceLineEndings("\n")); Assert.Contains( " \"Status\" => desc ? q.OrderByDescending(x => EF.Property(x!, \"Status\") == null).ThenByDescending(x => EF.Property(x!, \"Status\")) : q.OrderBy(x => EF.Property(x!, \"Status\") == null).ThenBy(x => EF.Property(x!, \"Status\")),", routes); // Every derived field of the cube is in the sort allowlist, in Table B order. - var sortable = allowlist.Split('\n').Select(l => l.Trim()).Where(l => l.StartsWith('"')) - .Select(l => l.Trim('"', ',')).ToList(); + var sortable = allowlist.Split('\n').Select(l => l.Trim()).Where(l => l.StartsWith("[\"", StringComparison.Ordinal)) + .Select(l => l[2..l.IndexOf('"', 2)]).ToList(); Assert.Equal( [ "Store", "Channel", "Status", "StoreRegion", "SoldAtHour", "SoldAtDay", "SoldAtMonth", diff --git a/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs index e2448a045f..fdaeef4dfc 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs @@ -205,7 +205,7 @@ public void A_credential_marked_filterable_and_sortable_is_on_neither_allowlist( var routes = new RoutesGenerator().Generate(ctx) .Single(f => System.IO.Path.GetFileName(f.Path) == "AccountRoutes.g.cs").Content; - var start = routes.IndexOf("SortAllowlist", StringComparison.Ordinal); + var start = routes.IndexOf("SortRules", StringComparison.Ordinal); var end = routes.IndexOf("MapAccountRoutes", StringComparison.Ordinal); Assert.True(start >= 0 && end > start, routes); var sort = routes[start..end]; @@ -254,7 +254,7 @@ public void A_column_any_sibling_subtype_hides_is_on_no_filter_or_sort_allowlist var routes = new RoutesGenerator().Generate(ctx) .Single(f => System.IO.Path.GetFileName(f.Path) == "ThingRoutes.g.cs").Content; - var start = routes.IndexOf("SortAllowlist", StringComparison.Ordinal); + var start = routes.IndexOf("SortRules", StringComparison.Ordinal); var end = routes.IndexOf("MapThingRoutes", StringComparison.Ordinal); Assert.True(start >= 0 && end > start, routes); var sort = routes[start..end]; diff --git a/server/csharp/MetaObjects.Codegen.Tests/TphCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/TphCodegenTests.cs index 19365e9468..06b38c1f13 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/TphCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/TphCodegenTests.cs @@ -240,12 +240,13 @@ public void Routes_base_emits_polymorphic_and_per_subtype_no_subtype_files() Assert.Contains("OfType()", auth); // Polymorphic POST is NOT emitted on the base path itself. Assert.DoesNotContain("MapPost(prefix + \"/auths\",", auth); - // Per-subtype list ?sort resolves the raw qs field through a per-subtype - // case-insensitive allowlist to the CLR property name BEFORE EF.Property — + // Per-subtype list ?sort resolves the raw qs field through per-subtype + // case-insensitive sort rules to the CLR property name BEFORE EF.Property — // a raw "id" (vs "Id") otherwise fails EF translation and 500s. - Assert.Contains("BridgeAuthSortAllowlist", auth); - Assert.Contains("BridgeAuthSortAllowlist.TryGetValue(parts[0], out var resolved)", auth); - Assert.DoesNotContain("EF.Property(x!, parts[0])", auth); + Assert.Contains("BridgeAuthSortRules", auth); + Assert.Contains("BridgeAuthSortRules[__sort.Field].Property is { } __sortProp", auth); + Assert.Contains("EF.Property(x!, __sortProp)", auth); + Assert.DoesNotContain("EF.Property(x!, __sort.Field)", auth); } [Fact] diff --git a/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md b/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md index 6c40143a84..014cf51b60 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md +++ b/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md @@ -8,9 +8,10 @@ Update when a gap closes or a new one surfaces. - `GET /api/` list, `GET /:id`, `POST`, `PATCH /:id`, `PUT /:id`, `DELETE /:id` mount under `apiPrefix` (default `/api`); entity segment is lowercased + pluralized. - `?limit=N&offset=N` pagination — honoured on the list route. -- `?sort=:asc|desc` — honoured against a per-entity static `SortAllowlist` derived from scalar fields. Unknown field returns 400 `{ "error": "validation", "message": "unknown sort field: ..." }`. +- `?sort=:asc|desc` — honoured against per-entity static `SortRules` derived from scalar fields; `?sort=` takes its `@sortableDefaultOrder`. Unknown field returns 400 `{ "error": "invalid_sort", "field": ... }`. - `?withCount=1` — switches the list envelope from `[...]` to `{ rows, total }`. The grid hook always sends this. `total` reflects the filtered count when `filter[...]` is present. -- `?filter[][]=` (and the `filter[]=` sugar form for `eq`) — honoured against a per-entity `FilterAllowlist` emitted by `FilterAllowlistGenerator`. Errors return 400 `{ "error": "invalid_filter_field" | "invalid_filter_op" | "invalid_filter_value" }`. The list handler calls `FilterParser.Parse` and dispatches via `EfCoreFilterDispatch.ApplyFilter` (both in the `MetaObjects.AspNetCore` package). FR-009. +- `?filter[][]=` (and the `filter[]=` sugar form for `eq`) — honoured against a per-entity `FilterAllowlist` emitted by `FilterAllowlistGenerator`. Errors return 400 `{ "error": "invalid_filter_field" | "invalid_filter_op" | "invalid_filter_value" }`. The list handler calls `ListQueryParser.Parse` and applies the result via `EfCoreFilterDispatch.Apply` (both in the `MetaObjects.AspNetCore` package). FR-009. +- The REST standard's list handling (since 1.3.0): `filter[or]` / `filter[and]` groups five levels deep, `?search=`, and the `filter.bare_field`, `filter.leading_wildcard_disallowed` and `filter.nesting_too_deep` refusals. A body that is not JSON is 400 `{ "error": "invalid_json" }` and a path id the key cannot hold is 400 `{ "error": "invalid_id" }` (`RouteErrors`). Gated by `fixtures/list-query-conformance/` and the api-contract `list-query/` sub-corpus. - Both `PATCH` and `PUT` map to the same update handler (TS reference exposes both verbs; C# now matches). - 404 carries a JSON envelope: `{ "error": "not_found" }`. - Projection (`object.projection` over a read-only `source.rdb` `@kind: view`) routes are read-only — only `GET` list + `GET /:id` are mounted; no `POST` / `PATCH` / `PUT` / `DELETE`. @@ -19,12 +20,6 @@ Update when a gap closes or a new one surfaces. ## Gaps -### G2 — `filter[or]` / `filter[and]` nested boolean grouping - -**Contract.** `filter[or]=[...]` and `filter[and]=[...]` keys nest disjunctions / conjunctions. Reference: [`api-contract.md` "Filter operators (8)"](../../../../docs/features/api-contract.md). - -**Today.** Half closed. Since 1.3.0, `MetaObjects.AspNetCore` has `ListQueryParser`, which parses the whole list query: or/and groups to a depth of five, search, the bare-field and leading-`%` refusals, value-format checks and the named error details. `EfCoreFilterDispatch.Apply` turns the parsed tree into one `Where`. Each generated `FilterAllowlist` carries the `Rules`, `Sort` and `FieldNames` the parser reads. All 95 shared parse cases in `fixtures/list-query-conformance/` pass (`ListQueryConformanceTests`). The generated list routes do not call any of this yet; they still use the flat `FilterParser`. Wiring them up, and turning on the api-contract `list-query/` scenarios the C# runner holds back, closes this gap. - ### G3 — Multi-field sort **Contract.** Single sort key only in the default contract (`sort=:asc|desc`). Multi-field sort is NOT in scope for the contract today. @@ -35,7 +30,7 @@ Update when a gap closes or a new one surfaces. **Contract.** The exact `error` code vocabulary is NOT a hard Tier-1 invariant; consumers should treat any 4xx as user-facing and 5xx as retryable. Reference: [`api-contract.md` "Error response"](../../../../docs/features/api-contract.md). -**Today.** We emit `{ "error": "not_found" }` for 404 and `{ "error": "validation", "message": "..." }` for the sort-validation 400. **FR-036 wired explicit body validation with the cross-port `{ "error": "validation" }` envelope:** a POST runs `Validator.TryValidateObject(input, ...)` and a PATCH runs `Validator.TryValidateProperty(value, ...)` per present value → 400 `{ "error": "validation", "issues": [...] }` (ASP.NET minimal-API never runs DataAnnotations on its own, so the annotations were previously decorative at the wire tier). Since 1.3.0 the handler collects every failure (each DataAnnotations attribute run on its own, value-object members, JSON read failures) through `ValidationIssues` and lists them all in the cross-port shape, `{code, path, message}` with Zod's code names; before that the 400 was bare. +**Today.** We emit `{ "error": "not_found" }` for 404 and `{ "error": "invalid_sort", "field": ... }` for the sort-validation 400. **FR-036 wired explicit body validation with the cross-port `{ "error": "validation" }` envelope:** a POST runs `Validator.TryValidateObject(input, ...)` and a PATCH runs `Validator.TryValidateProperty(value, ...)` per present value → 400 `{ "error": "validation", "issues": [...] }` (ASP.NET minimal-API never runs DataAnnotations on its own, so the annotations were previously decorative at the wire tier). Since 1.3.0 the handler collects every failure (each DataAnnotations attribute run on its own, value-object members, JSON read failures) through `ValidationIssues` and lists them all in the cross-port shape, `{code, path, message}` with Zod's code names; before that the 400 was bare. ### G7 — Value-object columns on TPH entities are still skipped on PATCH diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index 3fd331a1a6..ce9c9381ab 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -12,9 +12,14 @@ // takes `defaultLimit` and a limit above `maxLimit` is 400 { "error": "limit_too_large", // "maxLimit": N }; without it, no limit answers 50 rows (ApiSettings.DefaultPageLimit, // the default of every port) and an explicit limit is served as asked. -// - GET list honours ?sort=:asc|desc against a static SortAllowlist -// derived from the entity's scalar fields (case-insensitive lookup). -// Unknown field → 400 { "error": "invalid_sort", "field": ... }. +// - GET list honours ?sort=:asc|desc against static SortRules derived from the +// entity's scalar fields (case-insensitive lookup); ?sort= takes the field's +// @sortableDefaultOrder. Unknown field → 400 { "error": "invalid_sort", "field": ... }. +// - GET list honours ?search= (case-insensitive, over the filterable text fields) and +// filter[or][i] / filter[and][i] groups, five levels deep. A bare ?= is +// 400 filter.bare_field and a leading % on like is filter.leading_wildcard_disallowed. +// - A body that is not JSON is 400 { "error": "invalid_json" }, and a path id the key's type +// cannot hold is 400 { "error": "invalid_id" } (RouteErrors). // - Create, PATCH and PUT: under `api.unknownFields: reject` (the default) a body key no // field declares is 400 { "error": "unknown_fields", "fields": [...] } (UnknownFieldCheck); // under `drop` it is ignored. A failed validation is 400 { "error": "validation", @@ -29,10 +34,10 @@ // on POST, with no /{id} address at all (a report has no identity). // // Filter operators (eq/ne/gt/gte/lt/lte/in/like/isNull) ship via FR-009 — the -// generated list handler calls FilterParser.Parse against the per-entity +// generated list handler calls ListQueryParser.Parse against the per-entity // FilterAllowlist (emitted by FilterAllowlistGenerator), then -// dispatches the resulting predicates onto the IQueryable via -// EfCoreFilterDispatch.ApplyFilter. Those helpers (and ValueObjectValidator, +// applies the parsed filter tree and search onto the IQueryable via +// EfCoreFilterDispatch.Apply. Those helpers (and ValueObjectValidator, // ConstraintErrors) live in the namespace HelperRuntimeNamespace names: the // MetaObjects.AspNetCore package for the packaged generator, the adopter's // own codegen/runtime/ copy (Codegen.Runtime) once `dotnet meta eject routes` has @@ -51,7 +56,7 @@ public class RoutesGenerator : PerEntityGenerator { public override string Name => "routes-generator"; - // Where the emitted routes import FilterParser / EfCoreFilterDispatch / + // Where the emitted routes import ListQueryParser / EfCoreFilterDispatch / RouteErrors / // ValueObjectValidator / ConstraintErrors from. `dotnet meta eject routes` rewrites // this one line to "Codegen.Runtime" and copies those helpers' source into // codegen/runtime/, so an owned copy's output binds to code the adopter owns. @@ -360,8 +365,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte w.Open("{"); // Static sort allowlist (case-insensitive) so the qs ?sort=field:dir // is gated against the entity's scalar fields. - WriteSortAllowlist(w, "SortAllowlist", p.SortFieldNodes, ctx.Config); - WriteSortDefaultOrder(w, entity, "SortDefaultDesc", ctx.Config); + WriteSortRules(w, "SortRules", p.SortFieldNodes, ctx.Config); if (p.Writable) WriteKnownFields(w, [entity], ctx.Root); WriteUnauthenticatedRoutesDoc(w, p.Cls, p.IsProjection); w.Line($"public static IEndpointRouteBuilder Map{p.Cls}Routes(this IEndpointRouteBuilder app, string prefix = \"/api\")"); @@ -448,34 +452,11 @@ protected virtual void WriteListRoute(CsWriter w, StandardRoutesPlan p) } w.Line($"IQueryable<{readCls}> q = db." + readDbSet + ".AsNoTracking();"); w.Blank(); - w.Line("// Filter: ?filter[][]= against the per-entity allowlist."); var fm = FilterMapArg($"{cls}FilterAllowlist", p.Entity, p.Ctx.Config); - w.Line($"var filter = EfCoreFilterDispatch.Validate<{readCls}>(FilterParser.Parse(qs, {cls}FilterAllowlist.Fields, {cls}FilterAllowlist.OpsByField){fm});"); - w.Line("if (filter.ErrorEnvelope is not null)"); - // `field` names the rejected filter field — required cross-port on every - // filter envelope, so a caller with several filters knows which one failed. - using (w.Hanging()) w.Line("return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field });"); - w.Line($"q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates{fm});"); - w.Blank(); - w.Line("// Sort: ?sort=field:asc|desc against the static allowlist."); - w.Line("if (qs.TryGetValue(\"sort\", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw))"); - w.Open("{"); - w.Line("var parts = sortRaw.ToString().Split(':', 2);"); - w.Line("var field = parts[0];"); - w.Line("if (!SortAllowlist.TryGetValue(field, out var resolved))"); - using (w.Hanging()) w.Line("return Results.BadRequest(new { error = \"invalid_sort\", field });"); - // `?sort=field` with no `:order` takes the field's DECLARED @sortableDefaultOrder. - // Keyed on `resolved` — the allowlist's canonical Pascal spelling — so a - // case-insensitive wire name still finds its declaration. Ascending stays the - // fallback HERE, one place per port. - w.Line("var desc = parts.Length > 1"); - using (w.Hanging()) w.Line("? string.Equals(parts[1], \"desc\", System.StringComparison.OrdinalIgnoreCase)"); - using (w.Hanging()) w.Line(": SortDefaultDesc.TryGetValue(resolved, out var dd) && dd;"); - if (p.SqliteSort) - w.Line($"q = ApplySort{cls}(q, resolved, desc, db.Database.ProviderName?.Contains(\"Sqlite\", System.StringComparison.OrdinalIgnoreCase) == true);"); - else - w.Line($"q = ApplySort{cls}(q, resolved, desc);"); - w.Close("}"); + WriteListQuery(w, readCls, $"{cls}FilterAllowlist", fm, "SortRules", + p.SqliteSort + ? $"ApplySort{cls}(q, __sortProp, desc, db.Database.ProviderName?.Contains(\"Sqlite\", System.StringComparison.OrdinalIgnoreCase) == true)" + : $"ApplySort{cls}(q, __sortProp, desc)"); w.Blank(); if (p.IsReport) { @@ -484,8 +465,7 @@ protected virtual void WriteListRoute(CsWriter w, StandardRoutesPlan p) } else { - w.Line("// Pagination: ?offset=N first (skip), then ?limit=N (take)."); - WriteOffsetLimit(w, p.Ctx.Root.Api.Pagination, "offsetRaw", "offset", "limitRaw", "limit"); + WriteListPage(w, p.Ctx.Root.Api.Pagination); w.Blank(); w.Line("var rows = await q.ToListAsync();"); } @@ -496,7 +476,7 @@ protected virtual void WriteListRoute(CsWriter w, StandardRoutesPlan p) w.Line($"if (!withCount) return {OkResult("rows", credentials)};"); else w.Line($"if (!withCount) return format is null ? {OkResult("rows", credentials)} : ReportExportHttp.Json(http, \"{route}\", rows{ExportOmit(credentials, false)});"); - w.Line($"var totalQ = EfCoreFilterDispatch.ApplyFilter(db.{readDbSet}.AsNoTracking(), filter.Predicates{fm});"); + w.Line($"var totalQ = EfCoreFilterDispatch.Apply(db.{readDbSet}.AsNoTracking(), listQuery, {cls}FilterAllowlist.Rules{fm});"); w.Line("var total = await totalQ.CountAsync();"); if (export is null) w.Line($"return {OkResult("new { rows, total }", credentials, envelope: true)};"); @@ -509,10 +489,13 @@ protected virtual void WriteListRoute(CsWriter w, StandardRoutesPlan p) protected virtual void WriteGetRoute(CsWriter w, StandardRoutesPlan p) { w.Blank(); - w.Line("app.MapGet(prefix + \"/" + p.Route + "/{id}\", async (" + p.PkType + " id, " + p.ContextType + " db) =>"); - using (w.Hanging()) w.Line("await db." + p.ReadDbSet + ".FindAsync(id) is { } found"); - using (w.Hanging()) using (w.Hanging()) w.Line("? " + OkResult("found", p.Credentials)); - using (w.Hanging()) using (w.Hanging()) w.Line(": Results.NotFound(new { error = \"not_found\" }));"); + w.Line("app.MapGet(prefix + \"/" + p.Route + "/{id}\", async (HttpContext http, " + p.ContextType + " db) =>"); + w.Open("{"); + WriteReadId(w, p.PkType!); + w.Line("return await db." + p.ReadDbSet + ".FindAsync(id) is { } found"); + using (w.Hanging()) w.Line("? " + OkResult("found", p.Credentials)); + using (w.Hanging()) w.Line(": Results.NotFound(new { error = \"not_found\" });"); + w.Close("});"); } /// The create route: POST /<route> (see ). @@ -559,13 +542,14 @@ protected virtual void WriteUpdateRoute(CsWriter w, StandardRoutesPlan p) // is a 400. The per-key merge (shared with the TPH per-subtype handler) is // emitted by WritePartialMergeLoop. w.Blank(); - w.Line("async System.Threading.Tasks.Task Update" + cls + "(" + p.PkType + " id, HttpContext http, " + p.ContextType + " db)"); + w.Line("async System.Threading.Tasks.Task Update" + cls + "(HttpContext http, " + p.ContextType + " db)"); w.Open("{"); + WriteReadId(w, p.PkType!); w.Line("var existing = await db." + dbSet + ".FindAsync(id);"); w.Line("if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); w.Line("System.Text.Json.JsonDocument body;"); w.Line("try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }"); - w.Line("catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); }"); + w.Line("catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); }"); w.Line("using var bodyScope = body;"); w.Line("if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable();"); WriteUnknownFieldsCheck(w, ctx.Root, "body"); @@ -604,8 +588,9 @@ protected virtual void WriteUpdateRoute(CsWriter w, StandardRoutesPlan p) protected virtual void WriteDeleteRoute(CsWriter w, StandardRoutesPlan p) { w.Blank(); - w.Line("app.MapDelete(prefix + \"/" + p.Route + "/{id}\", async (" + p.PkType + " id, " + p.ContextType + " db) =>"); + w.Line("app.MapDelete(prefix + \"/" + p.Route + "/{id}\", async (HttpContext http, " + p.ContextType + " db) =>"); w.Open("{"); + WriteReadId(w, p.PkType!); w.Line("var existing = await db." + p.DbSet + ".FindAsync(id);"); w.Line("if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); w.Line("db." + p.DbSet + ".Remove(existing);"); @@ -755,8 +740,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t w.Open("{"); // Polymorphic sort allowlist over the base scalar columns. - WriteSortAllowlist(w, "SortAllowlist", p.SortFieldNodes, ctx.Config); - WriteSortDefaultOrder(w, baseEntity, "SortDefaultDesc", ctx.Config); + WriteSortRules(w, "SortRules", p.SortFieldNodes, ctx.Config); // One known set for the whole hierarchy: a sibling subtype's column is declared, so it is not unknown. WriteKnownFields(w, p.Hierarchy, ctx.Root); @@ -771,8 +755,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t var subSortFields = st.Entity.Fields() .Where(f => CSharpNaming.ScalarFor(f.SubType) is not null && !f.ResolvedIsArray() && !p.HierarchyCredentials.Contains(f.Name)) .ToList(); - WriteSortAllowlist(w, $"{subClsName}SortAllowlist", subSortFields, ctx.Config); - WriteSortDefaultOrder(w, st.Entity, $"{subClsName}SortDefaultDesc", ctx.Config); + WriteSortRules(w, $"{subClsName}SortRules", subSortFields, ctx.Config); } WriteUnauthenticatedRoutesDoc(w, baseCls, readOnly: false); @@ -834,23 +817,12 @@ protected virtual void WriteTphListRoute(CsWriter w, TphRoutesPlan p) w.Line("var qs = http.Request.Query;"); w.Line($"IQueryable<{baseCls}> q = db.{dbSet}.AsNoTracking();"); var fmB = FilterMapArg($"{baseCls}FilterAllowlist", p.BaseEntity, ctx.Config); - w.Line($"var filter = EfCoreFilterDispatch.Validate<{baseCls}>(FilterParser.Parse(qs, {baseCls}FilterAllowlist.Fields, {baseCls}FilterAllowlist.OpsByField){fmB});"); - w.Line("if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field });"); - w.Line($"q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates{fmB});"); - w.Line("if (qs.TryGetValue(\"sort\", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw))"); - w.Open("{"); - w.Line("var parts = sortRaw.ToString().Split(':', 2);"); - w.Line("if (!SortAllowlist.TryGetValue(parts[0], out var resolved)) return Results.BadRequest(new { error = \"invalid_sort\", field = parts[0] });"); - w.Line("var desc = parts.Length > 1"); - using (w.Hanging()) w.Line("? string.Equals(parts[1], \"desc\", System.StringComparison.OrdinalIgnoreCase)"); - using (w.Hanging()) w.Line(": SortDefaultDesc.TryGetValue(resolved, out var dd) && dd;"); - w.Line("q = ApplySort(q, resolved, desc);"); - w.Close("}"); - WriteOffsetLimit(w, ctx.Root.Api.Pagination, "offRaw", "off", "limRaw", "lim"); + WriteListQuery(w, baseCls, $"{baseCls}FilterAllowlist", fmB, "SortRules", "ApplySort(q, __sortProp, desc)"); + WriteListPage(w, ctx.Root.Api.Pagination); w.Line("var rows = await q.ToListAsync();"); w.Line("var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", System.StringComparison.OrdinalIgnoreCase));"); w.Line($"if (!withCount) return {OkResult("rows", p.BaseCredentials)};"); - w.Line($"var total = await EfCoreFilterDispatch.ApplyFilter(db.{dbSet}.AsNoTracking(), filter.Predicates{fmB}).CountAsync();"); + w.Line($"var total = await EfCoreFilterDispatch.Apply(db.{dbSet}.AsNoTracking(), listQuery, {baseCls}FilterAllowlist.Rules{fmB}).CountAsync();"); w.Line($"return {OkResult("new { rows, total }", p.BaseCredentials, envelope: true)};"); w.Close("});"); } @@ -859,10 +831,13 @@ protected virtual void WriteTphListRoute(CsWriter w, TphRoutesPlan p) protected virtual void WriteTphGetRoute(CsWriter w, TphRoutesPlan p) { w.Blank(); - w.Line("app.MapGet(prefix + \"/" + p.BaseRoute + "/{id}\", async (" + p.PkType + " id, " + p.ContextType + " db) =>"); - using (w.Hanging()) w.Line($"await db.{p.DbSet}.AsNoTracking().FirstOrDefaultAsync(x => x.{p.PkProp} == id) is {{ }} found"); - using (w.Hanging()) using (w.Hanging()) w.Line("? " + OkResult("found", p.BaseCredentials)); - using (w.Hanging()) using (w.Hanging()) w.Line(": Results.NotFound(new { error = \"not_found\" }));"); + w.Line("app.MapGet(prefix + \"/" + p.BaseRoute + "/{id}\", async (HttpContext http, " + p.ContextType + " db) =>"); + w.Open("{"); + WriteReadId(w, p.PkType!); + w.Line($"return await db.{p.DbSet}.AsNoTracking().FirstOrDefaultAsync(x => x.{p.PkProp} == id) is {{ }} found"); + using (w.Hanging()) w.Line("? " + OkResult("found", p.BaseCredentials)); + using (w.Hanging()) w.Line(": Results.NotFound(new { error = \"not_found\" });"); + w.Close("});"); } /// The polymorphic sort dispatch over the base's scalar columns (reflection-free, through EF.Property). @@ -1002,29 +977,22 @@ protected static IEnumerable CredentialSpellings(MetaField f, GenConfig protected static string KeyMatch(IEnumerable keys) => string.Join(" || ", keys.Select(k => $"string.Equals(prop.Name, \"{k}\", System.StringComparison.OrdinalIgnoreCase)")); - // A sort allowlist (case-insensitive): `TryGetValue(key, out var resolved)` gives the CLR property to - // sort on. Without a rename beyond case it is the set of property names (the field name matches one - // ignoring case), as ever. When a resolver renamed a property beyond case it is a map that accepts the - // field name too, so `?sort=` takes the same key as `?filter[...]` (which keys on the field name) - // and the property name a client may have read from a response. - protected virtual void WriteSortAllowlist(CsWriter w, string name, IReadOnlyList fields, GenConfig config) + // The sort rules (case-insensitive) a list route hands ListQueryParser: each key gives the CLR property to + // sort on and the field's DECLARED @sortableDefaultOrder. The keys are the property names (the field name + // matches one ignoring case); when a resolver renamed a property beyond case the field name is a key too, + // so `?sort=` takes the same key as `?filter[...]` (which keys on the field name) and the property name a + // client may have read from a response. + protected virtual void WriteSortRules(CsWriter w, string name, IReadOnlyList fields, GenConfig config) { - var pairs = fields.Select(f => (Field: f.Name, Prop: CSharpNaming.PropertyName(f, config))).ToList(); - if (pairs.All(p => string.Equals(p.Field, p.Prop, StringComparison.OrdinalIgnoreCase))) - { - w.Line($"private static readonly System.Collections.Generic.HashSet {name} = new(System.StringComparer.OrdinalIgnoreCase)"); - w.Open("{"); - foreach (var p in pairs) w.Line($"\"{p.Prop}\","); - w.Close("};"); - w.Blank(); - return; - } - w.Line($"private static readonly System.Collections.Generic.Dictionary {name} = new(System.StringComparer.OrdinalIgnoreCase)"); + var pairs = fields.Select(f => (Field: f.Name, Prop: CSharpNaming.PropertyName(f, config), Order: f.Attr(FIELD_ATTR_SORTABLE_DEFAULT_ORDER) as string)).ToList(); + w.Line($"private static readonly System.Collections.Generic.Dictionary {name} = new(System.StringComparer.OrdinalIgnoreCase)"); w.Open("{"); // Property names first, so a field name that spells another field's property never shadows it. var keys = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (var p in pairs) if (keys.Add(p.Prop)) w.Line($"[\"{p.Prop}\"] = \"{p.Prop}\","); - foreach (var p in pairs) if (keys.Add(p.Field)) w.Line($"[\"{p.Field}\"] = \"{p.Prop}\","); + static string Rule((string Field, string Prop, string? Order) p) => + p.Order is "asc" or "desc" ? $"new SortFieldRule(\"{p.Order}\", \"{p.Prop}\")" : $"new SortFieldRule(property: \"{p.Prop}\")"; + foreach (var p in pairs) if (keys.Add(p.Prop)) w.Line($"[\"{p.Prop}\"] = {Rule(p)},"); + foreach (var p in pairs) if (keys.Add(p.Field)) w.Line($"[\"{p.Field}\"] = {Rule(p)},"); w.Close("};"); w.Blank(); } @@ -1215,39 +1183,56 @@ protected virtual void WriteUnknownFieldsCheck(CsWriter w, MetaRoot root, string w.Line($"if (UnknownFieldCheck.Reject({bodyVar}.RootElement, {KnownFieldsConst}, http) is {{ }} __unknown) return __unknown;"); } - // The offset + limit lines of a list route. A bound that is present but not a non-negative integer is - // refused (pagination.invalid_value), never read as "absent". No limit takes `api.pagination`'s - // defaultLimit, or ApiSettings.DefaultPageLimit (50, as in every port) when the project sets no block; - // with the block, a limit above maxLimit is 400 limit_too_large, and without it there is no maximum. - protected virtual void WriteOffsetLimit(CsWriter w, ApiPagination? page, string offRaw, string off, string limRaw, string lim) + // The first line of an item handler: the `{id}` route value read as the key's type, or 400 invalid_id + // (RouteErrors). The handler binds no typed id itself, because ASP.NET Core's binding answers an + // unparsable one with an empty 400. + protected virtual void WriteReadId(CsWriter w, string pkType) => + w.Line($"if (!RouteErrors.TryReadId<{pkType}>(http, out var id)) return RouteErrors.InvalidId();"); + + // The offset + limit lines of a list route, over the bounds ListQueryParser already read (a bound that is + // present but not a non-negative integer was refused there, pagination.invalid_value). No limit takes + // `api.pagination`'s defaultLimit, or ApiSettings.DefaultPageLimit (50, as in every port) when the project + // sets no block; with the block, a limit above maxLimit is 400 limit_too_large, and without it there is no + // maximum. `limit=0` is a page of zero rows, as every other port serves it, not "no limit". + protected virtual void WriteListPage(CsWriter w, ApiPagination? page) { - w.Line($"if (qs.TryGetValue(\"offset\", out var {offRaw}Bad) && !(int.TryParse({offRaw}Bad, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {off}Bad) && {off}Bad >= 0))"); - using (w.Hanging()) w.Line($"return Results.BadRequest(new {{ error = \"pagination.invalid_value\", param = \"offset\", value = {offRaw}Bad.ToString(), expected = \"a non-negative integer (0 or more)\" }});"); - w.Line($"if (qs.TryGetValue(\"offset\", out var {offRaw}) && int.TryParse({offRaw}, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {off}) && {off} > 0)"); - using (w.Hanging()) w.Line($"q = q.Skip({off});"); - w.Line($"if (qs.TryGetValue(\"limit\", out var {limRaw}Neg) && !(long.TryParse({limRaw}Neg, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {lim}Neg) && {lim}Neg >= 0))"); - using (w.Hanging()) w.Line($"return Results.BadRequest(new {{ error = \"pagination.invalid_value\", param = \"limit\", value = {limRaw}Neg.ToString(), expected = \"a non-negative integer (0 or more)\" }});"); + w.Line("// Pagination: ?offset=N first (skip), then ?limit=N (take)."); + w.Line("if (listQuery.Offset is { } __offset && __offset > 0)"); + using (w.Hanging()) w.Line("q = q.Skip((int)System.Math.Min(__offset, int.MaxValue));"); if (page is not null) w.Line("// api.pagination: no limit takes defaultLimit; a limit above maxLimit is refused."); else w.Line("// No api.pagination: no limit takes the default page of 50; an explicit limit is served as asked."); w.Line($"var __take = {page?.DefaultLimit ?? ApiSettings.DefaultPageLimit};"); - // `limit=0` is a page of zero rows, as every other port serves it, not "no limit". - w.Line($"if (qs.TryGetValue(\"limit\", out var {limRaw}) && long.TryParse({limRaw}, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var {lim}) && {lim} >= 0)"); + w.Line("if (listQuery.Limit is { } __limit)"); w.Open("{"); if (page is not null) - { - w.Line($"if ({lim} > {page.MaxLimit}) return Results.BadRequest(new {{ error = \"limit_too_large\", maxLimit = {page.MaxLimit} }});"); - w.Line($"__take = (int){lim};"); - } - else - { - w.Line($"__take = (int)System.Math.Min({lim}, int.MaxValue);"); - } + w.Line($"if (__limit > {page.MaxLimit}) return Results.BadRequest(new {{ error = \"limit_too_large\", maxLimit = {page.MaxLimit} }});"); + w.Line("__take = (int)System.Math.Min(__limit, int.MaxValue);"); w.Close("}"); w.Line("q = q.Take(__take);"); } + // The REST standard's list handling (ListQueryParser): the filter tree with or/and groups, ?search, the + // sort, and the named refusals (filter.bare_field, filter.leading_wildcard_disallowed, + // filter.nesting_too_deep, invalid_filter_value, invalid_sort, pagination.invalid_value), then the parsed + // filter and search applied to `q` and the sort through `sortExpr` (which reads `__sortProp`, the CLR + // property, and `desc`). Leaves `listQuery` in scope for the page bounds and the withCount total. + protected virtual void WriteListQuery(CsWriter w, string entityType, string allowlist, string fm, string sortRules, string sortExpr) + { + w.Line("// ?filter[...] (or/and groups), ?search, ?sort and the page bounds, against the allowlist."); + w.Line($"var __parsed = ListQueryParser.Parse(http.Request.QueryString.Value, {allowlist}.Rules, {sortRules}, {allowlist}.FieldNames);"); + w.Line("if (__parsed.Error is { } __refused) return Results.BadRequest(__refused.Body());"); + w.Line("var listQuery = __parsed.Query!;"); + w.Line($"if (EfCoreFilterDispatch.Validate<{entityType}>(listQuery{fm}) is {{ }} __invalid) return Results.BadRequest(__invalid.Body());"); + w.Line($"q = EfCoreFilterDispatch.Apply(q, listQuery, {allowlist}.Rules{fm});"); + w.Line($"if (listQuery.Sort is {{ }} __sort && {sortRules}[__sort.Field].Property is {{ }} __sortProp)"); + w.Open("{"); + w.Line("var desc = __sort.Descending;"); + w.Line($"q = {sortExpr};"); + w.Close("}"); + } + protected virtual void WriteCreateHandler( CsWriter w, string mapPath, string cls, string ctxType, string dbSet, IReadOnlyList requiredKeys, string createdExpr, IReadOnlyList voFields, @@ -1268,7 +1253,7 @@ protected virtual void WriteCreateHandler( WriteJsonOptsLocal(w); w.Line("System.Text.Json.JsonDocument __body;"); w.Line("try { __body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }"); - w.Line("catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); }"); + w.Line("catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); }"); w.Line("using var __bodyScope = __body;"); w.Line("if (__body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object)"); using (w.Hanging()) w.Line("return ValidationIssues.Unreadable();"); @@ -1782,32 +1767,24 @@ protected virtual void WriteTphSubtypeRoutes( w.Line("var qs = http.Request.Query;"); w.Line($"IQueryable<{subType}> q = db.{dbSet}.OfType<{subType}>().AsNoTracking();"); var fmS = FilterMapArg(subAllowlist, st.Entity, config); - w.Line($"var filter = EfCoreFilterDispatch.Validate<{subType}>(FilterParser.Parse(qs, {subAllowlist}.Fields, {subAllowlist}.OpsByField){fmS});"); - w.Line("if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field });"); - w.Line($"q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates{fmS});"); - w.Line("if (qs.TryGetValue(\"sort\", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw))"); - w.Open("{"); - w.Line("var parts = sortRaw.ToString().Split(':', 2);"); - w.Line($"if (!{subCls}SortAllowlist.TryGetValue(parts[0], out var resolved)) return Results.BadRequest(new {{ error = \"invalid_sort\", field = parts[0] }});"); - w.Line("var desc = parts.Length > 1"); - using (w.Hanging()) w.Line("? string.Equals(parts[1], \"desc\", System.StringComparison.OrdinalIgnoreCase)"); - using (w.Hanging()) w.Line($": {subCls}SortDefaultDesc.TryGetValue(resolved, out var dd) && dd;"); - w.Line("q = " + NullsLargestSort("q", "EF.Property(x!, resolved)") + ";"); - w.Close("}"); - WriteOffsetLimit(w, root.Api.Pagination, "offRaw", "off", "limRaw", "lim"); + WriteListQuery(w, subType, subAllowlist, fmS, $"{subCls}SortRules", NullsLargestSort("q", "EF.Property(x!, __sortProp)")); + WriteListPage(w, root.Api.Pagination); w.Line("var rows = await q.ToListAsync();"); w.Line("var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", System.StringComparison.OrdinalIgnoreCase));"); w.Line($"if (!withCount) return {OkResult("rows", credentials)};"); - w.Line($"var total = await EfCoreFilterDispatch.ApplyFilter(db.{dbSet}.OfType<{subType}>().AsNoTracking(), filter.Predicates{fmS}).CountAsync();"); + w.Line($"var total = await EfCoreFilterDispatch.Apply(db.{dbSet}.OfType<{subType}>().AsNoTracking(), listQuery, {subAllowlist}.Rules{fmS}).CountAsync();"); w.Line($"return {OkResult("new { rows, total }", credentials, envelope: true)};"); w.Close("});"); // Per-subtype get: GET ///{id} — scoped (cross-subtype → 404). w.Blank(); - w.Line("app.MapGet(prefix + \"/" + subRoute + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); - using (w.Hanging()) w.Line($"await db.{dbSet}.OfType<{subType}>().AsNoTracking().FirstOrDefaultAsync(x => x.{pkProp} == id) is {{ }} found"); - using (w.Hanging()) using (w.Hanging()) w.Line("? " + OkResult("found", credentials)); - using (w.Hanging()) using (w.Hanging()) w.Line(": Results.NotFound(new { error = \"not_found\" }));"); + w.Line("app.MapGet(prefix + \"/" + subRoute + "/{id}\", async (HttpContext http, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); + w.Open("{"); + WriteReadId(w, pkType!); + w.Line($"return await db.{dbSet}.OfType<{subType}>().AsNoTracking().FirstOrDefaultAsync(x => x.{pkProp} == id) is {{ }} found"); + using (w.Hanging()) w.Line("? " + OkResult("found", credentials)); + using (w.Hanging()) w.Line(": Results.NotFound(new { error = \"not_found\" });"); + w.Close("});"); // Per-subtype create: POST // — discriminator injected by EF via the // subtype CLR type; the POST body OMITS the discriminator. FR-036 #4: the @required-key @@ -1830,13 +1807,14 @@ protected virtual void WriteTphSubtypeRoutes( // Per-subtype update (PATCH + PUT): partial merge of the JSON body onto the scoped // entity, NEVER touching the PK or the discriminator. Cross-subtype id → 404. w.Blank(); - w.Line("async System.Threading.Tasks.Task Update" + subCls + "(" + pkType + " id, HttpContext http, " + ValueObjectNames.ContextTypeRef(config) + " db)"); + w.Line("async System.Threading.Tasks.Task Update" + subCls + "(HttpContext http, " + ValueObjectNames.ContextTypeRef(config) + " db)"); w.Open("{"); + WriteReadId(w, pkType!); w.Line($"var existing = await db.{dbSet}.OfType<{subType}>().FirstOrDefaultAsync(x => x.{pkProp} == id);"); w.Line("if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); w.Line("System.Text.Json.JsonDocument body;"); w.Line("try { body = await System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }"); - w.Line("catch (System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); }"); + w.Line("catch (System.Text.Json.JsonException) { return RouteErrors.InvalidJson(); }"); w.Line("using var bodyScope = body;"); w.Line("if (body.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable();"); WriteUnknownFieldsCheck(w, root, "body"); @@ -1859,8 +1837,9 @@ protected virtual void WriteTphSubtypeRoutes( // Per-subtype delete: DELETE ///{id} — scoped (cross-subtype → 404). w.Blank(); - w.Line("app.MapDelete(prefix + \"/" + subRoute + "/{id}\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); + w.Line("app.MapDelete(prefix + \"/" + subRoute + "/{id}\", async (HttpContext http, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); w.Open("{"); + WriteReadId(w, pkType!); w.Line($"var existing = await db.{dbSet}.OfType<{subType}>().FirstOrDefaultAsync(x => x.{pkProp} == id);"); w.Line("if (existing is null) return Results.NotFound(new { error = \"not_found\" });"); w.Line($"db.{dbSet}.Remove(existing);"); @@ -1960,8 +1939,9 @@ protected virtual void WriteM2mRoute( ? JunctionProperty(nav.Target, tf[0], config) : "Id"; w.Blank(); - w.Line("app.MapGet(prefix + \"/" + sourceRoute + "/{id}/" + relSeg + "\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); + w.Line("app.MapGet(prefix + \"/" + sourceRoute + "/{id}/" + relSeg + "\", async (HttpContext http, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); w.Open("{"); + WriteReadId(w, pkType); if (sourceScope is not null) { // Rule c — prove the id names a row of THIS subtype before touching the @@ -2027,22 +2007,6 @@ protected static string JunctionFkType(M2MNavigation nav) /// default into its map. Attr() is the RESOLVING accessor (ADR-0039), so an /// order inherited via extends is honoured. /// - protected virtual void WriteSortDefaultOrder(CsWriter w, MetaObject owner, string constName, GenConfig config) - { - w.Line($"private static readonly System.Collections.Generic.Dictionary {constName} = new(System.StringComparer.OrdinalIgnoreCase)"); - w.Open("{"); - foreach (var f in owner.Fields()) - { - if (CSharpNaming.ScalarFor(f.SubType) is null || f.ResolvedIsArray()) continue; - if (f.Attr(FIELD_ATTR_SORTABLE_DEFAULT_ORDER) is not string v) continue; - if (v != "asc" && v != "desc") continue; - w.Line($"[\"{CSharpNaming.PropertyName(f, config)}\"] = {(v == "desc" ? "true" : "false")},"); - } - w.Close("};"); - w.Blank(); - } - - /// /// The emitted sort expression for one column, with nulls LARGER than any value: ASC puts /// them last, DESC first, on every provider (Postgres's own default; SQLite and MySQL diff --git a/server/csharp/MetaObjects.Codegen/HelperRuntime.cs b/server/csharp/MetaObjects.Codegen/HelperRuntime.cs index 2992a248f8..a358e886c3 100644 --- a/server/csharp/MetaObjects.Codegen/HelperRuntime.cs +++ b/server/csharp/MetaObjects.Codegen/HelperRuntime.cs @@ -72,6 +72,7 @@ public static class HelperRuntime /// is built with a report-export generator wired calls it. /// SerializerKeys.cs reads the host serializer's own JSON key for a property, so credential /// stripping and the PATCH key lookup agree with it under any naming policy. + /// RouteErrors.cs answers the named invalid_json and invalid_id refusals. /// public static readonly IReadOnlyList Files = [ @@ -92,6 +93,7 @@ public static class HelperRuntime "DecimalRangeEndpointFilter.cs", "ReportExportHttp.cs", "SerializerKeys.cs", + "RouteErrors.cs", ]; /// MetaObjects.Codegen/Runtime/ files that are CORE and never copied (see the header). diff --git a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj index 8ad370cce6..11a6dc6f9b 100644 --- a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj +++ b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj @@ -94,5 +94,6 @@ + diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractApiSettingsConformanceTest.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractApiSettingsConformanceTest.cs index ecd9eaab34..1f0431b000 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractApiSettingsConformanceTest.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractApiSettingsConformanceTest.cs @@ -27,13 +27,14 @@ public async Task Api_contract_api_settings_generated(string scenarioPath) // The corpus cannot pin this: Java/Kotlin answer Spring's type-mismatch 400 and Python FastAPI's 422 // for a non-numeric bound, so the generated C# route is exercised here against the cross-port 400 envelope. - // Only the plain entity list is driven: the TPH base and per-subtype lists emit through the same - // WriteOffsetLimit, and no TPH fixture with api.pagination boots in this lane. + // Only the plain entity list is driven: the TPH base and per-subtype lists read the same + // ListQueryParser bounds, and no TPH fixture with api.pagination boots in this lane. [Theory] [InlineData("/api/items?limit=abc", "limit", "abc")] [InlineData("/api/items?limit=1O", "limit", "1O")] [InlineData("/api/items?offset=x", "offset", "x")] - [InlineData("/api/items?offset=3000000000", "offset", "3000000000")] + // 2^53: one past the largest bound the TypeScript reference accepts (Number.isSafeInteger). + [InlineData("/api/items?offset=9007199254740992", "offset", "9007199254740992")] [InlineData("/api/items?offset=-5", "offset", "-5")] public async Task Non_numeric_page_bound_is_refused_not_served_as_default_page(string path, string param, string value) { diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractListQueryConformanceTest.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractListQueryConformanceTest.cs index 88402bfb60..90a6b27d9b 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractListQueryConformanceTest.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractListQueryConformanceTest.cs @@ -2,12 +2,8 @@ // // Drives the fixtures/api-contract-conformance/list-query/ scenarios over HTTP against the // GENERATED Part routes booted unmodified on Kestrel against a Postgres testcontainer, over the -// corpus's 60-row seed. Generated lane only, as the corpus README rules. -// -// The REST-standard work (search, or/and groups, the bare-field and leading-% refusals, the named -// error bodies) lands in C# with R-CS-1 and R-CS-2; until then those scenarios are listed in -// NotYetInCSharp, by name, and each one is checked to exist so the list cannot go stale. Every -// other scenario in the directory runs, so a new one is held to C# by default. +// corpus's 60-row seed. Generated lane only, as the corpus README rules. Every scenario in the +// directory runs, so a new one is held to C# by default. using System.Text.Json; using System.Text.Json.Nodes; @@ -18,25 +14,6 @@ namespace MetaObjects.IntegrationTests.Api; public sealed class ApiContractListQueryConformanceTest { - /// Scenarios the C# routes do not answer yet (the REST standard, R-CS-1 and R-CS-2). - internal static readonly IReadOnlySet NotYetInCSharp = new HashSet(StringComparer.Ordinal) - { - "and-inside-or", - "bare-field-not-filterable-refused", - "bare-field-refused", - "count-matches-the-filter", - "invalid-id", - "invalid-json", - "leading-wildcard-refused", - "nesting-at-the-cap", - "nesting-too-deep", - "or-beside-a-field", - "or-two-branches", - "search-is-case-insensitive", - "search-matches-every-text-field", - "search-with-filter", - }; - [Theory] [MemberData(nameof(Scenarios))] public async Task Api_contract_list_query_generated(string scenarioPath) @@ -48,21 +25,12 @@ public async Task Api_contract_list_query_generated(string scenarioPath) await RunAsync(scenario, server.BaseUrl); } - [Fact] - public void Every_scenario_not_yet_in_CSharp_exists() - { - var names = AllScenarioPaths().Select(Path.GetFileNameWithoutExtension).ToHashSet(StringComparer.Ordinal); - Assert.Empty(NotYetInCSharp.Where(n => !names.Contains(n))); - } - private static IEnumerable AllScenarioPaths() => Directory.EnumerateFiles(ApiContractCorpusPaths.ListQueryScenariosDir, "*.yaml", SearchOption.TopDirectoryOnly) .OrderBy(p => p, StringComparer.Ordinal); public static IEnumerable Scenarios() => - AllScenarioPaths() - .Where(p => !NotYetInCSharp.Contains(Path.GetFileNameWithoutExtension(p))) - .Select(p => new object[] { p }); + AllScenarioPaths().Select(p => new object[] { p }); private static async Task RunAsync(ApiScenario scenario, string baseUrl) { diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/DecimalWireGeneratedApiTests.cs b/server/csharp/MetaObjects.IntegrationTests/Api/DecimalWireGeneratedApiTests.cs index abffa8525b..005350a560 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/DecimalWireGeneratedApiTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/DecimalWireGeneratedApiTests.cs @@ -149,8 +149,9 @@ await ScenarioEngine.Postgres.ExecuteScriptAsync(pg.ConnectionString, Assert.DoesNotContain(" at ", bh); } - // A malformed or empty JSON body is the client's fault: 400 validation, never an unhandled - // JsonException (500) from the hand-parsed POST handler that decimal entities use. + // A malformed or empty JSON body is the client's fault: 400 invalid_json (the REST standard's + // name, as the TypeScript reference answers both), never an unhandled JsonException (500) from + // the hand-parsed POST handler that decimal entities use. [Fact] public async Task Malformed_and_empty_body_are_400_not_500_on_sqlite() { @@ -160,10 +161,10 @@ public async Task Malformed_and_empty_body_are_400_not_500_on_sqlite() var (s1, b1) = await Send(c, "POST", "/api/ledgers", "{not json"); Assert.Equal(400, s1); - Assert.Contains("validation", b1); + Assert.Equal("""{"error":"invalid_json"}""", b1); var (s2, b2) = await Send(c, "POST", "/api/ledgers", ""); Assert.Equal(400, s2); - Assert.Contains("validation", b2); + Assert.Equal("""{"error":"invalid_json"}""", b2); } } From 02d4d58d52371a12a79205c0a89f07153ecaeea1 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 04:56:33 -0500 Subject: [PATCH 5/9] fix(csharp): own routes and filter-allowlist together; report paging reads the parsed bounds Review fixes on the R-CS bundle: - The filter allowlist now emits the helper-typed rule table the routes hand to ListQueryParser, so ejecting only one of the two put two copies of the helper types in one build. Eject and eject --undo now move both together. - A report list read limit/offset twice, once in ListQueryParser and again from the raw query. It now reads the parsed bounds and keeps only the report's own checks (limit=0, the row cap), as the TypeScript report page does. - The pre-1.3.0 import warning now leads with the regenerate advice, since a project on the packaged generators sees it too. - Cli tests updated for the allowlist import and the ListQuery owned edit. - KNOWN_GAPS G10 records that the C# routes sort on more fields than the contract's sortable set; narrowing it is breaking and waits on a ruling. --- .../csharp-rest-standard-list-routes.md | 8 +++-- docs/features/own-your-codegen.md | 8 +++-- .../EjectCommandTests.cs | 28 +++++++++++++++- .../EjectCompanionsTests.cs | 8 +++-- .../EjectEndToEndTests.cs | 2 +- .../MetaObjects.Cli.Tests/EjectUndoTests.cs | 24 ++++++++++++++ .../VerifySubverbTests.cs | 3 +- server/csharp/MetaObjects.Cli/EjectCommand.cs | 33 ++++++++++++++++++- .../EjectContractTests.cs | 10 ++++-- .../pre-rc22-propname/LineTotalsRoutes.g.cs | 20 ++++------- .../Generators/KNOWN_GAPS.md | 6 ++++ .../Generators/RoutesGenerator.cs | 20 ++++------- .../HelperRuntimeReference.cs | 7 ++-- 13 files changed, 133 insertions(+), 44 deletions(-) diff --git a/changelog.d/csharp-rest-standard-list-routes.md b/changelog.d/csharp-rest-standard-list-routes.md index c50d831840..1ad457554c 100644 --- a/changelog.d/csharp-rest-standard-list-routes.md +++ b/changelog.d/csharp-rest-standard-list-routes.md @@ -9,10 +9,14 @@ path id the key cannot hold is `400 {"error": "invalid_id"}` on every item route (it was an empty 400 from ASP.NET Core's binding). The sortable set is unchanged. The routes read the new `RouteErrors` helper in `MetaObjects.AspNetCore`, and `dotnet meta eject routes` copies it with - the others. The C# generated lane now runs the whole `list-query/` sub-corpus, closing the C# + the others. The filter allowlist now carries the parser's rule table (`Rules`, `Sort`, + `FieldNames`), typed with the helpers, so `routes` and `filter-allowlist` are ejected together: + naming either owns both, and `eject --undo` gives both back. The C# generated lane now runs the whole `list-query/` sub-corpus, closing the C# routes' `KNOWN_GAPS.md` G2. Generated-output change — regenerate to pick it up; three-way merge preserves hand edits. - Upgrading: a client that sent a bare `?field=value` and read every row back now gets a 400; + Upgrading: a project that owns `routes` and not `filter-allowlist` runs + `dotnet meta eject filter-allowlist` (or `eject routes --force`), so both read the owned helpers. + A client that sent a bare `?field=value` and read every row back now gets a 400; send `filter[field][eq]=value`. A client that matched the `validation` body of a malformed JSON request should match `invalid_json`. diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index 2fe0612360..c52353a263 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -1715,8 +1715,12 @@ api contract's timestamp spelling. Each file is the packaged source with one cha `Codegen.Runtime`, matching the folder the way `codegen/generators/` matches `Codegen.Generators`. The ejected `RoutesGenerator.cs` differs from the reference in one more line, its `HelperRuntimeNamespace` constant, so its output says -`using Codegen.Runtime;`. Ejecting a generator whose output uses none of these, such as -`entity` or `filter-allowlist`, copies nothing extra. +`using Codegen.Runtime;`. The filter allowlist's output uses the helper types too (the rule +table the routes hand to the list parser), so `routes` and `filter-allowlist` are owned +together: ejecting either writes both, each with that constant changed, and +`dotnet meta eject --undo routes` gives both back. One owned and one packaged would put two +copies of the helper types in one build. Ejecting a generator whose output uses none of these, +such as `entity` or `names`, copies nothing extra. Wire it in two places: diff --git a/server/csharp/MetaObjects.Cli.Tests/EjectCommandTests.cs b/server/csharp/MetaObjects.Cli.Tests/EjectCommandTests.cs index 6a9f045acb..c40e16eaf2 100644 --- a/server/csharp/MetaObjects.Cli.Tests/EjectCommandTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/EjectCommandTests.cs @@ -390,10 +390,36 @@ public void Ejecting_routes_also_copies_the_helper_runtime_under_the_owned_names [Fact] public void Ejecting_a_generator_whose_output_uses_no_helper_runtime_copies_none() { - EjectCommand.Run(["entity", "filter-allowlist", "names"], _root, force: false); + EjectCommand.Run(["entity", "names"], _root, force: false); Assert.False(Directory.Exists(RuntimeDir)); } + // The routes hand the allowlist's FilterFieldRule table to ListQueryParser: owning one and not the + // other would put two copies of the helper types in one build, so they are ejected together. + [Theory] + [InlineData("routes", "FilterAllowlistGenerator.cs")] + [InlineData("filter-allowlist", "RoutesGenerator.cs")] + public void Ejecting_one_helper_runtime_user_ejects_the_other_with_it(string named, string partnerFile) + { + var result = EjectCommand.Run([named], _root, force: false); + Assert.Equal(0, result.ExitCode); + var partner = File.ReadAllText(Path.Combine(GeneratorsDir, partnerFile)); + Assert.Contains("HelperRuntimeNamespace = \"Codegen.Runtime\";", partner); + Assert.Contains(result.Out, l => l.Contains(partnerFile) && l.Contains("owned with them")); + } + + [Fact] + public void A_partner_already_owned_is_kept_as_it_is() + { + Assert.Equal(0, EjectCommand.Run(["filter-allowlist"], _root, force: false).ExitCode); + var allowlist = Path.Combine(GeneratorsDir, "FilterAllowlistGenerator.cs"); + File.AppendAllText(allowlist, "// mine\n"); + File.Delete(Path.Combine(GeneratorsDir, "RoutesGenerator.cs")); + + Assert.Equal(0, EjectCommand.Run(["routes"], _root, force: false).ExitCode); + Assert.EndsWith("// mine\n", File.ReadAllText(allowlist)); + } + [Fact] public void An_existing_runtime_file_is_kept_without_force_and_replaced_with_force() { diff --git a/server/csharp/MetaObjects.Cli.Tests/EjectCompanionsTests.cs b/server/csharp/MetaObjects.Cli.Tests/EjectCompanionsTests.cs index 2d8c00c4e6..ec7b11dd6f 100644 --- a/server/csharp/MetaObjects.Cli.Tests/EjectCompanionsTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/EjectCompanionsTests.cs @@ -42,14 +42,16 @@ public void Ejecting_a_generator_alone_writes_its_source_and_its_emitters_and_no .Where(f => !CodegenScaffold.Files.Contains(f) && !f.StartsWith("codegen/runtime/", StringComparison.Ordinal)) .Order(StringComparer.Ordinal) .ToList(); - var expected = EjectableGenerators.SourcePaths(entry) + // A helper-runtime user brings its partners with it (EjectCommand.RuntimePartners). + var owned = EjectCommand.RuntimePartners([name], EjectableGenerators.Entries()).Prepend(entry).ToList(); + var expected = owned.SelectMany(EjectableGenerators.SourcePaths).Distinct(StringComparer.Ordinal) .Select(EjectableGenerators.OwnedRelativePath) .Order(StringComparer.Ordinal) .ToList(); Assert.Equal(expected, written); // Each is the embedded source, rewritten the one way eject rewrites it. - foreach (var sourcePath in EjectableGenerators.SourcePaths(entry)) + foreach (var sourcePath in owned.SelectMany(EjectableGenerators.SourcePaths).Distinct(StringComparer.Ordinal)) Assert.Equal( EjectableGenerators.RewriteForEject(EjectableGenerators.ReadSourcePath(sourcePath)), File.ReadAllText(Owned(EjectableGenerators.OwnedRelativePath(sourcePath)))); @@ -91,7 +93,7 @@ public void A_later_eject_keeps_an_emitter_already_yours_and_force_replaces_it() [Fact] public void A_generator_with_no_emitters_reports_none() { - var outcome = EjectCommand.Run(["filter-allowlist"], _root, force: false); + var outcome = EjectCommand.Run(["names"], _root, force: false); Assert.DoesNotContain("emitters", string.Join("\n", outcome.Out)); } diff --git a/server/csharp/MetaObjects.Cli.Tests/EjectEndToEndTests.cs b/server/csharp/MetaObjects.Cli.Tests/EjectEndToEndTests.cs index a5e4e6b0d7..8be367c644 100644 --- a/server/csharp/MetaObjects.Cli.Tests/EjectEndToEndTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/EjectEndToEndTests.cs @@ -331,7 +331,7 @@ public void Ejected_routes_run_on_the_owned_helper_runtime_with_no_MetaObjects_r Assert.True(verifyExit == 0, $"verify --codegen failed (exit {verifyExit}):\n{verifyOutput}"); // The adopter's fix, made in their own copy. - var parserPath = Path.Combine(runtimeDir, "FilterParser.cs"); + var parserPath = Path.Combine(runtimeDir, "ListQuery.cs"); var parser = File.ReadAllText(parserPath); Assert.Contains("\"invalid_filter_field\"", parser); File.WriteAllText(parserPath, parser.Replace("\"invalid_filter_field\"", "\"invalid_filter_field_OWNED_EDIT\"")); diff --git a/server/csharp/MetaObjects.Cli.Tests/EjectUndoTests.cs b/server/csharp/MetaObjects.Cli.Tests/EjectUndoTests.cs index 5f69449ed0..3269cc74c0 100644 --- a/server/csharp/MetaObjects.Cli.Tests/EjectUndoTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/EjectUndoTests.cs @@ -20,6 +20,30 @@ private void Eject(params string[] names) => private void Edit(string rel) => File.AppendAllText(Owned(rel), "\n// my own edit\nvar mine = 1;\n"); + // The helper-runtime users (routes, filter-allowlist) are owned together, so they go back together: + // one packaged and one owned would put two copies of the helper types in one build. + [Fact] + public void Naming_one_helper_runtime_user_gives_back_its_owned_partner_too() + { + Eject("routes"); + Assert.True(File.Exists(Owned("codegen/generators/FilterAllowlistGenerator.cs"))); + + Assert.Equal(0, EjectCommand.Undo(["routes"], _root, force: false).ExitCode); + Assert.False(File.Exists(Owned("codegen/generators/RoutesGenerator.cs"))); + Assert.False(File.Exists(Owned("codegen/generators/FilterAllowlistGenerator.cs"))); + } + + [Fact] + public void With_no_names_an_identical_helper_runtime_user_stays_while_its_partner_is_edited() + { + Eject("routes"); + Edit("codegen/generators/FilterAllowlistGenerator.cs"); + + Assert.Equal(0, EjectCommand.Undo([], _root, force: false).ExitCode); + Assert.True(File.Exists(Owned("codegen/generators/RoutesGenerator.cs"))); + Assert.True(File.Exists(Owned("codegen/generators/FilterAllowlistGenerator.cs"))); + } + [Fact] public void With_no_names_removes_every_identical_copy_and_keeps_the_edited_one() { diff --git a/server/csharp/MetaObjects.Cli.Tests/VerifySubverbTests.cs b/server/csharp/MetaObjects.Cli.Tests/VerifySubverbTests.cs index 65859562c8..f3918e84d1 100644 --- a/server/csharp/MetaObjects.Cli.Tests/VerifySubverbTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/VerifySubverbTests.cs @@ -229,7 +229,8 @@ public void Codegen_routes_in_a_project_without_the_helper_package_warn_and_keep """); var gen = GenSuite.Run(MetaDir, OutDir, "Acme.Generated"); var genWarning = Assert.Single(gen.Result!.Warnings, w => w.Contains(HelperRuntime.PackageId)); - Assert.Contains("SubscriberRoutes.g.cs imports MetaObjects.AspNetCore", genWarning); + // The allowlist (FilterFieldRule, SortFieldRule) and the routes both import it. + Assert.Contains("SubscriberFilterAllowlist.g.cs and 1 other generated file(s) import MetaObjects.AspNetCore", genWarning); var r = VerifyCommand.RunSubverbs(TemplatesOpts(templates: false, codegen: true)); Assert.Equal(0, r.ExitCode); diff --git a/server/csharp/MetaObjects.Cli/EjectCommand.cs b/server/csharp/MetaObjects.Cli/EjectCommand.cs index cae34ac968..47478a0f85 100644 --- a/server/csharp/MetaObjects.Cli/EjectCommand.cs +++ b/server/csharp/MetaObjects.Cli/EjectCommand.cs @@ -152,6 +152,17 @@ internal static IReadOnlyList OlderPinWarning(string csprojPath, string : ["", warning + "."]; } + /// + /// The helper-runtime users () not in , + /// when holds one; else none. They are owned, and given back, together. + /// + internal static List RuntimePartners(IReadOnlyList names, IEnumerable entries) + { + static bool UsesRuntime(string name) => EjectableGenerators.ReadSource(name) is { } src && HelperRuntime.UsedBy(src); + if (!names.Any(UsesRuntime)) return []; + return entries.Where(e => !names.Contains(e.Name, StringComparer.Ordinal) && UsesRuntime(e.Name)).ToList(); + } + /// /// Eject into /codegen/. Every name /// is validated before anything is written. Returns exit 2 (usage) for no names or @@ -175,6 +186,15 @@ public static Outcome Run(IReadOnlyList names, string root, bool force) var generatorsDir = Path.Combine(root, "codegen", "generators"); + // The generators whose output uses the helper runtime share its types (the routes hand the + // allowlist's FilterFieldRule table to ListQueryParser), so they are owned together: one owned + // and one packaged would put two copies of those types in one build. A partner already owned + // stays as it is. + var partners = RuntimePartners(names, known.Values) + .Where(e => !File.Exists(Path.Combine(generatorsDir, e.SourceFileName!))) + .Select(e => e.Name).ToList(); + names = [.. names, .. partners]; + // All names checked BEFORE any write — see the ADR-0034 Amendment 3 doc comment // above. A partial eject (half copied, one refused) is worse than refusing the // whole call: the adopter cannot tell what state the repo is in. @@ -197,7 +217,10 @@ public static Outcome Run(IReadOnlyList names, string root, bool force) var rewritten = EjectableGenerators.RewriteForEject(EjectableGenerators.ReadSource(name)!); var dest = Path.Combine(generatorsDir, file); var status = WriteOwnedCopy(dest, rewritten, File.Exists(dest) ? "replaced" : "created"); - outLines.Add($"ejected \"{name}\" -> codegen/generators/{file} [{status}]"); + var why = partners.Contains(name) + ? " — its output shares the helper types with the generator(s) named, so it is owned with them" + : ""; + outLines.Add($"ejected \"{name}\" -> codegen/generators/{file} [{status}]{why}"); } outLines.AddRange(EjectCompanions(root, names.Select(n => known[n]).ToList(), force)); var runtimeUsers = names.Where(n => HelperRuntime.UsedBy(EjectableGenerators.ReadSource(n)!)).ToList(); @@ -257,6 +280,11 @@ public static Outcome Undo(IReadOnlyList names, string root, bool force) if (names.Count == 0) { targets = OwnedCopy.IdenticalCopies(root).ToList(); + // An identical helper-runtime user stays while an edited partner is still owned (see Run). + var editedRuntimeUser = all.Any(e => HelperRuntime.UsedBy(EjectableGenerators.ReadSource(e.Name)!) + && OwnedCopy.Status(root, e) is not null && !targets.Contains(e)); + if (editedRuntimeUser) + targets.RemoveAll(e => HelperRuntime.UsedBy(EjectableGenerators.ReadSource(e.Name)!)); if (targets.Count == 0) { var owned = all.Where(e => OwnedCopy.Status(root, e) is not null).ToList(); @@ -275,6 +303,9 @@ public static Outcome Undo(IReadOnlyList names, string root, bool force) $"unknown or non-ejectable generator(s): {string.Join(", ", unknown)}. " + $"Nothing was removed. Ejectable: {string.Join(", ", EjectableNames())}."); targets = names.Distinct(StringComparer.Ordinal).Select(n => known[n]).ToList(); + // A helper-runtime user goes back to the package with its owned partners (see Run). + targets.AddRange(RuntimePartners(targets.Select(t => t.Name).ToList(), all) + .Where(e => OwnedCopy.Status(root, e) is not null)); var notOwned = targets.Where(e => OwnedCopy.Status(root, e) is null).Select(e => e.Name).ToList(); if (notOwned.Count > 0) return Outcome.Usage( diff --git a/server/csharp/MetaObjects.Codegen.Tests/EjectContractTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EjectContractTests.cs index 53ebac321a..7a90c5c405 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EjectContractTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EjectContractTests.cs @@ -251,9 +251,13 @@ MetaRoot Directory(params string[] segments) ]; } - private static IGenerator Instantiate(Assembly owned, string? templateRoot) + private static IGenerator Instantiate(Assembly owned, string stableName, string? templateRoot) { - var type = owned.GetTypes().Single(t => typeof(IGenerator).IsAssignableFrom(t) && !t.IsAbstract); + // An eject can write more than one generator (the helper-runtime users are owned together), + // so the type is the one in the named generator's own file. + var className = Path.GetFileNameWithoutExtension( + EjectableGenerators.Entries().Single(e => e.Name == stableName).SourceFileName!); + var type = owned.GetTypes().Single(t => typeof(IGenerator).IsAssignableFrom(t) && !t.IsAbstract && t.Name == className); // The one generator constructed with an argument takes the template root. var takesTemplateRoot = type.GetConstructors().Any(c => c.GetParameters() is [{ ParameterType: var p }] && p == typeof(string)); @@ -292,7 +296,7 @@ List Run(IGenerator generator) => var packaged = Run(SharedModelTestSupport.Configure( GeneratorRegistry.Get(stableName)!.Factory(new GeneratorBuildContext(corpus.TemplateRoot)))); - var owned = Run(SharedModelTestSupport.Configure(Instantiate(copy.Assembly, corpus.TemplateRoot))); + var owned = Run(SharedModelTestSupport.Configure(Instantiate(copy.Assembly, stableName, corpus.TemplateRoot))); emitted += packaged.Count; Assert.Equal(packaged.Select(f => System.IO.Path.GetFileName(f.Path)), owned.Select(f => System.IO.Path.GetFileName(f.Path))); for (var i = 0; i < packaged.Count; i++) diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs index 1423cf044e..a122fa9d56 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs @@ -48,20 +48,12 @@ public static IEndpointRouteBuilder MapLineTotalsRoutes(this IEndpointRouteBuild // Pagination (report): every row up to the cap, refused above it. const int maxRows = 10000; - long? limit = null; - long offset = 0; - if (qs.TryGetValue("limit", out var limitRaw)) - { - if (!long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var parsedLimit) || parsedLimit < 1) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limitRaw.ToString(), expected = $"an integer from 1 to {maxRows}" }); - if (parsedLimit > maxRows) - return Results.BadRequest(new { error = "report_too_large", maxRows }); - limit = parsedLimit; - } - if (qs.TryGetValue("offset", out var offsetRaw) - && (!long.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out offset) || offset < 0)) - return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offsetRaw.ToString(), expected = "a non-negative integer (0 or more)" }); - if (offset > 0) q = q.Skip((int)System.Math.Min(offset, int.MaxValue)); + var limit = listQuery.Limit; + if (limit == 0) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = "0", expected = $"an integer from 1 to {maxRows}" }); + if (limit > maxRows) + return Results.BadRequest(new { error = "report_too_large", maxRows }); + if (listQuery.Offset is { } offset && offset > 0) q = q.Skip((int)System.Math.Min(offset, int.MaxValue)); q = q.Take((int)(limit ?? maxRows + 1L)); var rows = await q.ToListAsync(); diff --git a/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md b/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md index 014cf51b60..7692cfc111 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md +++ b/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md @@ -20,6 +20,12 @@ Update when a gap closes or a new one surfaces. ## Gaps +### G10 — The list routes sort on more fields than the contract's sortable set + +**Contract.** `sort=` names a field in the entity's sort allowlist: `@sortable: true`, or no `@sortable` and `@filterable: true` ([`api-contract.md` "Sort + pagination"](../../../../docs/features/api-contract.md)). The TypeScript routes serve exactly that set, and the C# `FilterAllowlist.Sort` table lists it (the `list-query-conformance` corpus reads it). + +**Today.** The generated C# routes sort on every scalar, non-credential field (`SortRules` in `RoutesGenerator.cs`), whatever `@sortable` and `@filterable` say: a request TypeScript refuses with `invalid_sort` is served here, and `invalid_sort`'s `allowed` lists the wider set. Narrowing it is a breaking change for any C# client that sorts on an undeclared field (a grid column, say), so it waits on a ruling rather than riding in a REST-standard change. + ### G3 — Multi-field sort **Contract.** Single sort key only in the default contract (`sort=:asc|desc`). Multi-field sort is NOT in scope for the contract today. diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index ce9c9381ab..dba9b15c8e 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -179,20 +179,14 @@ protected virtual void WriteReportPaging(CsWriter w, int? exportMaxRows) w.Line("var maxRows = format is null ? listMaxRows : exportMaxRows;"); tooLarge = "format is null ? " + tooLarge + " : ReportExportHttp.TooLarge(maxRows)"; } - w.Line("long? limit = null;"); - w.Line("long offset = 0;"); - w.Line("if (qs.TryGetValue(\"limit\", out var limitRaw))"); - w.Open("{"); - w.Line("if (!long.TryParse(limitRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var parsedLimit) || parsedLimit < 1)"); - using (w.Hanging()) w.Line("return Results.BadRequest(new { error = \"pagination.invalid_value\", param = \"limit\", value = limitRaw.ToString(), expected = $\"an integer from 1 to {maxRows}\" });"); - w.Line("if (parsedLimit > maxRows)"); + // ListQueryParser has refused a bound that is not a non-negative integer; a report also refuses + // limit=0 (a bad bound, not an empty answer) and a limit above the cap. + w.Line("var limit = listQuery.Limit;"); + w.Line("if (limit == 0)"); + using (w.Hanging()) w.Line("return Results.BadRequest(new { error = \"pagination.invalid_value\", param = \"limit\", value = \"0\", expected = $\"an integer from 1 to {maxRows}\" });"); + w.Line("if (limit > maxRows)"); using (w.Hanging()) w.Line($"return {tooLarge};"); - w.Line("limit = parsedLimit;"); - w.Close("}"); - w.Line("if (qs.TryGetValue(\"offset\", out var offsetRaw)"); - using (w.Hanging()) w.Line("&& (!long.TryParse(offsetRaw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out offset) || offset < 0))"); - using (w.Hanging()) w.Line("return Results.BadRequest(new { error = \"pagination.invalid_value\", param = \"offset\", value = offsetRaw.ToString(), expected = \"a non-negative integer (0 or more)\" });"); - w.Line("if (offset > 0) q = q.Skip((int)System.Math.Min(offset, int.MaxValue));"); + w.Line("if (listQuery.Offset is { } offset && offset > 0) q = q.Skip((int)System.Math.Min(offset, int.MaxValue));"); w.Line("q = q.Take((int)(limit ?? maxRows + 1L));"); w.Blank(); w.Line("var rows = await q.ToListAsync();"); diff --git a/server/csharp/MetaObjects.Codegen/HelperRuntimeReference.cs b/server/csharp/MetaObjects.Codegen/HelperRuntimeReference.cs index 2949131342..8b50bb5653 100644 --- a/server/csharp/MetaObjects.Codegen/HelperRuntimeReference.cs +++ b/server/csharp/MetaObjects.Codegen/HelperRuntimeReference.cs @@ -55,9 +55,10 @@ public static bool ImportsFormer(string content) => var example = sorted.Count > 1 ? $"{sorted[0]} and {sorted.Count - 1} other generated file(s) import" : $"{sorted[0]} imports"; return $"{example} {HelperRuntime.FormerNamespace} for the route helpers (FilterParser, EfCoreFilterDispatch, ...), which " + $"since 1.3.0 are in the {HelperRuntime.PackageId} package, namespace {HelperRuntime.PackagedNamespace}, so it will not compile. " + - $"The generator that wrote it is a copy owned from before 1.3.0: set its HelperRuntimeNamespace constant to " + - $"\"{HelperRuntime.PackagedNamespace}\" and reference the {HelperRuntime.PackageId} package, or run " + - $"`dotnet meta eject routes --force` to own the current generator and the helpers with it."; + $"Reference the {HelperRuntime.PackageId} package and run `dotnet meta gen`; the packaged generators write the " + + $"new import. If the generator that wrote it is a copy you own from before 1.3.0, also set its " + + $"HelperRuntimeNamespace constant to \"{HelperRuntime.PackagedNamespace}\", or run " + + $"`dotnet meta eject routes --force` to own the current generators and the helpers with them."; } /// From 107e9cd364b763d89c3e4d481a8ea2cb4833c4ff Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 04:58:25 -0500 Subject: [PATCH 6/9] refactor(csharp): one UsesRuntime check in eject; one offset-skip emit for list and report pages --- server/csharp/MetaObjects.Cli/EjectCommand.cs | 15 +++++++++------ .../pre-rc22-propname/LineTotalsRoutes.g.cs | 3 ++- .../Generators/RoutesGenerator.cs | 12 +++++++++--- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/server/csharp/MetaObjects.Cli/EjectCommand.cs b/server/csharp/MetaObjects.Cli/EjectCommand.cs index 47478a0f85..3cab6bb8d7 100644 --- a/server/csharp/MetaObjects.Cli/EjectCommand.cs +++ b/server/csharp/MetaObjects.Cli/EjectCommand.cs @@ -152,13 +152,16 @@ internal static IReadOnlyList OlderPinWarning(string csprojPath, string : ["", warning + "."]; } + /// True when generator 's output uses the helper runtime. + private static bool UsesRuntime(string name) => + EjectableGenerators.ReadSource(name) is { } src && HelperRuntime.UsedBy(src); + /// /// The helper-runtime users () not in , /// when holds one; else none. They are owned, and given back, together. /// internal static List RuntimePartners(IReadOnlyList names, IEnumerable entries) { - static bool UsesRuntime(string name) => EjectableGenerators.ReadSource(name) is { } src && HelperRuntime.UsedBy(src); if (!names.Any(UsesRuntime)) return []; return entries.Where(e => !names.Contains(e.Name, StringComparer.Ordinal) && UsesRuntime(e.Name)).ToList(); } @@ -223,7 +226,7 @@ public static Outcome Run(IReadOnlyList names, string root, bool force) outLines.Add($"ejected \"{name}\" -> codegen/generators/{file} [{status}]{why}"); } outLines.AddRange(EjectCompanions(root, names.Select(n => known[n]).ToList(), force)); - var runtimeUsers = names.Where(n => HelperRuntime.UsedBy(EjectableGenerators.ReadSource(n)!)).ToList(); + var runtimeUsers = names.Where(UsesRuntime).ToList(); if (runtimeUsers.Count > 0) outLines.AddRange(EjectRuntime(root, runtimeUsers, force)); @@ -281,10 +284,10 @@ public static Outcome Undo(IReadOnlyList names, string root, bool force) { targets = OwnedCopy.IdenticalCopies(root).ToList(); // An identical helper-runtime user stays while an edited partner is still owned (see Run). - var editedRuntimeUser = all.Any(e => HelperRuntime.UsedBy(EjectableGenerators.ReadSource(e.Name)!) + var editedRuntimeUser = all.Any(e => UsesRuntime(e.Name) && OwnedCopy.Status(root, e) is not null && !targets.Contains(e)); if (editedRuntimeUser) - targets.RemoveAll(e => HelperRuntime.UsedBy(EjectableGenerators.ReadSource(e.Name)!)); + targets.RemoveAll(e => UsesRuntime(e.Name)); if (targets.Count == 0) { var owned = all.Where(e => OwnedCopy.Status(root, e) is not null).ToList(); @@ -347,12 +350,12 @@ public static Outcome Undo(IReadOnlyList names, string root, bool force) } } - var runtimeUsers = targets.Where(t => HelperRuntime.UsedBy(EjectableGenerators.ReadSource(t.Name)!)).ToList(); + var runtimeUsers = targets.Where(t => UsesRuntime(t.Name)).ToList(); var runtimeDir = Path.Combine(root, HelperRuntime.OwnedDirectory.Replace('/', Path.DirectorySeparatorChar)); var runtimeRemoved = false; if (runtimeUsers.Count > 0 && Directory.Exists(runtimeDir)) { - if (remaining.FirstOrDefault(e => HelperRuntime.UsedBy(EjectableGenerators.ReadSource(e.Name)!)) is { } user) + if (remaining.FirstOrDefault(e => UsesRuntime(e.Name)) is { } user) lines.Add($" kept {HelperRuntime.OwnedDirectory}/ — \"{user.Name}\" is still owned and uses it"); else { diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs index a122fa9d56..58c0d48e92 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs @@ -53,7 +53,8 @@ public static IEndpointRouteBuilder MapLineTotalsRoutes(this IEndpointRouteBuild return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = "0", expected = $"an integer from 1 to {maxRows}" }); if (limit > maxRows) return Results.BadRequest(new { error = "report_too_large", maxRows }); - if (listQuery.Offset is { } offset && offset > 0) q = q.Skip((int)System.Math.Min(offset, int.MaxValue)); + if (listQuery.Offset is { } __offset && __offset > 0) + q = q.Skip((int)System.Math.Min(__offset, int.MaxValue)); q = q.Take((int)(limit ?? maxRows + 1L)); var rows = await q.ToListAsync(); diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index dba9b15c8e..48f2d06644 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -186,7 +186,7 @@ protected virtual void WriteReportPaging(CsWriter w, int? exportMaxRows) using (w.Hanging()) w.Line("return Results.BadRequest(new { error = \"pagination.invalid_value\", param = \"limit\", value = \"0\", expected = $\"an integer from 1 to {maxRows}\" });"); w.Line("if (limit > maxRows)"); using (w.Hanging()) w.Line($"return {tooLarge};"); - w.Line("if (listQuery.Offset is { } offset && offset > 0) q = q.Skip((int)System.Math.Min(offset, int.MaxValue));"); + WriteSkip(w); w.Line("q = q.Take((int)(limit ?? maxRows + 1L));"); w.Blank(); w.Line("var rows = await q.ToListAsync();"); @@ -1188,11 +1188,17 @@ protected virtual void WriteReadId(CsWriter w, string pkType) => // `api.pagination`'s defaultLimit, or ApiSettings.DefaultPageLimit (50, as in every port) when the project // sets no block; with the block, a limit above maxLimit is 400 limit_too_large, and without it there is no // maximum. `limit=0` is a page of zero rows, as every other port serves it, not "no limit". - protected virtual void WriteListPage(CsWriter w, ApiPagination? page) + // The parsed ?offset, skipped (an offset is at most 2^53 - 1; EF's Skip takes an int). + private static void WriteSkip(CsWriter w) { - w.Line("// Pagination: ?offset=N first (skip), then ?limit=N (take)."); w.Line("if (listQuery.Offset is { } __offset && __offset > 0)"); using (w.Hanging()) w.Line("q = q.Skip((int)System.Math.Min(__offset, int.MaxValue));"); + } + + protected virtual void WriteListPage(CsWriter w, ApiPagination? page) + { + w.Line("// Pagination: ?offset=N first (skip), then ?limit=N (take)."); + WriteSkip(w); if (page is not null) w.Line("// api.pagination: no limit takes defaultLimit; a limit above maxLimit is refused."); else From 3296c9baac69f3c3d0d27f2b020e3947c64a8f3c Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 05:15:01 -0500 Subject: [PATCH 7/9] no-mistakes(review): Deprecate flat filter path, repoint tests --- .../csharp-rest-standard-list-routes.md | 4 ++ .../EfCoreFilterDispatch.cs | 20 +++------ .../FilterParseResult.cs | 1 + .../MetaObjects.AspNetCore/FilterParser.cs | 1 + .../MetaObjects.AspNetCore/FilterPredicate.cs | 1 + .../DecimalWireTests.cs | 22 ++++++---- .../DurationWireTests.cs | 22 ++++++---- .../PackageKeyedOutputTests.cs | 2 +- .../PackageNamespaceTests.cs | 2 +- .../PropertyNamingEmitSitesTests.cs | 41 +++++++++++++++++-- .../ServerOwnedCreateInputTests.cs | 2 +- .../TphM2mRoutesTests.cs | 2 +- 12 files changed, 81 insertions(+), 39 deletions(-) diff --git a/changelog.d/csharp-rest-standard-list-routes.md b/changelog.d/csharp-rest-standard-list-routes.md index 1ad457554c..e2b920447f 100644 --- a/changelog.d/csharp-rest-standard-list-routes.md +++ b/changelog.d/csharp-rest-standard-list-routes.md @@ -20,3 +20,7 @@ A client that sent a bare `?field=value` and read every row back now gets a 400; send `filter[field][eq]=value`. A client that matched the `validation` body of a malformed JSON request should match `invalid_json`. + The flat-filter path (`FilterParser`, `FilterPredicate`, `FilterParseResult`, + `EfCoreFilterDispatch.ApplyFilter` and `Validate(FilterParseResult)`) is now `[Obsolete]` and will be + removed in 2.0; a hand-written endpoint moves to `ListQueryParser.Parse`, `EfCoreFilterDispatch.Apply` + and `Validate(ListQuery)`. diff --git a/server/csharp/MetaObjects.AspNetCore/EfCoreFilterDispatch.cs b/server/csharp/MetaObjects.AspNetCore/EfCoreFilterDispatch.cs index 9e0cc8ab0c..1492a53770 100644 --- a/server/csharp/MetaObjects.AspNetCore/EfCoreFilterDispatch.cs +++ b/server/csharp/MetaObjects.AspNetCore/EfCoreFilterDispatch.cs @@ -36,17 +36,16 @@ namespace MetaObjects.AspNetCore; /// public static class EfCoreFilterDispatch { + [Obsolete("Use EfCoreFilterDispatch.Apply with the ListQuery from ListQueryParser.Parse. Will be removed in 2.0.")] public static IQueryable ApplyFilter( IQueryable source, IReadOnlyList predicates, IReadOnlyDictionary? propertyByField = null) where T : class { if (predicates is null || predicates.Count == 0) return source; + var x = Expression.Parameter(typeof(T), "x"); foreach (var p in predicates) - { - var lambda = BuildLambda(p, propertyByField); - source = source.Where(lambda); - } + source = source.Where(Expression.Lambda>(LeafBody(x, typeof(T), p.Field, p.Op, p.Value, propertyByField), x)); return source; } @@ -60,6 +59,7 @@ public static IQueryable ApplyFilter( /// duration operand with the duration wire grammar (). /// A failed parse result is returned unchanged. /// + [Obsolete("Use EfCoreFilterDispatch.Validate(ListQuery) with the ListQuery from ListQueryParser.Parse. Will be removed in 2.0.")] public static FilterParseResult Validate(FilterParseResult parsed, IReadOnlyDictionary? propertyByField = null) { if (parsed.ErrorEnvelope is not null) return parsed; @@ -67,7 +67,7 @@ public static FilterParseResult Validate(FilterParseResult parsed, IReadOnlyD { if (p.Op is "isNull" or "like") continue; var prop = ResolveProperty(typeof(T), p.Field, propertyByField); - if (prop is null) continue; // the allowlist gate upstream guarantees a match; BuildLambda reports a miss + if (prop is null) continue; // the allowlist gate upstream guarantees a match; LeafBody reports a miss var memberType = prop.PropertyType; var underlying = Nullable.GetUnderlyingType(memberType) ?? memberType; try @@ -85,16 +85,6 @@ public static FilterParseResult Validate(FilterParseResult parsed, IReadOnlyD return parsed; } - /// - /// Build an Expression<Func<T, bool>> for a single predicate - /// against the resolved CLR property of . - /// - private static Expression> BuildLambda(FilterPredicate p, IReadOnlyDictionary? propertyByField) - { - var x = Expression.Parameter(typeof(T), "x"); - return Expression.Lambda>(LeafBody(x, typeof(T), p.Field, p.Op, p.Value, propertyByField), x); - } - /// /// Apply a parsed list query's filter tree and search () to /// : and/or groups become AndAlso/OrElse in one diff --git a/server/csharp/MetaObjects.AspNetCore/FilterParseResult.cs b/server/csharp/MetaObjects.AspNetCore/FilterParseResult.cs index 3dcc552792..b625b3a981 100644 --- a/server/csharp/MetaObjects.AspNetCore/FilterParseResult.cs +++ b/server/csharp/MetaObjects.AspNetCore/FilterParseResult.cs @@ -25,6 +25,7 @@ namespace MetaObjects.AspNetCore; /// invalid_filter_value) — the caller must not have to guess which of /// several filters was rejected. /// +[System.Obsolete("Use ListQueryResult from ListQueryParser.Parse. Will be removed in 2.0.")] public sealed record FilterParseResult( System.Collections.Generic.IReadOnlyList Predicates, string? ErrorEnvelope, diff --git a/server/csharp/MetaObjects.AspNetCore/FilterParser.cs b/server/csharp/MetaObjects.AspNetCore/FilterParser.cs index 4bc26e3569..66d51b88a5 100644 --- a/server/csharp/MetaObjects.AspNetCore/FilterParser.cs +++ b/server/csharp/MetaObjects.AspNetCore/FilterParser.cs @@ -20,6 +20,7 @@ namespace MetaObjects.AspNetCore; /// filter[<field>]=<value> sugar form for eq) against /// a per-entity allowlist. /// +[System.Obsolete("Use ListQueryParser.Parse, which reads the whole REST-standard list query. Will be removed in 2.0.")] public static class FilterParser { /// Sentinel returned by on a parse failure. diff --git a/server/csharp/MetaObjects.AspNetCore/FilterPredicate.cs b/server/csharp/MetaObjects.AspNetCore/FilterPredicate.cs index a9a45eefe6..663f05d0c7 100644 --- a/server/csharp/MetaObjects.AspNetCore/FilterPredicate.cs +++ b/server/csharp/MetaObjects.AspNetCore/FilterPredicate.cs @@ -20,4 +20,5 @@ namespace MetaObjects.AspNetCore; /// in, a for isNull. The dispatcher is /// responsible for any further conversion to the column type. /// +[System.Obsolete("Use the FilterNode tree from ListQueryParser.Parse. Will be removed in 2.0.")] public sealed record FilterPredicate(string Field, string Op, object? Value); diff --git a/server/csharp/MetaObjects.Codegen.Tests/DecimalWireTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DecimalWireTests.cs index afc4eabc28..581cccf375 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/DecimalWireTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/DecimalWireTests.cs @@ -152,8 +152,13 @@ public void An_array_of_decimals_crosses_as_canonical_strings() public sealed class Row { public decimal Amount { get; set; } public int Count { get; set; } } - private static FilterParseResult Check(string field, string op, object value) => - EfCoreFilterDispatch.Validate(FilterParseResult.Ok([new FilterPredicate(field, op, value)])); + private static ListQueryError? Check(string field, string op, object value) => + EfCoreFilterDispatch.Validate(new ListQuery(new FilterLeaf(field, op, value), null, null, null, null)); + + private static List Many(params string[] items) => items.Cast().ToList(); + + private static string? FieldOf(ListQueryError error) => + (string?)error.Details.Single(d => d.Key == "field").Value; [Theory] [InlineData("amount", "eq", "abc")] @@ -166,17 +171,18 @@ private static FilterParseResult Check(string field, string op, object value) => public void A_malformed_operand_is_invalid_filter_value_naming_the_field(string field, string op, string operand) { var r = Check(field, op, operand); - Assert.Equal("invalid_filter_value", r.ErrorEnvelope); - Assert.Equal(field, r.Field); + Assert.NotNull(r); + Assert.Equal("invalid_filter_value", r!.Error); + Assert.Equal(field, FieldOf(r)); } [Fact] public void A_good_operand_passes_and_an_in_list_is_checked_element_wise() { - Assert.Null(Check("amount", "eq", "12345678901234567.89").ErrorEnvelope); - Assert.Null(Check("amount", "gte", "1e-7").ErrorEnvelope); - Assert.Null(Check("amount", "in", new List { "1", "2.50" }).ErrorEnvelope); - Assert.Equal("invalid_filter_value", Check("amount", "in", new List { "1", "x" }).ErrorEnvelope); + Assert.Null(Check("amount", "eq", "12345678901234567.89")); + Assert.Null(Check("amount", "gte", "1e-7")); + Assert.Null(Check("amount", "in", Many("1", "2.50"))); + Assert.Equal("invalid_filter_value", Check("amount", "in", Many("1", "x"))?.Error); } [Fact] diff --git a/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs index 8a4ee58f01..fec49233b1 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs @@ -168,8 +168,13 @@ public void A_span_past_a_timespan_is_refused_never_wrapped() public sealed class Row { public TimeSpan Wait { get; set; } public TimeSpan? Grace { get; set; } } - private static FilterParseResult Check(string field, string op, object value) => - EfCoreFilterDispatch.Validate(FilterParseResult.Ok([new FilterPredicate(field, op, value)])); + private static ListQueryError? Check(string field, string op, object value) => + EfCoreFilterDispatch.Validate(new ListQuery(new FilterLeaf(field, op, value), null, null, null, null)); + + private static List Many(params string[] items) => items.Cast().ToList(); + + private static string? FieldOf(ListQueryError error) => + (string?)error.Details.Single(d => d.Key == "field").Value; [Theory] [InlineData("wait", "eq", "P1M")] @@ -179,17 +184,18 @@ private static FilterParseResult Check(string field, string op, object value) => public void A_malformed_duration_operand_is_invalid_filter_value_naming_the_field(string field, string op, string operand) { var r = Check(field, op, operand); - Assert.Equal("invalid_filter_value", r.ErrorEnvelope); - Assert.Equal(field, r.Field); + Assert.NotNull(r); + Assert.Equal("invalid_filter_value", r!.Error); + Assert.Equal(field, FieldOf(r)); } [Fact] public void A_good_duration_operand_passes_and_an_in_list_is_checked_element_wise() { - Assert.Null(Check("wait", "eq", "PT90M").ErrorEnvelope); - Assert.Null(Check("grace", "ne", "-P1DT0.5S").ErrorEnvelope); - Assert.Null(Check("wait", "in", new List { "PT1H", "P2D", "P1W" }).ErrorEnvelope); - Assert.Equal("invalid_filter_value", Check("wait", "in", new List { "PT1H", "P1Y" }).ErrorEnvelope); + Assert.Null(Check("wait", "eq", "PT90M")); + Assert.Null(Check("grace", "ne", "-P1DT0.5S")); + Assert.Null(Check("wait", "in", Many("PT1H", "P2D", "P1W"))); + Assert.Equal("invalid_filter_value", Check("wait", "in", Many("PT1H", "P1Y"))?.Error); } [Fact] diff --git a/server/csharp/MetaObjects.Codegen.Tests/PackageKeyedOutputTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PackageKeyedOutputTests.cs index 15fe409ba4..804c73d1e8 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PackageKeyedOutputTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PackageKeyedOutputTests.cs @@ -222,7 +222,7 @@ private static List CompileErrors(IEnumerable<(string Path, string Conte var refs = HelperRuntimeTests.ReferencesWithoutMetaObjects(); refs.Add(MetadataReference.CreateFromFile(typeof(MetaObjects.Meta.MetaObject).Assembly.Location)); refs.Add(MetadataReference.CreateFromFile(typeof(MetaObjects.Codegen.Runtime.ExtractObject).Assembly.Location)); - refs.Add(MetadataReference.CreateFromFile(typeof(MetaObjects.AspNetCore.FilterParser).Assembly.Location)); + refs.Add(MetadataReference.CreateFromFile(typeof(MetaObjects.AspNetCore.ListQueryParser).Assembly.Location)); var comp = CSharpCompilation.Create( "package_keyed_" + Guid.NewGuid().ToString("N"), trees, refs, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); diff --git a/server/csharp/MetaObjects.Codegen.Tests/PackageNamespaceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PackageNamespaceTests.cs index 43bd0d3dfa..26b174bb78 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PackageNamespaceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PackageNamespaceTests.cs @@ -184,7 +184,7 @@ internal static List CompileErrors(IEnumerable files) paths.Add(typeof(Microsoft.EntityFrameworkCore.DbContext).Assembly.Location); paths.Add(typeof(Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions).Assembly.Location); paths.Add(typeof(Uri).Assembly.Location); - paths.Add(typeof(MetaObjects.AspNetCore.FilterParser).Assembly.Location); + paths.Add(typeof(MetaObjects.AspNetCore.ListQueryParser).Assembly.Location); paths.Add(typeof(MetaObjects.Render.Extract.ExtractSchema).Assembly.Location); paths.Add(typeof(MetaObject).Assembly.Location); var comp = CSharpCompilation.Create("pkgns_" + Guid.NewGuid().ToString("N"), diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs index be571b135a..a264feb418 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs @@ -229,7 +229,7 @@ private static List CompileAll(IEnumerable files) paths.Add(typeof(Microsoft.EntityFrameworkCore.ModelBuilder).Assembly.Location); paths.Add(typeof(Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions).Assembly.Location); paths.Add(typeof(Microsoft.EntityFrameworkCore.PrimaryKeyAttribute).Assembly.Location); - paths.Add(typeof(MetaObjects.AspNetCore.FilterParser).Assembly.Location); + paths.Add(typeof(MetaObjects.AspNetCore.ListQueryParser).Assembly.Location); var refs = paths.Where(File.Exists).Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)).ToList(); var comp = CSharpCompilation.Create("all_sites_" + Guid.NewGuid().ToString("N"), trees, refs, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); @@ -362,20 +362,53 @@ private sealed class FilterRow public long OwnerKey { get; set; } } + private static MetaObjects.AspNetCore.ListQuery OwnerQuery(string operand) => + new(new MetaObjects.AspNetCore.FilterLeaf("ownerRef", "eq", operand), null, null, null, null); + + private static readonly IReadOnlyDictionary OwnerRules = + new Dictionary + { + ["ownerRef"] = new(MetaObjects.AspNetCore.FilterValueKind.Number, "eq") { Integer = true }, + }; + [Fact] public void The_filter_dispatch_finds_a_property_the_resolver_renamed_beyond_case() { - var predicates = new[] { new MetaObjects.AspNetCore.FilterPredicate("ownerRef", "eq", "5") }; var map = new Dictionary { ["ownerRef"] = "OwnerKey" }; var rows = new[] { new FilterRow { OwnerKey = 5 }, new FilterRow { OwnerKey = 6 } }.AsQueryable(); // With the map the field resolves to its property; without it the lookup misses (the 500 this guards). - var filtered = MetaObjects.AspNetCore.EfCoreFilterDispatch.ApplyFilter(rows, predicates, map).ToList(); + var filtered = MetaObjects.AspNetCore.EfCoreFilterDispatch.Apply(rows, OwnerQuery("5"), OwnerRules, map).ToList(); + Assert.Equal(5, Assert.Single(filtered).OwnerKey); + Assert.Throws(() => MetaObjects.AspNetCore.EfCoreFilterDispatch.Apply(rows, OwnerQuery("5"), OwnerRules)); + + var bad = MetaObjects.AspNetCore.EfCoreFilterDispatch.Validate(OwnerQuery("not-a-number"), map); + Assert.Equal("invalid_filter_value", bad?.Error); + } + +#pragma warning disable CS0618 // the flat-filter path is obsolete (removed in 2.0) but must keep working until then + [Fact] + public void The_obsolete_flat_filter_path_still_parses_validates_and_filters() + { + var map = new Dictionary { ["ownerRef"] = "OwnerKey" }; + var rows = new[] { new FilterRow { OwnerKey = 5 }, new FilterRow { OwnerKey = 6 } }.AsQueryable(); + var query = new Microsoft.AspNetCore.Http.QueryCollection(new Dictionary + { + ["filter[ownerRef][eq]"] = "5", + }); + + var parsed = MetaObjects.AspNetCore.FilterParser.Parse( + query, + new HashSet { "ownerRef" }, + new Dictionary> { ["ownerRef"] = new() { "eq" } }); + var validated = MetaObjects.AspNetCore.EfCoreFilterDispatch.Validate(parsed, map); + Assert.Null(validated.ErrorEnvelope); + var filtered = MetaObjects.AspNetCore.EfCoreFilterDispatch.ApplyFilter(rows, validated.Predicates, map).ToList(); Assert.Equal(5, Assert.Single(filtered).OwnerKey); - Assert.Throws(() => MetaObjects.AspNetCore.EfCoreFilterDispatch.ApplyFilter(rows, predicates)); var bad = MetaObjects.AspNetCore.EfCoreFilterDispatch.Validate( MetaObjects.AspNetCore.FilterParseResult.Ok([new MetaObjects.AspNetCore.FilterPredicate("ownerRef", "eq", "not-a-number")]), map); Assert.Equal("invalid_filter_value", bad.ErrorEnvelope); } +#pragma warning restore CS0618 } diff --git a/server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs index c95ae8240b..5e372d7009 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs @@ -220,7 +220,7 @@ public void A_readOnly_key_and_readOnly_discriminator_get_no_reset_and_the_model paths.Add(typeof(Microsoft.EntityFrameworkCore.ModelBuilder).Assembly.Location); paths.Add(typeof(Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions).Assembly.Location); paths.Add(typeof(Microsoft.EntityFrameworkCore.PrimaryKeyAttribute).Assembly.Location); - paths.Add(typeof(MetaObjects.AspNetCore.FilterParser).Assembly.Location); + paths.Add(typeof(MetaObjects.AspNetCore.ListQueryParser).Assembly.Location); var refs = paths.Where(File.Exists) .Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)).ToList(); var comp = CSharpCompilation.Create( diff --git a/server/csharp/MetaObjects.Codegen.Tests/TphM2mRoutesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/TphM2mRoutesTests.cs index 730df13933..9b899fb6b3 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/TphM2mRoutesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/TphM2mRoutesTests.cs @@ -343,7 +343,7 @@ public void Full_model_compiles_against_ef_core_8_and_aspnetcore() // The routes file's `using MetaObjects.AspNetCore;` (FilterParser, // EfCoreFilterDispatch) lives in this same assembly — a project reference, so it // is not on TRUSTED_PLATFORM_ASSEMBLIES. - paths.Add(typeof(MetaObjects.AspNetCore.FilterParser).Assembly.Location); + paths.Add(typeof(MetaObjects.AspNetCore.ListQueryParser).Assembly.Location); var refs = paths.Where(File.Exists) .Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)).ToList(); From ba1097b480043eceeea9407845ca1764ff9d6bcf Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 05:15:43 -0500 Subject: [PATCH 8/9] no-mistakes(review): apply reviewer inline fixes --- docs/features/api-contract.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/features/api-contract.md b/docs/features/api-contract.md index 19f42c84f5..24961f8d40 100644 --- a/docs/features/api-contract.md +++ b/docs/features/api-contract.md @@ -223,7 +223,7 @@ 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` list parser), Python (`MAX_IN_LIST`), -Java (`FilterParser.MAX_IN_LIST`), C# (`FilterParser.MaxInList`) and Kotlin (a generated +Java (`FilterParser.MAX_IN_LIST`), C# (`ListQueryParser.DefaultMaxInList`) and Kotlin (a generated file-private constant that matches the TypeScript default). ### Error responses for a bad request or a failed write From 03c7def987c68ae3e1677adc3d6c910f4a153239 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 05:31:59 -0500 Subject: [PATCH 9/9] no-mistakes(document): sync C# docs and agent refs to ListQuery --- .../files/16283aaffb2211da.md | 2 +- .../files/1944176d5ab05889.md | 2 +- ...3a4f77d88acbd3b.md => 459fd71735a6bc90.md} | 2 +- ...8d3d3a7e1e287ce.md => 86a47920a4cf7abc.md} | 2 +- .../files/93ebe0549b1c81af.md | 2 +- ...e7130ca4922c867.md => 9965e221bf197a06.md} | 6 +- ...41cb586bdd98720.md => bd42756bc33c3899.md} | 2 +- ...03a2dff540a3c7b.md => ea613a5701fa6856.md} | 4 +- agent-context-shipped/manifest.json | 352 +++++++++--------- .../references/calibration.md | 2 +- .../references/capability-checklist.md | 2 +- .../metaobjects-audit/references/csharp.md | 6 +- .../metaobjects-audit/references/java.md | 4 +- .../metaobjects-audit/references/kotlin.md | 2 +- .../metaobjects-audit/references/python.md | 2 +- .../references/typescript.md | 2 +- .../references/csharp.md | 2 +- docs/CONFORMANCE.md | 2 +- docs/features/language-differences.md | 6 +- docs/ports/csharp.md | 12 +- .../references/calibration.md | 2 +- .../references/capability-checklist.md | 2 +- .../metaobjects-audit/references/csharp.md | 6 +- .../references/csharp.md | 2 +- .../references/calibration.md | 2 +- .../references/capability-checklist.md | 2 +- .../metaobjects-audit/references/java.md | 4 +- .../metaobjects-audit/references/kotlin.md | 2 +- .../references/calibration.md | 2 +- .../references/capability-checklist.md | 2 +- .../metaobjects-audit/references/java.md | 4 +- .../references/calibration.md | 2 +- .../references/capability-checklist.md | 2 +- .../metaobjects-audit/references/python.md | 2 +- .../references/calibration.md | 2 +- .../references/capability-checklist.md | 2 +- .../references/calibration.md | 2 +- .../references/capability-checklist.md | 2 +- .../references/typescript.md | 2 +- fixtures/api-contract-conformance/README.md | 2 +- .../EfCoreFilterDispatch.cs | 12 +- .../MetaObjects.AspNetCore/FilterParser.cs | 15 +- .../Generators/KNOWN_GAPS.md | 15 +- .../shipped/files/16283aaffb2211da.md | 2 +- .../shipped/files/1944176d5ab05889.md | 2 +- ...3a4f77d88acbd3b.md => 459fd71735a6bc90.md} | 2 +- ...8d3d3a7e1e287ce.md => 86a47920a4cf7abc.md} | 2 +- .../shipped/files/93ebe0549b1c81af.md | 2 +- ...e7130ca4922c867.md => 9965e221bf197a06.md} | 6 +- ...41cb586bdd98720.md => bd42756bc33c3899.md} | 2 +- ...03a2dff540a3c7b.md => ea613a5701fa6856.md} | 4 +- .../agent_context/shipped/manifest.json | 352 +++++++++--------- 52 files changed, 438 insertions(+), 442 deletions(-) rename server/python/src/metaobjects/agent_context/shipped/files/71f3aede2e59870d.md => agent-context-shipped/files/16283aaffb2211da.md (98%) rename server/python/src/metaobjects/agent_context/shipped/files/8e5978224add0b68.md => agent-context-shipped/files/1944176d5ab05889.md (98%) rename agent-context-shipped/files/{43a4f77d88acbd3b.md => 459fd71735a6bc90.md} (99%) rename agent-context-shipped/files/{b8d3d3a7e1e287ce.md => 86a47920a4cf7abc.md} (99%) rename server/python/src/metaobjects/agent_context/shipped/files/acf97bce8886e14c.md => agent-context-shipped/files/93ebe0549b1c81af.md (98%) rename agent-context-shipped/files/{ce7130ca4922c867.md => 9965e221bf197a06.md} (98%) rename agent-context-shipped/files/{a41cb586bdd98720.md => bd42756bc33c3899.md} (97%) rename agent-context-shipped/files/{003a2dff540a3c7b.md => ea613a5701fa6856.md} (98%) rename agent-context-shipped/files/71f3aede2e59870d.md => server/python/src/metaobjects/agent_context/shipped/files/16283aaffb2211da.md (98%) rename agent-context-shipped/files/8e5978224add0b68.md => server/python/src/metaobjects/agent_context/shipped/files/1944176d5ab05889.md (98%) rename server/python/src/metaobjects/agent_context/shipped/files/{43a4f77d88acbd3b.md => 459fd71735a6bc90.md} (99%) rename server/python/src/metaobjects/agent_context/shipped/files/{b8d3d3a7e1e287ce.md => 86a47920a4cf7abc.md} (99%) rename agent-context-shipped/files/acf97bce8886e14c.md => server/python/src/metaobjects/agent_context/shipped/files/93ebe0549b1c81af.md (98%) rename server/python/src/metaobjects/agent_context/shipped/files/{ce7130ca4922c867.md => 9965e221bf197a06.md} (98%) rename server/python/src/metaobjects/agent_context/shipped/files/{a41cb586bdd98720.md => bd42756bc33c3899.md} (97%) rename server/python/src/metaobjects/agent_context/shipped/files/{003a2dff540a3c7b.md => ea613a5701fa6856.md} (98%) diff --git a/server/python/src/metaobjects/agent_context/shipped/files/71f3aede2e59870d.md b/agent-context-shipped/files/16283aaffb2211da.md similarity index 98% rename from server/python/src/metaobjects/agent_context/shipped/files/71f3aede2e59870d.md rename to agent-context-shipped/files/16283aaffb2211da.md index 21722e10af..f3344a642c 100644 --- a/server/python/src/metaobjects/agent_context/shipped/files/71f3aede2e59870d.md +++ b/agent-context-shipped/files/16283aaffb2211da.md @@ -167,7 +167,7 @@ cross-port versioning — **do not flag it** (only intra-port skew matters). 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 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 + gating; ADR-0068) passes in TypeScript and C#, 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/server/python/src/metaobjects/agent_context/shipped/files/8e5978224add0b68.md b/agent-context-shipped/files/1944176d5ab05889.md similarity index 98% rename from server/python/src/metaobjects/agent_context/shipped/files/8e5978224add0b68.md rename to agent-context-shipped/files/1944176d5ab05889.md index d0f9766c6d..e65deaeade 100644 --- a/server/python/src/metaobjects/agent_context/shipped/files/8e5978224add0b68.md +++ b/agent-context-shipped/files/1944176d5ab05889.md @@ -162,7 +162,7 @@ another) matters. validated against the generated filter allowlist (api-contract corpus, 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 Python until the Python port's 1.3.0 REST-standard work lands — do + TypeScript and C#, 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 diff --git a/agent-context-shipped/files/43a4f77d88acbd3b.md b/agent-context-shipped/files/459fd71735a6bc90.md similarity index 99% rename from agent-context-shipped/files/43a4f77d88acbd3b.md rename to agent-context-shipped/files/459fd71735a6bc90.md index 487543bf0e..5b79c838a3 100644 --- a/agent-context-shipped/files/43a4f77d88acbd3b.md +++ b/agent-context-shipped/files/459fd71735a6bc90.md @@ -350,7 +350,7 @@ to nothing, and does not check that each claimed node complies). is **generated in all five ports** (api-contract corpus, both lanes) — **flag hand-rolled 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 + TypeScript and C#, 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 diff --git a/agent-context-shipped/files/b8d3d3a7e1e287ce.md b/agent-context-shipped/files/86a47920a4cf7abc.md similarity index 99% rename from agent-context-shipped/files/b8d3d3a7e1e287ce.md rename to agent-context-shipped/files/86a47920a4cf7abc.md index dfba5e06a5..5738f1bd60 100644 --- a/agent-context-shipped/files/b8d3d3a7e1e287ce.md +++ b/agent-context-shipped/files/86a47920a4cf7abc.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; 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. +- 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 and C#; 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** (the Node CLI hosts the reference migration helper, one option for every port). diff --git a/server/python/src/metaobjects/agent_context/shipped/files/acf97bce8886e14c.md b/agent-context-shipped/files/93ebe0549b1c81af.md similarity index 98% rename from server/python/src/metaobjects/agent_context/shipped/files/acf97bce8886e14c.md rename to agent-context-shipped/files/93ebe0549b1c81af.md index 753bfabc76..27a99889d4 100644 --- a/server/python/src/metaobjects/agent_context/shipped/files/acf97bce8886e14c.md +++ b/agent-context-shipped/files/93ebe0549b1c81af.md @@ -97,7 +97,7 @@ app.Run(); Filter operators (`eq` `ne` `gt` `gte` `lt` `lte` `in` `like` `isNull`) ship via the per-entity `FilterAllowlist` (from `FilterAllowlistGenerator`); the generated list -handler calls the `FilterParser` / `EfCoreFilterDispatch` runtime helpers in the +handler calls the `ListQueryParser` / `EfCoreFilterDispatch` runtime helpers in the `MetaObjects.AspNetCore` package, so your ASP.NET host references that package. After `dotnet meta eject routes` it calls your own copies in `codegen/runtime/` (namespace `Codegen.Runtime`) instead: compile that folder into the app and the reference goes away. The same diff --git a/agent-context-shipped/files/ce7130ca4922c867.md b/agent-context-shipped/files/9965e221bf197a06.md similarity index 98% rename from agent-context-shipped/files/ce7130ca4922c867.md rename to agent-context-shipped/files/9965e221bf197a06.md index f1fdd94246..cc2cf9a295 100644 --- a/agent-context-shipped/files/ce7130ca4922c867.md +++ b/agent-context-shipped/files/9965e221bf197a06.md @@ -157,12 +157,12 @@ version across these packages is an intra-port skew finding. (ADR-0015). `dotnet meta` has no migrate subcommand; `meta migrate` is correct. - **Core filter-operator codegen ships in C# — do NOT treat it as deferred.** The `routes` 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` + + (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`) via the runtime `ListQueryParser` + `EfCoreFilterDispatch`, validated against the generated filter allowlist (api-contract corpus, 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. + passes in TypeScript and C#; it is pending in each other port until that port's 1.3.0 + REST-standard work lands — do NOT flag its absence in a port before 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-shipped/files/a41cb586bdd98720.md b/agent-context-shipped/files/bd42756bc33c3899.md similarity index 97% rename from agent-context-shipped/files/a41cb586bdd98720.md rename to agent-context-shipped/files/bd42756bc33c3899.md index 48b411ee42..fb00f1fd0c 100644 --- a/agent-context-shipped/files/a41cb586bdd98720.md +++ b/agent-context-shipped/files/bd42756bc33c3899.md @@ -22,7 +22,7 @@ gated by the api-contract corpus in BOTH lanes. **Flag hand-rolled filter parsing anywhere.** 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 + gating (ADR-0068) — passes in TypeScript and C#, 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` diff --git a/agent-context-shipped/files/003a2dff540a3c7b.md b/agent-context-shipped/files/ea613a5701fa6856.md similarity index 98% rename from agent-context-shipped/files/003a2dff540a3c7b.md rename to agent-context-shipped/files/ea613a5701fa6856.md index 937f26fa4f..8a296b7928 100644 --- a/agent-context-shipped/files/003a2dff540a3c7b.md +++ b/agent-context-shipped/files/ea613a5701fa6856.md @@ -159,8 +159,8 @@ versioning — **do not flag it** (only intra-port skew matters). 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.** 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. + combinators, leading-wildcard gating (ADR-0068) — passes in TypeScript and C#, 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-shipped/manifest.json b/agent-context-shipped/manifest.json index f8c2630ed2..67d13c4b40 100644 --- a/agent-context-shipped/manifest.json +++ b/agent-context-shipped/manifest.json @@ -18,11 +18,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -42,7 +42,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/typescript.md", - "file": "b8d3d3a7e1e287ce.md" + "file": "86a47920a4cf7abc.md" }, { "path": ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md", @@ -232,11 +232,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -256,7 +256,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/typescript.md", - "file": "b8d3d3a7e1e287ce.md" + "file": "86a47920a4cf7abc.md" }, { "path": ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md", @@ -448,11 +448,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -472,7 +472,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/typescript.md", - "file": "b8d3d3a7e1e287ce.md" + "file": "86a47920a4cf7abc.md" }, { "path": ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md", @@ -668,11 +668,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -692,7 +692,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/typescript.md", - "file": "b8d3d3a7e1e287ce.md" + "file": "86a47920a4cf7abc.md" }, { "path": ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md", @@ -889,11 +889,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -913,7 +913,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/typescript.md", - "file": "b8d3d3a7e1e287ce.md" + "file": "86a47920a4cf7abc.md" }, { "path": ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md", @@ -1114,11 +1114,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -1138,7 +1138,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/typescript.md", - "file": "b8d3d3a7e1e287ce.md" + "file": "86a47920a4cf7abc.md" }, { "path": ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md", @@ -1338,11 +1338,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -1362,7 +1362,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/typescript.md", - "file": "b8d3d3a7e1e287ce.md" + "file": "86a47920a4cf7abc.md" }, { "path": ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md", @@ -1554,11 +1554,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -1578,7 +1578,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/typescript.md", - "file": "b8d3d3a7e1e287ce.md" + "file": "86a47920a4cf7abc.md" }, { "path": ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md", @@ -1768,11 +1768,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -1780,7 +1780,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -1958,11 +1958,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -1970,7 +1970,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2150,11 +2150,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -2162,7 +2162,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2346,11 +2346,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -2358,7 +2358,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2543,11 +2543,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -2555,7 +2555,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2744,11 +2744,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -2756,7 +2756,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2944,11 +2944,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -2956,7 +2956,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3136,11 +3136,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -3148,7 +3148,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3326,11 +3326,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -3338,7 +3338,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3516,11 +3516,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -3528,7 +3528,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3708,11 +3708,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -3720,7 +3720,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3904,11 +3904,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -3916,7 +3916,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4101,11 +4101,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -4113,7 +4113,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4302,11 +4302,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -4314,7 +4314,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4502,11 +4502,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -4514,7 +4514,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4694,11 +4694,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -4706,7 +4706,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4884,15 +4884,15 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "ce7130ca4922c867.md" + "file": "9965e221bf197a06.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5036,7 +5036,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "acf97bce8886e14c.md" + "file": "93ebe0549b1c81af.md" }, { "path": ".claude/skills/metaobjects-verify/SKILL.md", @@ -5074,15 +5074,15 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "ce7130ca4922c867.md" + "file": "9965e221bf197a06.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5226,7 +5226,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "acf97bce8886e14c.md" + "file": "93ebe0549b1c81af.md" }, { "path": ".claude/skills/metaobjects-verify/SKILL.md", @@ -5266,15 +5266,15 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "ce7130ca4922c867.md" + "file": "9965e221bf197a06.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5418,7 +5418,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "acf97bce8886e14c.md" + "file": "93ebe0549b1c81af.md" }, { "path": ".claude/skills/metaobjects-runtime-ui/references/react.md", @@ -5462,15 +5462,15 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "ce7130ca4922c867.md" + "file": "9965e221bf197a06.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5614,7 +5614,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "acf97bce8886e14c.md" + "file": "93ebe0549b1c81af.md" }, { "path": ".claude/skills/metaobjects-runtime-ui/references/react.md", @@ -5659,15 +5659,15 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "ce7130ca4922c867.md" + "file": "9965e221bf197a06.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5811,7 +5811,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "acf97bce8886e14c.md" + "file": "93ebe0549b1c81af.md" }, { "path": ".claude/skills/metaobjects-runtime-ui/references/react.md", @@ -5860,15 +5860,15 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "ce7130ca4922c867.md" + "file": "9965e221bf197a06.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6012,7 +6012,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "acf97bce8886e14c.md" + "file": "93ebe0549b1c81af.md" }, { "path": ".claude/skills/metaobjects-runtime-ui/references/react.md", @@ -6060,15 +6060,15 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "ce7130ca4922c867.md" + "file": "9965e221bf197a06.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6212,7 +6212,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "acf97bce8886e14c.md" + "file": "93ebe0549b1c81af.md" }, { "path": ".claude/skills/metaobjects-verify/SKILL.md", @@ -6252,15 +6252,15 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "ce7130ca4922c867.md" + "file": "9965e221bf197a06.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6404,7 +6404,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "acf97bce8886e14c.md" + "file": "93ebe0549b1c81af.md" }, { "path": ".claude/skills/metaobjects-verify/SKILL.md", @@ -6442,11 +6442,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6458,7 +6458,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/python.md", - "file": "8e5978224add0b68.md" + "file": "1944176d5ab05889.md" }, { "path": ".claude/skills/metaobjects-audit/references/requirements.md", @@ -6632,11 +6632,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6648,7 +6648,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/python.md", - "file": "8e5978224add0b68.md" + "file": "1944176d5ab05889.md" }, { "path": ".claude/skills/metaobjects-audit/references/requirements.md", @@ -6824,11 +6824,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6840,7 +6840,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/python.md", - "file": "8e5978224add0b68.md" + "file": "1944176d5ab05889.md" }, { "path": ".claude/skills/metaobjects-audit/references/requirements.md", @@ -7020,11 +7020,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -7036,7 +7036,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/python.md", - "file": "8e5978224add0b68.md" + "file": "1944176d5ab05889.md" }, { "path": ".claude/skills/metaobjects-audit/references/requirements.md", @@ -7217,11 +7217,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -7233,7 +7233,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/python.md", - "file": "8e5978224add0b68.md" + "file": "1944176d5ab05889.md" }, { "path": ".claude/skills/metaobjects-audit/references/requirements.md", @@ -7418,11 +7418,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -7434,7 +7434,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/python.md", - "file": "8e5978224add0b68.md" + "file": "1944176d5ab05889.md" }, { "path": ".claude/skills/metaobjects-audit/references/requirements.md", @@ -7618,11 +7618,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -7634,7 +7634,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/python.md", - "file": "8e5978224add0b68.md" + "file": "1944176d5ab05889.md" }, { "path": ".claude/skills/metaobjects-audit/references/requirements.md", @@ -7810,11 +7810,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -7826,7 +7826,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/python.md", - "file": "8e5978224add0b68.md" + "file": "1944176d5ab05889.md" }, { "path": ".claude/skills/metaobjects-audit/references/requirements.md", @@ -8000,11 +8000,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -8170,11 +8170,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -8342,11 +8342,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -8518,11 +8518,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -8695,11 +8695,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -8876,11 +8876,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -9056,11 +9056,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -9228,11 +9228,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -9399,11 +9399,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -9411,11 +9411,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -9610,11 +9610,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -9622,11 +9622,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -9823,11 +9823,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -9835,11 +9835,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10040,11 +10040,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -10052,11 +10052,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10258,11 +10258,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -10270,11 +10270,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10480,11 +10480,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -10492,11 +10492,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10701,11 +10701,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -10713,11 +10713,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10914,11 +10914,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -10926,11 +10926,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", diff --git a/agent-context/skills/metaobjects-audit/references/calibration.md b/agent-context/skills/metaobjects-audit/references/calibration.md index 48b411ee42..fb00f1fd0c 100644 --- a/agent-context/skills/metaobjects-audit/references/calibration.md +++ b/agent-context/skills/metaobjects-audit/references/calibration.md @@ -22,7 +22,7 @@ gated by the api-contract corpus in BOTH lanes. **Flag hand-rolled filter parsing anywhere.** 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 + gating (ADR-0068) — passes in TypeScript and C#, 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` diff --git a/agent-context/skills/metaobjects-audit/references/capability-checklist.md b/agent-context/skills/metaobjects-audit/references/capability-checklist.md index 487543bf0e..5b79c838a3 100644 --- a/agent-context/skills/metaobjects-audit/references/capability-checklist.md +++ b/agent-context/skills/metaobjects-audit/references/capability-checklist.md @@ -350,7 +350,7 @@ to nothing, and does not check that each claimed node complies). is **generated in all five ports** (api-contract corpus, both lanes) — **flag hand-rolled 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 + TypeScript and C#, 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 diff --git a/agent-context/skills/metaobjects-audit/references/csharp.md b/agent-context/skills/metaobjects-audit/references/csharp.md index f1fdd94246..cc2cf9a295 100644 --- a/agent-context/skills/metaobjects-audit/references/csharp.md +++ b/agent-context/skills/metaobjects-audit/references/csharp.md @@ -157,12 +157,12 @@ version across these packages is an intra-port skew finding. (ADR-0015). `dotnet meta` has no migrate subcommand; `meta migrate` is correct. - **Core filter-operator codegen ships in C# — do NOT treat it as deferred.** The `routes` 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` + + (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`) via the runtime `ListQueryParser` + `EfCoreFilterDispatch`, validated against the generated filter allowlist (api-contract corpus, 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. + passes in TypeScript and C#; it is pending in each other port until that port's 1.3.0 + REST-standard work lands — do NOT flag its absence in a port before 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 937f26fa4f..8a296b7928 100644 --- a/agent-context/skills/metaobjects-audit/references/java.md +++ b/agent-context/skills/metaobjects-audit/references/java.md @@ -159,8 +159,8 @@ versioning — **do not flag it** (only intra-port skew matters). 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.** 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. + combinators, leading-wildcard gating (ADR-0068) — passes in TypeScript and C#, 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 21722e10af..f3344a642c 100644 --- a/agent-context/skills/metaobjects-audit/references/kotlin.md +++ b/agent-context/skills/metaobjects-audit/references/kotlin.md @@ -167,7 +167,7 @@ cross-port versioning — **do not flag it** (only intra-port skew matters). 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 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 + gating; ADR-0068) passes in TypeScript and C#, 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 d0f9766c6d..e65deaeade 100644 --- a/agent-context/skills/metaobjects-audit/references/python.md +++ b/agent-context/skills/metaobjects-audit/references/python.md @@ -162,7 +162,7 @@ another) matters. validated against the generated filter allowlist (api-contract corpus, 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 Python until the Python port's 1.3.0 REST-standard work lands — do + TypeScript and C#, 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 diff --git a/agent-context/skills/metaobjects-audit/references/typescript.md b/agent-context/skills/metaobjects-audit/references/typescript.md index dfba5e06a5..5738f1bd60 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; 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. +- 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 and C#; 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** (the Node CLI hosts the reference migration helper, one option for every port). diff --git a/agent-context/skills/metaobjects-runtime-ui/references/csharp.md b/agent-context/skills/metaobjects-runtime-ui/references/csharp.md index 753bfabc76..27a99889d4 100644 --- a/agent-context/skills/metaobjects-runtime-ui/references/csharp.md +++ b/agent-context/skills/metaobjects-runtime-ui/references/csharp.md @@ -97,7 +97,7 @@ app.Run(); Filter operators (`eq` `ne` `gt` `gte` `lt` `lte` `in` `like` `isNull`) ship via the per-entity `FilterAllowlist` (from `FilterAllowlistGenerator`); the generated list -handler calls the `FilterParser` / `EfCoreFilterDispatch` runtime helpers in the +handler calls the `ListQueryParser` / `EfCoreFilterDispatch` runtime helpers in the `MetaObjects.AspNetCore` package, so your ASP.NET host references that package. After `dotnet meta eject routes` it calls your own copies in `codegen/runtime/` (namespace `Codegen.Runtime`) instead: compile that folder into the app and the reference goes away. The same diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 340c477b5c..b3878015dd 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -582,7 +582,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`), `rules/` (17, ADR-0066 through a generated service: derived and declared commands, a query, permission points, the three 409 codes, a declared error and a refusal rolling back, under the default settings and three `rules.*` variants; generated lane, TypeScript only until each port's 1.3.0 service work), `list-query/` (21, 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, a default page of 50, paging past 50, and the `invalid_json`, `invalid_id`, `pagination.invalid_value` and `constraint_violation` refusals; generated lane, TypeScript and C# until each port's 1.3.0 REST-standard work) and `report/` (37, +`api.unknownFields: drop`), `rules/` (17, ADR-0066 through a generated service: derived and declared commands, a query, permission points, the three 409 codes, a declared error and a refusal rolling back, under the default settings and three `rules.*` variants; generated lane, TypeScript only until each port's 1.3.0 service work), `list-query/` (21, 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, a default page of 50, paging past 50, and the `invalid_json`, `invalid_id`, `pagination.invalid_value` and `constraint_violation` refusals; generated lane, TypeScript and C#; the other ports from their 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, diff --git a/docs/features/language-differences.md b/docs/features/language-differences.md index 3e5ffbd5d6..d2eb6d6679 100644 --- a/docs/features/language-differences.md +++ b/docs/features/language-differences.md @@ -41,9 +41,9 @@ project. | **Largest report page** | 10,000 rows, then 400 `report_too_large` | Same | Same | Same | Same | | **`api.pagination`, `api.unknownFields`, the validation `issues` list** | The same in every port; defined once in [api-contract.md](api-contract.md) ([page size](api-contract.md#sort--pagination), [unknown fields](api-contract.md#unknown-request-fields-apiunknownfields), [validation issues](api-contract.md#a-validation-error-lists-every-issue)) | | | | | | **Filter and sort errors** | 400 with `field`, plus `op`, `expected` and the allowed fields | 400 with `field` | 400 with `field` | 400 with `field` | 400 with `field` | -| **`?status=active` (a bare field, not `filter[status][eq]`)** | 400 `filter.bare_field`, naming the form that works | Ignored: every row comes back | Ignored | Ignored | Ignored | -| **Filter extras beyond the nine operators** | `?search=`, `filter[or]` / `filter[and]`, leading-`%` refusal, filter-value format check | None | None | None | None | -| **Malformed JSON, a malformed id, a bad page bound, a database constraint, a server error** | Pinned bodies: `invalid_json`, `invalid_id`, `pagination.invalid_value`, `constraint_violation`, 500 `internal` | As the framework answers (a report's bad page bound is pinned in every port) | Same as C# | Same as C# | Same as C# | +| **`?status=active` (a bare field, not `filter[status][eq]`)** | 400 `filter.bare_field`, naming the form that works | 400 `filter.bare_field`, naming the form that works | Ignored: every row comes back | Ignored | Ignored | +| **Filter extras beyond the nine operators** | `?search=`, `filter[or]` / `filter[and]`, leading-`%` refusal, filter-value format check | Same as TypeScript | None | None | None | +| **Malformed JSON, a malformed id, a bad page bound, a database constraint, a server error** | Pinned bodies: `invalid_json`, `invalid_id`, `pagination.invalid_value`, `constraint_violation`, 500 `internal` | The same pinned bodies as TypeScript | As the framework answers | As the framework answers | As the framework answers | | **Field names in code** | The model's names (`createdAt`) | PascalCase properties (`CreatedAt`) | The model's names | The model's names | The model's names, not snake_case (`createdAt`) | | **Field names on the wire** | The model's names, in every port | | | | | | **Decimals and null members on the wire** | Each port writes its serializer's default; a `wire` setting makes them identical. The per-port table is under [The wire setting](api-contract.md#the-wire-setting) | | | | | diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 9f8b89780f..8bf97b7703 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -1245,8 +1245,9 @@ Today's `RoutesGenerator` honours pagination (`?limit`/`?offset`), sort always sends. Filter operators (`eq` / `ne` / `gt` / `gte` / `lt` / `lte` / `in` / `like` / `isNull`) per [`api-contract.md`](../features/api-contract.md) ship too — the generated `FilterAllowlist` (`FilterAllowlistGenerator`) -feeds `FilterParser.Parse` + `EfCoreFilterDispatch.ApplyFilter`, both wired -directly into the generated list handler. A read-only projection +feeds `ListQueryParser.Parse` + `EfCoreFilterDispatch.Apply`, both wired +directly into the generated list handler; the REST-standard query (`?search`, `filter[or]` / `filter[and]`, +the named refusals) is read the same way. A read-only projection (`source.rdb @kind: view`) and a view-backed report get the same filter and sort on their list route, against an allowlist of their own fields. @@ -1264,12 +1265,9 @@ integer is `400 pagination.invalid_value` with or without the setting. **Known gaps** (full list with workarounds in [KNOWN_GAPS.md](https://github.com/metaobjectsdev/metaobjects/blob/main/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md)): -no `filter[or]` / `filter[and]` boolean grouping and a single sort key only (both outside the -cross-port contract today); the `View` / `Views` names are reserved for a +a single sort key only (`G3`); the sort set is wider than the contract's sortable set (`G10`); the `View` / `Views` names are reserved for a write-through entity's generated read model; an `EmitMappedClass` override does not reach that -read model; M:N traversal on a write-through entity is not routed through the replica view; the -ordered-comparison filter fallback in `EfCoreFilterDispatch` needs a hand-written typed -dispatcher for some column types; there is no metadata-driven runtime tier (EF Core output is +read model; M:N traversal on a write-through entity is not routed through the replica view; there is no metadata-driven runtime tier (EF Core output is generated code), and no `migrate` surface (EF Core Migrations, or the Node `meta migrate` reference helper). ## Capability snapshot 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 48b411ee42..fb00f1fd0c 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 @@ -22,7 +22,7 @@ gated by the api-contract corpus in BOTH lanes. **Flag hand-rolled filter parsing anywhere.** 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 + gating (ADR-0068) — passes in TypeScript and C#, 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` 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 487543bf0e..5b79c838a3 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 @@ -350,7 +350,7 @@ to nothing, and does not check that each claimed node complies). is **generated in all five ports** (api-contract corpus, both lanes) — **flag hand-rolled 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 + TypeScript and C#, 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 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 f1fdd94246..cc2cf9a295 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 @@ -157,12 +157,12 @@ version across these packages is an intra-port skew finding. (ADR-0015). `dotnet meta` has no migrate subcommand; `meta migrate` is correct. - **Core filter-operator codegen ships in C# — do NOT treat it as deferred.** The `routes` 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` + + (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`) via the runtime `ListQueryParser` + `EfCoreFilterDispatch`, validated against the generated filter allowlist (api-contract corpus, 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. + passes in TypeScript and C#; it is pending in each other port until that port's 1.3.0 + REST-standard work lands — do NOT flag its absence in a port before 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/csharp/expected/.claude/skills/metaobjects-runtime-ui/references/csharp.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-runtime-ui/references/csharp.md index 753bfabc76..27a99889d4 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-runtime-ui/references/csharp.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-runtime-ui/references/csharp.md @@ -97,7 +97,7 @@ app.Run(); Filter operators (`eq` `ne` `gt` `gte` `lt` `lte` `in` `like` `isNull`) ship via the per-entity `FilterAllowlist` (from `FilterAllowlistGenerator`); the generated list -handler calls the `FilterParser` / `EfCoreFilterDispatch` runtime helpers in the +handler calls the `ListQueryParser` / `EfCoreFilterDispatch` runtime helpers in the `MetaObjects.AspNetCore` package, so your ASP.NET host references that package. After `dotnet meta eject routes` it calls your own copies in `codegen/runtime/` (namespace `Codegen.Runtime`) instead: compile that folder into the app and the reference goes away. The same 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 48b411ee42..fb00f1fd0c 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 @@ -22,7 +22,7 @@ gated by the api-contract corpus in BOTH lanes. **Flag hand-rolled filter parsing anywhere.** 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 + gating (ADR-0068) — passes in TypeScript and C#, 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` 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 487543bf0e..5b79c838a3 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 @@ -350,7 +350,7 @@ to nothing, and does not check that each claimed node complies). is **generated in all five ports** (api-contract corpus, both lanes) — **flag hand-rolled 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 + TypeScript and C#, 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 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 937f26fa4f..8a296b7928 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 @@ -159,8 +159,8 @@ versioning — **do not flag it** (only intra-port skew matters). 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.** 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. + combinators, leading-wildcard gating (ADR-0068) — passes in TypeScript and C#, 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 21722e10af..f3344a642c 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 @@ -167,7 +167,7 @@ cross-port versioning — **do not flag it** (only intra-port skew matters). 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 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 + gating; ADR-0068) passes in TypeScript and C#, 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 48b411ee42..fb00f1fd0c 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 @@ -22,7 +22,7 @@ gated by the api-contract corpus in BOTH lanes. **Flag hand-rolled filter parsing anywhere.** 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 + gating (ADR-0068) — passes in TypeScript and C#, 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` 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 487543bf0e..5b79c838a3 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 @@ -350,7 +350,7 @@ to nothing, and does not check that each claimed node complies). is **generated in all five ports** (api-contract corpus, both lanes) — **flag hand-rolled 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 + TypeScript and C#, 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 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 937f26fa4f..8a296b7928 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 @@ -159,8 +159,8 @@ versioning — **do not flag it** (only intra-port skew matters). 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.** 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. + combinators, leading-wildcard gating (ADR-0068) — passes in TypeScript and C#, 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 48b411ee42..fb00f1fd0c 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 @@ -22,7 +22,7 @@ gated by the api-contract corpus in BOTH lanes. **Flag hand-rolled filter parsing anywhere.** 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 + gating (ADR-0068) — passes in TypeScript and C#, 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` 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 487543bf0e..5b79c838a3 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 @@ -350,7 +350,7 @@ to nothing, and does not check that each claimed node complies). is **generated in all five ports** (api-contract corpus, both lanes) — **flag hand-rolled 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 + TypeScript and C#, 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 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 d0f9766c6d..e65deaeade 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 @@ -162,7 +162,7 @@ another) matters. validated against the generated filter allowlist (api-contract corpus, 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 Python until the Python port's 1.3.0 REST-standard work lands — do + TypeScript and C#, 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 diff --git a/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/calibration.md index 48b411ee42..fb00f1fd0c 100644 --- a/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -22,7 +22,7 @@ gated by the api-contract corpus in BOTH lanes. **Flag hand-rolled filter parsing anywhere.** 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 + gating (ADR-0068) — passes in TypeScript and C#, 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` diff --git a/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index 487543bf0e..5b79c838a3 100644 --- a/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -350,7 +350,7 @@ to nothing, and does not check that each claimed node complies). is **generated in all five ports** (api-contract corpus, both lanes) — **flag hand-rolled 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 + TypeScript and C#, 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 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 48b411ee42..fb00f1fd0c 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 @@ -22,7 +22,7 @@ gated by the api-contract corpus in BOTH lanes. **Flag hand-rolled filter parsing anywhere.** 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 + gating (ADR-0068) — passes in TypeScript and C#, 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` 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 487543bf0e..5b79c838a3 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 @@ -350,7 +350,7 @@ to nothing, and does not check that each claimed node complies). is **generated in all five ports** (api-contract corpus, both lanes) — **flag hand-rolled 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 + TypeScript and C#, 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 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 dfba5e06a5..5738f1bd60 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; 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. +- 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 and C#; 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** (the Node CLI hosts the reference migration helper, one option for every port). diff --git a/fixtures/api-contract-conformance/README.md b/fixtures/api-contract-conformance/README.md index 666c111003..48c1c09173 100644 --- a/fixtures/api-contract-conformance/README.md +++ b/fixtures/api-contract-conformance/README.md @@ -72,7 +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/` | 21 | 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, a default page of 50, 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 in full; C# runs the scenarios its routes answer today (see the sub-corpus README); the other ports from their 1.3.0 REST-standard work | generated only | +| `list-query/` | 21 | 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, a default page of 50, 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 and C# in full; the other ports from their 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 | | `rules/` | 17 | ADR-0066 through a generated service: a derived transition command and its derived permission name, a declared `@permission`, 403 `forbidden`, the three 409 codes (`invalid_transition`, `transition_condition_failed`, `state_managed` on update and create), a declared command and its declared error, a `@public` command and query, a claimed transition with no command of its own, and a hook's and the event hook's refusal rolling the write back; `settings/` runs `rules.lifecycle.create: any` and `rules.lifecycle.commands: all` and `none` over the same model | generated only, TypeScript only until each port's 1.3.0 service work | diff --git a/server/csharp/MetaObjects.AspNetCore/EfCoreFilterDispatch.cs b/server/csharp/MetaObjects.AspNetCore/EfCoreFilterDispatch.cs index 1492a53770..47058d464c 100644 --- a/server/csharp/MetaObjects.AspNetCore/EfCoreFilterDispatch.cs +++ b/server/csharp/MetaObjects.AspNetCore/EfCoreFilterDispatch.cs @@ -1,10 +1,10 @@ -// EfCoreFilterDispatch — translates a list of FilterPredicate into an -// IQueryable filter chain. Generated routes call -// EfCoreFilterDispatch.ApplyFilter(q, predicates) in their list handler after -// FilterParser.Parse returns success. +// EfCoreFilterDispatch — translates the filter tree of a ListQuery into an +// IQueryable filter chain. Generated routes call EfCoreFilterDispatch.Apply(q, query) +// in their list handler after ListQueryParser.Parse returns success. The flat +// ApplyFilter(q, predicates) overload is [Obsolete] (1.3.0) and kept only for hand-written callers. // -// Each predicate becomes a single Expression> appended via -// IQueryable.Where; multiple predicates AND together. +// Each leaf predicate becomes a single Expression> appended via +// IQueryable.Where; sibling predicates AND together. // // Translation strategy — the predicate field name is the METADATA field name // (e.g. "createdAt"), which maps to the entity's PascalCase CLR property diff --git a/server/csharp/MetaObjects.AspNetCore/FilterParser.cs b/server/csharp/MetaObjects.AspNetCore/FilterParser.cs index 66d51b88a5..24f1d41402 100644 --- a/server/csharp/MetaObjects.AspNetCore/FilterParser.cs +++ b/server/csharp/MetaObjects.AspNetCore/FilterParser.cs @@ -1,13 +1,10 @@ -// FilterParser — substrate-agnostic parser for the FR-009 filter URL grammar -// (filter[][]=, plus filter[]= sugar for eq). +// FilterParser — the flat FR-009 filter parser (filter[][]=, plus +// filter[]= sugar for eq). Obsolete since 1.3.0: generated routes call +// ListQueryParser.Parse, which reads the whole REST-standard list query (or/and groups, search, +// sort, page and the named refusals). Kept only for hand-written callers until 2.0. // -// Generated routes call FilterParser.Parse(request.Query, allowlistFields, -// opsByField) at the top of their list handler. On error → 400 with the -// returned envelope key; on success → the dispatcher (EfCoreFilterDispatch) -// applies the predicates to an IQueryable. -// -// Part of the codegen runtime surface; mirrors Java codegen-spring's -// runtime/FilterParser.java byte-for-byte semantics. +// Part of the helper runtime surface; mirrors Java codegen-spring's +// runtime/FilterParser.java semantics for the flat grammar. using System.Collections.Generic; using Microsoft.AspNetCore.Http; diff --git a/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md b/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md index 7692cfc111..11626e47dd 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md +++ b/server/csharp/MetaObjects.Codegen/Generators/KNOWN_GAPS.md @@ -52,13 +52,14 @@ Update when a gap closes or a new one surfaces. So the entry stays OPEN, scoped to TPH only, and its cross-port framing is intact rather than obsolete. What closed is the part that was stale: the vanilla path, corrected in **Today** above. Reopening the TPH half is a feature decision (extend the TPH union to carry owned navigations), not a bug fix, and it would want to move on Java and C# together. -### G5 — `EfCoreFilterDispatch` ordered-comparison fallback - -**Contract.** `gt` / `gte` / `lt` / `lte` work uniformly for all numeric/date subtypes. - -**Today.** [`EfCoreFilterDispatch.BuildComparison`](../Runtime/EfCoreFilterDispatch.cs) tries `long.TryParse` first and falls through to lexicographic `string.Compare`. Works for `long` columns and for ISO 8601 string-backed dates (which sort lexicographically). Fragile for `decimal` / `double` / non-ISO date columns — those degrade silently to string-compare semantics. The contract still holds for the operator vocabulary; only the comparison precision is gappy. - -**Workaround.** Consumers can hand-write a typed dispatcher in their repository layer that materializes `Expression>` with the column's CLR type. A future closure pass would add `decimal.TryParse` + `DateTime.TryParse` to the dispatcher; tracked here rather than auto-closed because the right fix is per-port substrate-aware emit, not a runtime tweak. +### G5 — `EfCoreFilterDispatch` ordered-comparison fallback — **CLOSED** + +**Was.** `EfCoreFilterDispatch` compared `gt` / `gte` / `lt` / `lte` through a string fallback +(`long.TryParse`, then lexicographic `string.Compare`), so `decimal`, `double` and non-ISO date +columns compared as text. The 1.3.0 dispatch types each operand to its column's CLR type +(`EfCoreFilterDispatch.CoerceTo`: exact `decimal`, `TimeSpan` duration, `DateTimeOffset`, `DateTime`, +`DateOnly`, `TimeOnly`, enum, `bool`, `Guid`) before it builds the comparison, and the api-contract +`decimal/` corpus gates the ordered operators (`gt` / `lt` on exact decimals) in the generated C# lane. ### G6 — CORS diff --git a/agent-context-shipped/files/71f3aede2e59870d.md b/server/python/src/metaobjects/agent_context/shipped/files/16283aaffb2211da.md similarity index 98% rename from agent-context-shipped/files/71f3aede2e59870d.md rename to server/python/src/metaobjects/agent_context/shipped/files/16283aaffb2211da.md index 21722e10af..f3344a642c 100644 --- a/agent-context-shipped/files/71f3aede2e59870d.md +++ b/server/python/src/metaobjects/agent_context/shipped/files/16283aaffb2211da.md @@ -167,7 +167,7 @@ cross-port versioning — **do not flag it** (only intra-port skew matters). 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 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 + gating; ADR-0068) passes in TypeScript and C#, 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-shipped/files/8e5978224add0b68.md b/server/python/src/metaobjects/agent_context/shipped/files/1944176d5ab05889.md similarity index 98% rename from agent-context-shipped/files/8e5978224add0b68.md rename to server/python/src/metaobjects/agent_context/shipped/files/1944176d5ab05889.md index d0f9766c6d..e65deaeade 100644 --- a/agent-context-shipped/files/8e5978224add0b68.md +++ b/server/python/src/metaobjects/agent_context/shipped/files/1944176d5ab05889.md @@ -162,7 +162,7 @@ another) matters. validated against the generated filter allowlist (api-contract corpus, 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 Python until the Python port's 1.3.0 REST-standard work lands — do + TypeScript and C#, 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 diff --git a/server/python/src/metaobjects/agent_context/shipped/files/43a4f77d88acbd3b.md b/server/python/src/metaobjects/agent_context/shipped/files/459fd71735a6bc90.md similarity index 99% rename from server/python/src/metaobjects/agent_context/shipped/files/43a4f77d88acbd3b.md rename to server/python/src/metaobjects/agent_context/shipped/files/459fd71735a6bc90.md index 487543bf0e..5b79c838a3 100644 --- a/server/python/src/metaobjects/agent_context/shipped/files/43a4f77d88acbd3b.md +++ b/server/python/src/metaobjects/agent_context/shipped/files/459fd71735a6bc90.md @@ -350,7 +350,7 @@ to nothing, and does not check that each claimed node complies). is **generated in all five ports** (api-contract corpus, both lanes) — **flag hand-rolled 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 + TypeScript and C#, 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 diff --git a/server/python/src/metaobjects/agent_context/shipped/files/b8d3d3a7e1e287ce.md b/server/python/src/metaobjects/agent_context/shipped/files/86a47920a4cf7abc.md similarity index 99% rename from server/python/src/metaobjects/agent_context/shipped/files/b8d3d3a7e1e287ce.md rename to server/python/src/metaobjects/agent_context/shipped/files/86a47920a4cf7abc.md index dfba5e06a5..5738f1bd60 100644 --- a/server/python/src/metaobjects/agent_context/shipped/files/b8d3d3a7e1e287ce.md +++ b/server/python/src/metaobjects/agent_context/shipped/files/86a47920a4cf7abc.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; 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. +- 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 and C#; 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** (the Node CLI hosts the reference migration helper, one option for every port). diff --git a/agent-context-shipped/files/acf97bce8886e14c.md b/server/python/src/metaobjects/agent_context/shipped/files/93ebe0549b1c81af.md similarity index 98% rename from agent-context-shipped/files/acf97bce8886e14c.md rename to server/python/src/metaobjects/agent_context/shipped/files/93ebe0549b1c81af.md index 753bfabc76..27a99889d4 100644 --- a/agent-context-shipped/files/acf97bce8886e14c.md +++ b/server/python/src/metaobjects/agent_context/shipped/files/93ebe0549b1c81af.md @@ -97,7 +97,7 @@ app.Run(); Filter operators (`eq` `ne` `gt` `gte` `lt` `lte` `in` `like` `isNull`) ship via the per-entity `FilterAllowlist` (from `FilterAllowlistGenerator`); the generated list -handler calls the `FilterParser` / `EfCoreFilterDispatch` runtime helpers in the +handler calls the `ListQueryParser` / `EfCoreFilterDispatch` runtime helpers in the `MetaObjects.AspNetCore` package, so your ASP.NET host references that package. After `dotnet meta eject routes` it calls your own copies in `codegen/runtime/` (namespace `Codegen.Runtime`) instead: compile that folder into the app and the reference goes away. The same diff --git a/server/python/src/metaobjects/agent_context/shipped/files/ce7130ca4922c867.md b/server/python/src/metaobjects/agent_context/shipped/files/9965e221bf197a06.md similarity index 98% rename from server/python/src/metaobjects/agent_context/shipped/files/ce7130ca4922c867.md rename to server/python/src/metaobjects/agent_context/shipped/files/9965e221bf197a06.md index f1fdd94246..cc2cf9a295 100644 --- a/server/python/src/metaobjects/agent_context/shipped/files/ce7130ca4922c867.md +++ b/server/python/src/metaobjects/agent_context/shipped/files/9965e221bf197a06.md @@ -157,12 +157,12 @@ version across these packages is an intra-port skew finding. (ADR-0015). `dotnet meta` has no migrate subcommand; `meta migrate` is correct. - **Core filter-operator codegen ships in C# — do NOT treat it as deferred.** The `routes` 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` + + (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`) via the runtime `ListQueryParser` + `EfCoreFilterDispatch`, validated against the generated filter allowlist (api-contract corpus, 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. + passes in TypeScript and C#; it is pending in each other port until that port's 1.3.0 + REST-standard work lands — do NOT flag its absence in a port before 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/server/python/src/metaobjects/agent_context/shipped/files/a41cb586bdd98720.md b/server/python/src/metaobjects/agent_context/shipped/files/bd42756bc33c3899.md similarity index 97% rename from server/python/src/metaobjects/agent_context/shipped/files/a41cb586bdd98720.md rename to server/python/src/metaobjects/agent_context/shipped/files/bd42756bc33c3899.md index 48b411ee42..fb00f1fd0c 100644 --- a/server/python/src/metaobjects/agent_context/shipped/files/a41cb586bdd98720.md +++ b/server/python/src/metaobjects/agent_context/shipped/files/bd42756bc33c3899.md @@ -22,7 +22,7 @@ gated by the api-contract corpus in BOTH lanes. **Flag hand-rolled filter parsing anywhere.** 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 + gating (ADR-0068) — passes in TypeScript and C#, 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` diff --git a/server/python/src/metaobjects/agent_context/shipped/files/003a2dff540a3c7b.md b/server/python/src/metaobjects/agent_context/shipped/files/ea613a5701fa6856.md similarity index 98% rename from server/python/src/metaobjects/agent_context/shipped/files/003a2dff540a3c7b.md rename to server/python/src/metaobjects/agent_context/shipped/files/ea613a5701fa6856.md index 937f26fa4f..8a296b7928 100644 --- a/server/python/src/metaobjects/agent_context/shipped/files/003a2dff540a3c7b.md +++ b/server/python/src/metaobjects/agent_context/shipped/files/ea613a5701fa6856.md @@ -159,8 +159,8 @@ versioning — **do not flag it** (only intra-port skew matters). 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.** 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. + combinators, leading-wildcard gating (ADR-0068) — passes in TypeScript and C#, 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/server/python/src/metaobjects/agent_context/shipped/manifest.json b/server/python/src/metaobjects/agent_context/shipped/manifest.json index f8c2630ed2..67d13c4b40 100644 --- a/server/python/src/metaobjects/agent_context/shipped/manifest.json +++ b/server/python/src/metaobjects/agent_context/shipped/manifest.json @@ -18,11 +18,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -42,7 +42,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/typescript.md", - "file": "b8d3d3a7e1e287ce.md" + "file": "86a47920a4cf7abc.md" }, { "path": ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md", @@ -232,11 +232,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -256,7 +256,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/typescript.md", - "file": "b8d3d3a7e1e287ce.md" + "file": "86a47920a4cf7abc.md" }, { "path": ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md", @@ -448,11 +448,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -472,7 +472,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/typescript.md", - "file": "b8d3d3a7e1e287ce.md" + "file": "86a47920a4cf7abc.md" }, { "path": ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md", @@ -668,11 +668,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -692,7 +692,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/typescript.md", - "file": "b8d3d3a7e1e287ce.md" + "file": "86a47920a4cf7abc.md" }, { "path": ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md", @@ -889,11 +889,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -913,7 +913,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/typescript.md", - "file": "b8d3d3a7e1e287ce.md" + "file": "86a47920a4cf7abc.md" }, { "path": ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md", @@ -1114,11 +1114,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -1138,7 +1138,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/typescript.md", - "file": "b8d3d3a7e1e287ce.md" + "file": "86a47920a4cf7abc.md" }, { "path": ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md", @@ -1338,11 +1338,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -1362,7 +1362,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/typescript.md", - "file": "b8d3d3a7e1e287ce.md" + "file": "86a47920a4cf7abc.md" }, { "path": ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md", @@ -1554,11 +1554,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -1578,7 +1578,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/typescript.md", - "file": "b8d3d3a7e1e287ce.md" + "file": "86a47920a4cf7abc.md" }, { "path": ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md", @@ -1768,11 +1768,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -1780,7 +1780,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -1958,11 +1958,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -1970,7 +1970,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2150,11 +2150,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -2162,7 +2162,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2346,11 +2346,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -2358,7 +2358,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2543,11 +2543,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -2555,7 +2555,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2744,11 +2744,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -2756,7 +2756,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2944,11 +2944,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -2956,7 +2956,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3136,11 +3136,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -3148,7 +3148,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3326,11 +3326,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -3338,7 +3338,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3516,11 +3516,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -3528,7 +3528,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3708,11 +3708,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -3720,7 +3720,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3904,11 +3904,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -3916,7 +3916,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4101,11 +4101,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -4113,7 +4113,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4302,11 +4302,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -4314,7 +4314,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4502,11 +4502,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -4514,7 +4514,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4694,11 +4694,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -4706,7 +4706,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4884,15 +4884,15 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "ce7130ca4922c867.md" + "file": "9965e221bf197a06.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5036,7 +5036,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "acf97bce8886e14c.md" + "file": "93ebe0549b1c81af.md" }, { "path": ".claude/skills/metaobjects-verify/SKILL.md", @@ -5074,15 +5074,15 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "ce7130ca4922c867.md" + "file": "9965e221bf197a06.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5226,7 +5226,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "acf97bce8886e14c.md" + "file": "93ebe0549b1c81af.md" }, { "path": ".claude/skills/metaobjects-verify/SKILL.md", @@ -5266,15 +5266,15 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "ce7130ca4922c867.md" + "file": "9965e221bf197a06.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5418,7 +5418,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "acf97bce8886e14c.md" + "file": "93ebe0549b1c81af.md" }, { "path": ".claude/skills/metaobjects-runtime-ui/references/react.md", @@ -5462,15 +5462,15 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "ce7130ca4922c867.md" + "file": "9965e221bf197a06.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5614,7 +5614,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "acf97bce8886e14c.md" + "file": "93ebe0549b1c81af.md" }, { "path": ".claude/skills/metaobjects-runtime-ui/references/react.md", @@ -5659,15 +5659,15 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "ce7130ca4922c867.md" + "file": "9965e221bf197a06.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5811,7 +5811,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "acf97bce8886e14c.md" + "file": "93ebe0549b1c81af.md" }, { "path": ".claude/skills/metaobjects-runtime-ui/references/react.md", @@ -5860,15 +5860,15 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "ce7130ca4922c867.md" + "file": "9965e221bf197a06.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6012,7 +6012,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "acf97bce8886e14c.md" + "file": "93ebe0549b1c81af.md" }, { "path": ".claude/skills/metaobjects-runtime-ui/references/react.md", @@ -6060,15 +6060,15 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "ce7130ca4922c867.md" + "file": "9965e221bf197a06.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6212,7 +6212,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "acf97bce8886e14c.md" + "file": "93ebe0549b1c81af.md" }, { "path": ".claude/skills/metaobjects-verify/SKILL.md", @@ -6252,15 +6252,15 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "ce7130ca4922c867.md" + "file": "9965e221bf197a06.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6404,7 +6404,7 @@ }, { "path": ".claude/skills/metaobjects-runtime-ui/references/csharp.md", - "file": "acf97bce8886e14c.md" + "file": "93ebe0549b1c81af.md" }, { "path": ".claude/skills/metaobjects-verify/SKILL.md", @@ -6442,11 +6442,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6458,7 +6458,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/python.md", - "file": "8e5978224add0b68.md" + "file": "1944176d5ab05889.md" }, { "path": ".claude/skills/metaobjects-audit/references/requirements.md", @@ -6632,11 +6632,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6648,7 +6648,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/python.md", - "file": "8e5978224add0b68.md" + "file": "1944176d5ab05889.md" }, { "path": ".claude/skills/metaobjects-audit/references/requirements.md", @@ -6824,11 +6824,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6840,7 +6840,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/python.md", - "file": "8e5978224add0b68.md" + "file": "1944176d5ab05889.md" }, { "path": ".claude/skills/metaobjects-audit/references/requirements.md", @@ -7020,11 +7020,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -7036,7 +7036,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/python.md", - "file": "8e5978224add0b68.md" + "file": "1944176d5ab05889.md" }, { "path": ".claude/skills/metaobjects-audit/references/requirements.md", @@ -7217,11 +7217,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -7233,7 +7233,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/python.md", - "file": "8e5978224add0b68.md" + "file": "1944176d5ab05889.md" }, { "path": ".claude/skills/metaobjects-audit/references/requirements.md", @@ -7418,11 +7418,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -7434,7 +7434,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/python.md", - "file": "8e5978224add0b68.md" + "file": "1944176d5ab05889.md" }, { "path": ".claude/skills/metaobjects-audit/references/requirements.md", @@ -7618,11 +7618,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -7634,7 +7634,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/python.md", - "file": "8e5978224add0b68.md" + "file": "1944176d5ab05889.md" }, { "path": ".claude/skills/metaobjects-audit/references/requirements.md", @@ -7810,11 +7810,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -7826,7 +7826,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/python.md", - "file": "8e5978224add0b68.md" + "file": "1944176d5ab05889.md" }, { "path": ".claude/skills/metaobjects-audit/references/requirements.md", @@ -8000,11 +8000,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -8170,11 +8170,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -8342,11 +8342,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -8518,11 +8518,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -8695,11 +8695,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -8876,11 +8876,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -9056,11 +9056,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -9228,11 +9228,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -9399,11 +9399,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -9411,11 +9411,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -9610,11 +9610,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -9622,11 +9622,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -9823,11 +9823,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -9835,11 +9835,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10040,11 +10040,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -10052,11 +10052,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10258,11 +10258,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -10270,11 +10270,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10480,11 +10480,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -10492,11 +10492,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10701,11 +10701,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -10713,11 +10713,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10914,11 +10914,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "a41cb586bdd98720.md" + "file": "bd42756bc33c3899.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "43a4f77d88acbd3b.md" + "file": "459fd71735a6bc90.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -10926,11 +10926,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "003a2dff540a3c7b.md" + "file": "ea613a5701fa6856.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "71f3aede2e59870d.md" + "file": "16283aaffb2211da.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md",