From c891e0c5c29776b6ea098f2ab4d9f3c6012089a5 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 12:39:37 -0500 Subject: [PATCH 1/6] feat(csharp): rules-names generator for the business-rules names (ADR-0067 layer 0) A layer generator, opt-in like any other. For each entity with a lifecycle it writes Rules.g.cs: each lifecycle field's states, initial and terminal states, transitions, and the permission each derived command asks the policy about. For each api.operational it writes Operations.g.cs: each operation's name, permission and @errors codes. RuleErrorCodes.g.cs holds the shell's own codes once. A model with no rules vocabulary gets no file. Permission names and which transitions derive a command come from the same derivation verify's rules gate runs (RulesCheck.CommandTransitions and the permission helpers, now public); the project's rules settings ride on the loaded root as WireFormat does. SHELL_ERROR_CODES is the single list RESERVED_ERROR_CODES now spreads. The flat generators are unchanged: RulesInertTests excludes the layer generators by name and keeps holding every flat one to identical output. The shared generator manifest gains rules-names (C# only for now). --- .claude/rules/cross-language-porting.md | 2 +- CHANGELOG.md | 10 + docs/features/business-rules.md | 12 +- docs/ports/csharp.md | 30 ++ .../registry.json | 7 + .../GenListAndSelectionTests.cs | 4 +- .../EjectContractTests.cs | 2 + .../EjectedGeneratorsAloneTests.cs | 8 + .../GeneratorRegistryTests.cs | 1 + .../RulesInertTests.cs | 17 +- .../RulesNamesGeneratorTests.cs | 205 +++++++++++++ .../MetaObjects.Codegen/GeneratorRegistry.cs | 10 + .../Generators/RulesNamesGenerator.cs | 288 ++++++++++++++++++ .../MetaObjects.Codegen.csproj | 1 + .../MetaObjects/Config/MetadataLocation.cs | 1 + .../MetaObjects/Core/Api/ApiConstants.cs | 8 +- .../MetaObjects/Core/Transition/RulesCheck.cs | 26 ++ server/csharp/MetaObjects/Meta/MetaRoot.cs | 6 + 18 files changed, 627 insertions(+), 11 deletions(-) create mode 100644 server/csharp/MetaObjects.Codegen.Tests/RulesNamesGeneratorTests.cs create mode 100644 server/csharp/MetaObjects.Codegen/Generators/RulesNamesGenerator.cs diff --git a/.claude/rules/cross-language-porting.md b/.claude/rules/cross-language-porting.md index e5222f1882..a49a4b733d 100644 --- a/.claude/rules/cross-language-porting.md +++ b/.claude/rules/cross-language-porting.md @@ -26,7 +26,7 @@ Preserve the following contracts exactly across all language ports: - Relationship subtypes: `association`, `aggregation`, `composition`. Cardinality via `@cardinality: one|many`; target via `@objectRef`. **M:N (FR-018) slim vocabulary:** `@cardinality: "many"` + `@objectRef` (target) + `@through` (the junction/through entity — a third entity that MUST declare two `identity.reference` children, one per FK side). The relationship's FK fields are **derived** from those references (the `identity.reference` SSOT for FK direction), never restated. `@sourceRefField` (optional) disambiguates a *directed* self-join by naming the source-side FK field on the junction (the other reference is the target side); on a `@cardinality: one` relationship it instead names which of several `identity.reference` nodes onto the same target this relationship navigates, short-circuiting the unique-candidate/`@sourceRefField`/name-pairing ladder (#368, [ADR-0029](spec/decisions/ADR-0029-entity-child-extends-and-via-inference.md) Amendment 1) — an unresolvable 1:N reference set is `ERR_INVALID_RELATIONSHIP` at load. `@symmetric` (optional boolean) marks an *undirected* self-join (union-on-read) — valid only when `@objectRef` == the declaring entity, and mutually exclusive with `@sourceRefField`. The pre-FR-018 `@joinEntity`/`@joinFields` attrs are REMOVED. Validation errors: symmetric-on-hetero / symmetric+sourceRefField → `ERR_BAD_ATTR_VALUE`; junction-missing-two-references / sourceRefField-not-matching / M:N-attr-on-1:N / **junction-unpairable** → `ERR_INVALID_RELATIONSHIP`. **Unpairable means the junction declares its two references but neither resolves to the navigating entity, or neither to the `@objectRef` target** — declaring two references is NOT enough, and the loader now checks WHAT they point at (owner ruling 2026-09-20). It does so by running the real FK derivation and converting its failure, never a parallel re-implementation, so the loader and the derivation cannot drift; scope mirrors codegen's own iteration exactly — every CONCRETE, non-projection object crossed with its EFFECTIVE relationships, NOT deduped by declaration, because pairing is a property of the navigating entity and an inherited M:N can pair from one subtype and not another. Before the ruling this loaded clean and then diverged: TS and C# warned and emitted no traversal route (a silent 404), while Java, Kotlin and Python failed the build. Gated by `fixtures/conformance/error-relationship-m2m-junction-unpairable/`. - Index subtypes: `index.lookup` (non-unique retrieval index; uniqueness is encoded in the **type**: `identity.secondary` = unique alternate key, `index.lookup` = non-unique; `@unique` is REMOVED from `identity.secondary` — `ERR_UNKNOWN_ATTR` on any legacy `@unique`). RDB-physical escapes `@using`/`@expr`/`@where`/`@orders` are registered by the db provider on **both** `identity.secondary` and `index.lookup`. `index.fulltext` / `index.vector` / `index.spatial` are reserved on the subtype axis — documented, NOT registered (YAGNI + 1.0 vocab freeze). See [ADR-0040](spec/decisions/ADR-0040-index-type-and-secondary-key-purity.md). - Layout subtypes: `dataGrid` -- API subtypes: `api.base` / `api.operational` (request/response surface, a root child; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `binding.rest` (`@method`, `@path`) now, `messaging`/`grpc` reserved; the event/streaming sibling of `api.operational` is reserved). Children: `operation.query` (`@outputRef`, `@many`) / `operation.command` (`@inputRef` → `object.value`, `@transitions`, `@errors`); both take `@inputRef`, `@outputRef`, `@objectRef` (only when the target cannot be derived), `@permission`, `@public`. Derived CRUD (FR-008/009) stays the zero-config default; declared `api` extends it. Org-tier modeling (application/service/network/deployment) stays OUT of core — provider SPI, FQN references. See [ADR-0030](spec/decisions/ADR-0030-declared-api-surface-and-org-tier-boundary.md). **Registered in all five ports since 1.3.0, experimental** (may change in a MINOR) ([ADR-0066](spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)), with the loader rules (`error-rules-*` fixtures) and the `verify` rules gate (`fixtures/rules-check-conformance/`); nothing is generated from it yet (`fixtures/codegen-noop/rules/`). +- API subtypes: `api.base` / `api.operational` (request/response surface, a root child; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `binding.rest` (`@method`, `@path`) now, `messaging`/`grpc` reserved; the event/streaming sibling of `api.operational` is reserved). Children: `operation.query` (`@outputRef`, `@many`) / `operation.command` (`@inputRef` → `object.value`, `@transitions`, `@errors`); both take `@inputRef`, `@outputRef`, `@objectRef` (only when the target cannot be derived), `@permission`, `@public`. Derived CRUD (FR-008/009) stays the zero-config default; declared `api` extends it. Org-tier modeling (application/service/network/deployment) stays OUT of core — provider SPI, FQN references. See [ADR-0030](spec/decisions/ADR-0030-declared-api-surface-and-org-tier-boundary.md). **Registered in all five ports since 1.3.0, experimental** (may change in a MINOR) ([ADR-0066](spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)), with the loader rules (`error-rules-*` fixtures) and the `verify` rules gate (`fixtures/rules-check-conformance/`); the flat generators generate nothing from it (`fixtures/codegen-noop/rules/`); the ADR-0067 layer generators do (C# `rules-names` so far). - Transition subtypes: `transition.action` (a child of `field.enum` on an `object.entity`: `@from`, `@to`, `@condition` in the validators' grammar, `@permission`, `@public`); `transition.base` is the abstract root and `transition.timed` is reserved, not registered. An enum with a transition IS a lifecycle — states, initial state (`@default`), terminal states and each unclaimed transition's command are derived, never declared (ADR-0066). A transition's `@from` lists enum members, not object references: every port's ref-bearing-attr check excludes `transition.*` nodes. A lifecycle belongs to the declaring entity and its `extends` descendants, NEVER to an entity whose field merely `extends` the lifecycle field (filter by the declaring field's owner); a command claims a transition NODE for its target and every entity extending it. Transition and operation names compare case-insensitively; operation names are unique per PACKAGE across its APIs, except one operation declared identically in two APIs (a versioned API). A lifecycle on an entity with no source loads and is inert (no derived command, no permission checks); the writable-source check applies once a source exists. A `@permission` is a dotted identifier path (a package prefix may use `::`); an absent one derives `.` for an operation and `..` for a transition's command. - Currency attrs: `@currency` (ISO 4217), `@locale` (BCP 47) - Schema attrs: `@schema` on `source.rdb` (DB schema name; Postgres default `public`, SQLite rejects non-default values) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f5a8c75c2..3a49cb1421 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,16 @@ here.** exactly the reference content is left alone and reported as identical, with or without `force`. The codegen fingerprint, `metaobjects:fmt` and `metaobjects:init` also compare before they write. +- **C#: a `rules-names` generator writes the business-rules names as constants (ADR-0067 layer 0).** + It is opt-in, like any generator: add `new RulesNamesGenerator()` to `codegen/Generators.cs`. For + each entity with a lifecycle it writes `Rules.g.cs`, with each lifecycle's states, initial + and terminal states, transitions, and the permission each derived command asks for. For each + `api.operational` it writes `Operations.g.cs`, with each operation's name, permission and + `@errors` codes. It also writes `RuleErrorCodes.g.cs` once, with the shell's own codes. Permission + names are derived the way `verify` derives them, and `rules.lifecycle.commands` decides which + transitions get one. A model with no rules vocabulary gets no file. It is a layer generator, so the + flat generators' output is unchanged and the codegen-noop rules corpus still holds them. The shared + generator manifest gains the `rules-names` entry (C# only for now). - **C#: a `@sequenceStart` whose migrations project lacks the design-time services line is a generation error.** When `dotnet meta gen` can see the context's `ModelSnapshot.cs` in another project and that project does not carry `[assembly: DesignTimeServicesReference]`, the next `dotnet ef migrations add` diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index e0071d6310..02a7d3bf9d 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -12,12 +12,14 @@ is needed, which moves are legal, and what a command may return, so all three ca **What 1.3.0 ships.** The vocabulary, checked when it loads and by `verify`, in all five ports. The Rust port loads the vocabulary and runs the same loader rules, and its `verify` runs the same rules gate, held to `fixtures/rules-check-conformance/` ([Rust port](../ports/rust.md)). -A requirement can claim an operation or a transition. Nothing is generated from the vocabulary -yet: the service shells that enforce these rules at run time are later work (ADR-0067): service -generators an app adds to its generator list, as it adds any generator. A lifecycle in a project +A requirement can claim an operation or a transition. The flat generators generate nothing from +the vocabulary. The layer generators of ADR-0067 do, and an app adds them to its generator list as +it adds any generator. The first is C#'s `rules-names`, which writes the states, transitions, +permissions and error codes as constants ([C# port](../ports/csharp.md)). The service shells that +enforce these rules at run time are later work. A lifecycle in a project that wires none will be advised by `verify` once that check lands; today the flat routes enforce -nothing and `verify` says nothing about it. Until the shells land, a model with this vocabulary -generates byte-identical code to the same model without it. The design is [ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md). +nothing and `verify` says nothing about it. Every flat generator writes byte-identical code for +a model with this vocabulary and the same model without it. The design is [ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md). **Experimental.** This vocabulary, its loader rules, its `verify` checks and its settings may change in a MINOR, including removals and renames, until generated services run on it in an diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 23ae646c0a..78328504f8 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -770,6 +770,36 @@ when the committed output was generated with another rule, rather than telling y regenerate. See the "Column naming" section of [`features/field-types.md`](../features/field-types.md). +### `rules-names` — the business-rules names, as constants + +The `rules-names` generator (`RulesNamesGenerator`) is ADR-0067's layer 0 for the business-rules +vocabulary ([business rules](../features/business-rules.md)). It writes nothing for a model that +declares no lifecycle and no operation. For one that does, it writes: + +- `Rules.g.cs` for each entity with a lifecycle. Each lifecycle field becomes a nested class + holding `Field`, `Initial` (the enum's `@default`), `TerminalStates` (the members no transition + leaves), `States`, `Transitions` and `Permissions`. `Permissions` maps each transition that + derives a command to the permission that command asks the policy about: its `@permission`, or the + derived `..`. A `@public` transition, and one a declared command + claims, has none. `rules.lifecycle.commands` decides which transitions derive a command, and + `verify`'s rules gate uses the same derivation. +- `Operations.g.cs` for each `api.operational`, with a nested class per operation holding + `Name`, `Permission` (absent when `@public`) and `Errors` (its `@errors` codes). +- `RuleErrorCodes.g.cs`, once per run, with the codes the enforcing shell answers on its own + (`not_found`, `forbidden`, `invalid_transition`, `transition_condition_failed`, `state_managed`). + +```csharp +if (!policy.Allows(user, PurchaseRequestRules.Status.Permissions.Submit)) return Results.Forbid(); +if (request.Status != PurchaseRequestRules.Status.States.Draft) return Conflict(RuleErrorCodes.InvalidTransition); +``` + +Every name is a `const string`, so it can stand in an attribute argument or a `switch` label, and +hand code that uses one stops compiling when the model renames it. Two names that fold to one C# +member (`in_review` and `inReview`) are refused, naming both. `Include` on the entry scopes it as +it does any generator: an entity's file follows the entity, and an API's file follows its package. +This is a layer generator, separate from the flat ones (ADR-0067 §5), so adding it changes no +other generator's output. + ### Report export A served report (a view-backed `object.report`) can be downloaded as a file: diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index 662d716c5e..ccdf349ec9 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -104,6 +104,13 @@ "eject": "full", "ports": ["typescript", "csharp", "kotlin", "python", "java"] }, + "rules-names": { + "concept": "Business-rules name constants (ADR-0067 layer 0): each lifecycle's states, initial and terminal states and transitions, the permission each derived command and each operation asks for, and the error codes. A layer generator: it acts on the rules vocabulary, so the codegen-noop rules corpus does not hold it.", + "tier": "native", + "layer": "model", + "eject": "full", + "ports": ["csharp"] + }, "prompt-render": { "concept": "Per-template.prompt render handle over the render engine, aggregated into one module. TYPESCRIPT ONLY by design: the other four ports emit a prompt's render helper from `render-helper` (see its note) rather than a second generator.", "tier": "native", diff --git a/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs index 3f8949d822..bc04c0b3de 100644 --- a/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs @@ -47,7 +47,7 @@ public void ListHeader_says_generators_are_owned_via_eject() public void ListLines_prints_all_generators_with_stable_names_and_descriptions() { var lines = GenCommand.ListLines(_tmp); - Assert.Equal(16, lines.Count); + Assert.Equal(17, lines.Count); foreach (var name in new[] { "entity", "db-context", "routes", "output-parser", "extractor", @@ -56,6 +56,8 @@ public void ListLines_prints_all_generators_with_stable_names_and_descriptions() "callable", // Program A / §A5 — per-object physical database name constants. "names", + // ADR-0067 layer 0 — the business-rules names (states, transitions, permissions, errors). + "rules-names", // ADR-0057 — per-requirement xUnit tests calling a project-owned witness. "requirement-tests", "report-export", diff --git a/server/csharp/MetaObjects.Codegen.Tests/EjectContractTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EjectContractTests.cs index 09ff7bbb7b..53ebac321a 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EjectContractTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EjectContractTests.cs @@ -243,6 +243,8 @@ MetaRoot Directory(params string[] segments) new("stored-proc", Directory("conformance", "parameter-ref-on-stored-proc", "input"), null), // An @expr index: expression-indexes emits only over one. new("expression-indexes", InlineModel(ExpressionIndexesGeneratorTests.Model), null), + // A lifecycle and an api.operational: rules-names emits only over them. + new("rules", Directory("codegen-noop", "rules", "with"), null), // A reply with a nested object: the extractor emits only over one. new("nested-reply", Directory("template-output-render-conformance", "xpkg-collision-json"), Path.Combine(CorpusPaths.RepoRoot(), "fixtures", "template-output-render-conformance", "templates")), diff --git a/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs index f7f331e203..51d0bc3bdb 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EjectedGeneratorsAloneTests.cs @@ -281,6 +281,14 @@ private static MetaRoot LoadInline(string model, string id) // `expression-indexes` emits only for an @expr index, which neither shared corpus has. if (generator is "expression-indexes") yield return ("expression-indexes", LoadInline(ExpressionIndexesGeneratorTests.Model, "expr.json")); + // `rules-names` emits only for a lifecycle or an api.operational, which neither shared corpus has. + if (generator is "rules-names") + { + var rules = MetaDataLoader.FromDirectory( + Path.Combine(CorpusPaths.RepoRoot(), "fixtures", "codegen-noop", "rules", "with"), strict: true); + Assert.Empty(rules.Errors.Select(e => e.Code + ": " + e.Message)); + yield return ("rules", rules.Root); + } yield return ("fitness", EjectedGeneratorCompileTests.LoadCorpus()); var worked = MetaDataLoader.FromDirectory( Path.Combine(CorpusPaths.RepoRoot(), "fixtures", "requirement-test-identity-conformance", "worked-example", "input"), strict: true); diff --git a/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs index c86309703f..a28b0abd3d 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs @@ -22,6 +22,7 @@ public sealed class GeneratorRegistryTests "callable", // Program A / §A5 — per-object physical database name constants. "names", + "rules-names", // The @expr indexes the EF model cannot carry, as SQL (C#-only). "expression-indexes", // ADR-0057 — per-requirement xUnit tests calling a project-owned witness. diff --git a/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs b/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs index 3a9b696868..fc4e23e6ff 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/RulesInertTests.cs @@ -64,13 +64,24 @@ private static SortedDictionary Emit(MetaRoot root, IReadOnlyLis return files; } + /// + /// The layer generators (ADR-0067 §5.2). They act on the rules vocabulary by design, so they are not held + /// to identical output; the flat generators they sit beside are, and that is what this test guards. + /// Pinned by name so a flat generator cannot be excused by being added here. + /// + private static readonly HashSet LayerGenerators = new(StringComparer.Ordinal) { "rules-names" }; + + /// The registry's flat generators: every entry but the layer ones. + private static IEnumerable> Flat() => + GeneratorRegistry.Entries.Where(e => !LayerGenerators.Contains(e.Key)); + private static IGenerator Build(GeneratorRegistryEntry entry) => entry.Factory(new GeneratorBuildContext(CorpusPaths.FitnessTemplateRoot)); public static TheoryData GeneratorNames() { var data = new TheoryData(); - foreach (var name in GeneratorRegistry.Entries.Keys.Where(n => n != SharedModelTestSupport.Name)) data.Add(name); + foreach (var name in Flat().Select(e => e.Key).Where(n => n != SharedModelTestSupport.Name)) data.Add(name); return data; } @@ -110,7 +121,7 @@ public void Exactly_these_generators_cannot_run_from_a_bare_model() { // Each is compared above on its error message alone, which proves nothing about its // output. Pinned by name so a generator that starts throwing cannot drop out silently. - var threw = GeneratorRegistry.Entries + var threw = Flat() .Where(e => Emit(Load("without"), [Build(e.Value)]).ContainsKey("")) .Select(e => e.Key) .OrderBy(n => n, StringComparer.Ordinal) @@ -121,7 +132,7 @@ public void Exactly_these_generators_cannot_run_from_a_bare_model() [Fact] public void Every_runnable_generator_in_one_run_emits_the_same_files() { - var runnable = GeneratorRegistry.Entries + var runnable = Flat() .Where(e => !Emit(Load("without"), [Build(e.Value)]).ContainsKey("")) .ToList(); var expected = Emit(Load("without"), runnable.Select(e => Build(e.Value)).ToList()); diff --git a/server/csharp/MetaObjects.Codegen.Tests/RulesNamesGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/RulesNamesGeneratorTests.cs new file mode 100644 index 0000000000..3c56ee16c4 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/RulesNamesGeneratorTests.cs @@ -0,0 +1,205 @@ +// ADR-0067 layer 0, the business-rules half: the rules-names generator. +// +// The model is fixtures/codegen-noop/rules/with, the corpus every port's inert test already +// loads. The expected names come from ADR-0066, not from the generator: the lifecycle's states +// are the enum's @values, its initial state the @default, its terminal states the members no +// transition leaves; a transition that a declared command claims derives no command of its own +// under `rules.lifecycle.commands: unclaimed`; an absent @permission derives +// `..` or `.`, and a @public node asks for none. +// +// Each test compiles the emitted files with Roslyn, loads the assembly and reads the constants +// back, so what is checked is what a consumer's code would see. + +using System.Reflection; +using MetaObjects.Codegen.Generators; +using MetaObjects.Config; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class RulesNamesGeneratorTests +{ + private const string Ns = "Acme.Rules"; + + private static MetaRoot Load(string variant = "with") + { + var path = Path.Combine(CorpusPaths.RepoRoot(), "fixtures", "codegen-noop", "rules", variant, "meta.purchasing.json"); + var result = new MetaDataLoader().Load([new FileSource(path)]); + Assert.True(result.Errors.Count == 0, string.Join("\n", result.Errors.Select(e => $"{e.Code}: {e.Message}"))); + return result.Root; + } + + private static GenContext Ctx(MetaRoot root) => new() + { + Entities = root.Objects(), + Root = root, + Config = new GenConfig { OutDir = "/unused", Namespace = Ns }, + }; + + private static IReadOnlyList Emit(MetaRoot root, RulesNamesGenerator? gen = null) => + (gen ?? new RulesNamesGenerator()).Generate(Ctx(root)).ToList(); + + /// Compile the files and load them; a compile error fails the test with the diagnostics. + private static Assembly Compile(IEnumerable files) + { + var trees = files.Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12))); + var comp = CSharpCompilation.Create("rules_names_" + Guid.NewGuid().ToString("N"), trees, + DbContextCompileTests.BuildReferences(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + using var ms = new MemoryStream(); + var result = comp.Emit(ms); + Assert.True(result.Success, string.Join("\n", result.Diagnostics + .Where(d => d.Severity == DiagnosticSeverity.Error).Select(d => $"{d.Id}: {d.GetMessage()}"))); + return Assembly.Load(ms.ToArray()); + } + + private static Type Nested(Assembly asm, string path) + { + var parts = path.Split('+'); + var type = asm.GetType($"{Ns}.{parts[0]}") ?? throw new Xunit.Sdk.XunitException($"no type {Ns}.{parts[0]}"); + foreach (var p in parts.Skip(1)) + type = type.GetNestedType(p) ?? throw new Xunit.Sdk.XunitException($"no nested type {p} in {type.FullName}"); + return type; + } + + /// A class's const string members, member name to value, in declaration order. + private static List<(string Name, string Value)> Consts(Type type) => + type.GetFields(BindingFlags.Public | BindingFlags.Static) + .Where(f => f.IsLiteral) + .OrderBy(f => f.MetadataToken) + .Select(f => (f.Name, (string)f.GetRawConstantValue()!)).ToList(); + + private static string? Const(Type type, string name) => + type.GetField(name, BindingFlags.Public | BindingFlags.Static)?.GetRawConstantValue() as string; + + [Fact] + public void The_lifecycle_names_are_the_enums_states_and_transitions() + { + var asm = Compile(Emit(Load())); + var status = Nested(asm, "PurchaseRequestRules+Status"); + + Assert.Equal("status", Const(status, "Field")); + Assert.Equal("draft", Const(status, "Initial")); + Assert.Equal(["approved", "rejected"], + (IReadOnlyList)status.GetField("TerminalStates")!.GetValue(null)!); + Assert.Equal( + [("Draft", "draft"), ("Submitted", "submitted"), ("Approved", "approved"), ("Rejected", "rejected")], + Consts(Nested(asm, "PurchaseRequestRules+Status+States"))); + Assert.Equal( + [("Submit", "submit"), ("Approve", "approve"), ("Reject", "reject")], + Consts(Nested(asm, "PurchaseRequestRules+Status+Transitions"))); + } + + [Fact] + public void Only_a_transition_that_derives_a_command_gets_a_permission() + { + // `decide` claims approve and reject, so under the default only submit derives a command, + // and it declares no @permission: the derived name. + var asm = Compile(Emit(Load())); + Assert.Equal([("Submit", "acme::purchasing.PurchaseRequest.submit")], + Consts(Nested(asm, "PurchaseRequestRules+Status+Permissions"))); + } + + [Fact] + public void Commands_all_gives_every_transition_its_permission_declared_or_derived() + { + var root = Load(); + root.Rules = RulesSettings.Default with { LifecycleCommands = "all" }; + var asm = Compile(Emit(root)); + Assert.Equal( + [ + ("Submit", "acme::purchasing.PurchaseRequest.submit"), + ("Approve", "acme::purchasing.PurchaseRequest.approve"), + ("Reject", "purchasing.review"), + ], + Consts(Nested(asm, "PurchaseRequestRules+Status+Permissions"))); + } + + [Fact] + public void Commands_none_derives_no_command_so_no_permission() + { + var root = Load(); + root.Rules = RulesSettings.Default with { LifecycleCommands = "none" }; + var asm = Compile(Emit(root)); + Assert.Null(Nested(asm, "PurchaseRequestRules+Status").GetNestedType("Permissions")); + // The states and transitions do not depend on the setting. + Assert.Equal(3, Consts(Nested(asm, "PurchaseRequestRules+Status+Transitions")).Count); + } + + [Fact] + public void Each_operation_carries_its_name_permission_and_errors() + { + var asm = Compile(Emit(Load())); + + var decide = Nested(asm, "PurchasingOperations+Decide"); + Assert.Equal("decide", Const(decide, "Name")); + Assert.Equal("purchasing.decide", Const(decide, "Permission")); + Assert.Equal([("OverBudget", "over_budget"), ("AlreadyDecided", "already_decided")], + Consts(Nested(asm, "PurchasingOperations+Decide+Errors"))); + + var summary = Nested(asm, "PurchasingOperations+RequestSummary"); + Assert.Equal("acme::purchasing.requestSummary", Const(summary, "Permission")); + Assert.Null(summary.GetNestedType("Errors")); + + // @public: nothing to ask the policy. + var open = Nested(asm, "PurchasingOperations+OpenRequests"); + Assert.Equal("openRequests", Const(open, "Name")); + Assert.Null(Const(open, "Permission")); + } + + [Fact] + public void The_shells_own_codes_are_written_once() + { + var asm = Compile(Emit(Load())); + Assert.Equal( + [ + ("NotFound", "not_found"), ("Forbidden", "forbidden"), ("InvalidTransition", "invalid_transition"), + ("TransitionConditionFailed", "transition_condition_failed"), ("StateManaged", "state_managed"), + ], + Consts(Nested(asm, "RuleErrorCodes"))); + } + + [Fact] + public void A_model_with_no_rules_vocabulary_gets_no_file() + { + Assert.Empty(Emit(Load("without"))); + } + + [Fact] + public void Include_scopes_the_entity_and_its_packages_operations() + { + var none = new RulesNamesGenerator { Include = o => o.Name == "NoSuchObject" }; + Assert.Empty(Emit(Load(), none)); + + var paths = Emit(Load(), new RulesNamesGenerator { Include = o => o.Name == "PurchaseRequest" }) + .Select(f => f.Path).Order(StringComparer.Ordinal).ToList(); + Assert.Equal(["PurchaseRequestRules.g.cs", "PurchasingOperations.g.cs", "RuleErrorCodes.g.cs"], paths); + } + + [Fact] + public void Two_names_folding_to_one_member_are_refused_naming_both() + { + var load = new MetaDataLoader().Load([new InMemoryStringSource(""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Ticket", "children": [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "field.enum": { "name": "status", "@values": ["open", "in_review", "inReview"], "@default": "open", "@normalize": "none", + "children": [ + { "transition.action": { "name": "review", "@from": ["open"], "@to": "in_review" } }, + { "transition.action": { "name": "hold", "@from": ["in_review"], "@to": "inReview" } } + ] } } + ] } } + ] } } + """)]); + Assert.Empty(load.Errors); + var e = Assert.Throws(() => Emit(load.Root)); + Assert.Contains("state \"in_review\"", e.Message); + Assert.Contains("state \"inReview\"", e.Message); + Assert.Contains("\"InReview\"", e.Message); + } +} diff --git a/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs b/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs index 12124b5a1a..e291a68c75 100644 --- a/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs +++ b/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs @@ -261,6 +261,16 @@ private static IGenerator RenderHelper(GeneratorBuildContext ctx) => Factory = _ => new NamesGenerator(), SourceFileName = "NamesGenerator.cs", }, + // ADR-0067 layer 0, the business-rules half: a layer generator, separate from the flat ones. + ["rules-names"] = new() + { + Name = "rules-names", + Description = "Business-rules name constants: lifecycle states, transitions, permissions and error codes (ADR-0066).", + Tier = GeneratorTier.Native, + Layer = GeneratorLayer.Model, + Factory = _ => new RulesNamesGenerator(), + SourceFileName = "RulesNamesGenerator.cs", + }, // The indexes the EF model cannot carry (an @expr key), as one SQL file to apply after the // schema EF builds. C#-only: meta migrate writes them into its own DDL. ["expression-indexes"] = new() diff --git a/server/csharp/MetaObjects.Codegen/Generators/RulesNamesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RulesNamesGenerator.cs new file mode 100644 index 0000000000..d48755269b --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Generators/RulesNamesGenerator.cs @@ -0,0 +1,288 @@ +// rules-names-generator — ADR-0067 layer 0, the business-rules half: compile-time constants for +// every state, transition, permission and error the model declares or derives (ADR-0066), so hand +// code that names one stops compiling when the model renames it. +// +// Three kinds of file, each only when the model has something to put in it: +// +// Rules.g.cs one per in-scope object.entity with a lifecycle: a nested class per +// lifecycle field holding its states, initial state, terminal states, +// transitions and, for each transition that derives a command, the +// permission that command asks the policy about. +// Operations.g.cs one per api.operational: a nested class per operation holding its +// name, its permission and its declared @errors codes. +// RuleErrorCodes.g.cs once per run: the codes the enforcing shell answers on its own. +// +// Everything here is DERIVED through the same code `verify`'s rules gate runs +// (MetaObjects.Core.Transition), so a permission name codegen writes is the one `verify` reports. +// A permission is absent for a @public command or operation: there is nothing to ask the policy. +// +// A layer generator, separate from the flat ones (ADR-0067 §5.2): it acts on the rules vocabulary +// by design, so fixtures/codegen-noop/rules/ does not hold it to identical output. +// +// const, not static readonly, for every single name, so a constant can stand in an attribute +// argument or a switch label; the terminal-state list is the one collection, and a collection +// cannot be const. + +using MetaObjects.Codegen.Writer; +using MetaObjects.Config; +using MetaObjects.Core.Transition; +using MetaObjects.Meta; +using static MetaObjects.Core.Api.ApiConstants; +using static MetaObjects.Shared.BaseTypes; + +namespace MetaObjects.Codegen.Generators; + +/// Generates the business-rules name constants: states, transitions, permissions and errors. +public class RulesNamesGenerator : IGenerator +{ + public virtual string Name => "rules-names"; + + /// + /// Scope this entry to some objects (set on the entry in codegen/Generators.cs). An entity's + /// file is written when it accepts the entity; an API's when it accepts at least one object of the + /// API's package, so a package-level choice covers that package's operations too. null + /// accepts everything. + /// + public Func? Include { get; init; } + + public virtual IEnumerable Generate(GenContext ctx) + { + var narrowed = ctx.Narrow(Include); + var settings = ctx.Root.Rules; + var files = new List(); + + foreach (var entity in narrowed.Entities) + { + if (Lifecycles.LifecyclesOf(entity).Count == 0) continue; + if (RenderEntity(entity, ctx, settings) is { } file) files.Add(file); + } + + var packages = narrowed.Entities + .Select(e => PackageBindingResolver.EffectivePackage(e) ?? "") + .ToHashSet(StringComparer.Ordinal); + foreach (var api in Apis(ctx.Root)) + { + if (Include is not null && !packages.Contains(PackageBindingResolver.EffectivePackage(api) ?? "")) continue; + if (Operations(api).Count == 0) continue; + if (RenderApi(api, ctx) is { } file) files.Add(file); + } + + // The shell codes are written once the run wrote anything else: a model with no lifecycle and no + // operation gets no file at all. + if (files.Count > 0 && RenderShellErrors(ctx) is { } shell) files.Add(shell); + return files; + } + + /// The in-scope api.operational nodes of the model, in model order. + protected static IReadOnlyList Apis(MetaRoot root) => + root.Children().Where(c => c.Type == TYPE_API && c.SubType == API_SUBTYPE_OPERATIONAL + && (root.ImportScope?.InScope(c.ResolutionKey()) ?? true)).ToList(); + + /// The operations of an API, in declaration order. + protected static IReadOnlyList Operations(MetaData api) => + api.Children().Where(c => c.Type == TYPE_OPERATION).ToList(); + + // ---- the entity file ------------------------------------------------------------------------ + + /// The <Entity>Rules.g.cs file of an entity with at least one lifecycle. + /// Override to adjust it, or to answer null for an entity whose names an adopter supplies itself. + protected virtual EmittedFile? RenderEntity(MetaObject entity, GenContext ctx, RulesSettings settings) + { + var cls = CSharpNaming.Pascal(entity.Name) + "Rules"; + var ns = Namespace(ctx, entity, cls); + var commands = new HashSet(RulesCheck.CommandTransitions(ctx.Root, settings, entity), ReferenceEqualityComparer.Instance); + + var w = NewWriter(); + WriteFileHeader(w); + w.Blank(); + w.Line($"namespace {ns};"); + w.Blank(); + w.DocSummary($"GENERATED — the lifecycle names of {CSharpNaming.Pascal(entity.Name)}: states, transitions and the permissions its derived commands ask for (ADR-0066)."); + using (w.Braced($"public static class {cls}")) + { + var lifecycleClasses = new Members(entity.Name + " lifecycles"); + var first = true; + foreach (var l in Lifecycles.LifecyclesOf(entity)) + { + if (!first) w.Blank(); + first = false; + WriteLifecycle(w, entity, l, commands, lifecycleClasses.Add(Ident(l.Field.Name), $"field \"{l.Field.Name}\"")); + } + } + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}.g.cs"), w.ToString()); + } + + /// One lifecycle field as a nested class. + protected virtual void WriteLifecycle(CsWriter w, MetaObject entity, Lifecycle l, IReadOnlySet commands, string cls) + { + var where = $"{entity.Name}.{l.Field.Name}"; + w.DocSummary($"The lifecycle held in field \"{l.Field.Name}\"."); + using (w.Braced($"public static class {cls}")) + { + Const(w, "Field", l.Field.Name); + if (l.Initial is { } initial) + { + w.DocSummary("The state a new row starts in: the enum's @default."); + Const(w, "Initial", initial); + } + w.DocSummary("The states no transition leaves."); + w.Line("public static readonly System.Collections.Generic.IReadOnlyList TerminalStates = " + + $"[{string.Join(", ", Lifecycles.TerminalStates(l).Select(Literal))}];"); + w.Blank(); + + WriteGroup(w, "States", "The lifecycle's states: the enum's @values.", $"{where} states", + l.States.Select(s => (s, $"state \"{s}\""))); + w.Blank(); + WriteGroup(w, "Transitions", "The lifecycle's transitions.", $"{where} transitions", + l.Transitions.Select(t => (t.Name, $"transition \"{t.Name}\""))); + + var permissions = l.Transitions + .Where(commands.Contains) + .Select(t => (Transition: t, Permission: RulesCheck.TransitionCommandPermission(entity, t))) + .Where(p => p.Permission is not null) + .ToList(); + if (permissions.Count > 0) + { + w.Blank(); + var members = new Members($"{where} permissions"); + w.DocSummary("The permission each derived command asks the policy about, by transition. A @public " + + "transition, and one a declared command makes, has none."); + using (w.Braced("public static class Permissions")) + { + foreach (var (t, permission) in permissions) + Const(w, members.Add(Ident(t.Name), $"transition \"{t.Name}\""), permission!); + } + } + } + } + + // ---- the API file --------------------------------------------------------------------------- + + /// The <Api>Operations.g.cs file of an api.operational. + protected virtual EmittedFile? RenderApi(MetaData api, GenContext ctx) + { + var cls = CSharpNaming.Pascal(api.Name) + "Operations"; + var ns = Namespace(ctx, api, cls); + + var w = NewWriter(); + WriteFileHeader(w); + w.Blank(); + w.Line($"namespace {ns};"); + w.Blank(); + w.DocSummary($"GENERATED — the operations of API \"{api.Name}\": each one's name, permission and declared error codes (ADR-0066)."); + using (w.Braced($"public static class {cls}")) + { + var members = new Members($"api \"{api.Name}\" operations"); + var first = true; + foreach (var op in Operations(api)) + { + if (!first) w.Blank(); + first = false; + WriteOperation(w, op, members.Add(Ident(op.Name), $"operation \"{op.Name}\"")); + } + } + return new EmittedFile(OutputPaths.Of(api, ctx, $"{cls}.g.cs"), w.ToString()); + } + + /// One operation as a nested class. + protected virtual void WriteOperation(CsWriter w, MetaData op, string cls) + { + w.DocSummary($"operation.{op.SubType} \"{op.Name}\"."); + using (w.Braced($"public static class {cls}")) + { + Const(w, "Name", op.Name); + if (RulesCheck.OperationPermission(op) is { } permission) + { + w.DocSummary("The permission the operation asks the policy about."); + Const(w, "Permission", permission); + } + var errors = Lifecycles.StringList(op, OPERATION_ATTR_ERRORS); + if (errors.Count > 0) + { + w.Blank(); + WriteGroup(w, "Errors", "The business error codes a body may refuse with: the operation's @errors.", + $"operation \"{op.Name}\" errors", errors.Select(e => (e, $"error \"{e}\""))); + } + } + } + + // ---- the shell's codes ---------------------------------------------------------------------- + + /// The run-wide RuleErrorCodes.g.cs file, in the run's root namespace. + protected virtual EmittedFile? RenderShellErrors(GenContext ctx) + { + const string cls = "RuleErrorCodes"; + var w = NewWriter(); + WriteFileHeader(w); + w.Blank(); + w.Line($"namespace {ctx.Config.Namespace};"); + w.Blank(); + w.DocSummary("GENERATED — the wire error codes the enforcing shell answers on its own (ADR-0066 §6). " + + "A declared @errors code may not be one of these."); + using (w.Braced($"public static class {cls}")) + { + var members = new Members("shell error codes"); + foreach (var code in SHELL_ERROR_CODES) Const(w, members.Add(Ident(code), $"error \"{code}\""), code); + } + return new EmittedFile(cls + ".g.cs", w.ToString()); + } + + // ---- pieces --------------------------------------------------------------------------------- + // One overridable method each (ADR-0063 item 7). Not a stability contract. + + /// The writer the file is written on. + protected virtual CsWriter NewWriter() => new(); + + /// The generated-file marker and the nullable context. + protected virtual void WriteFileHeader(CsWriter w) => w.GeneratedFileHeader("rules-names-generator"); + + /// The namespace a node's file is written in: its package's binding, claimed for the class. + protected virtual string Namespace(GenContext ctx, MetaData node, string cls) + { + var ns = PackageBindingResolver.Resolve(ctx.Config, PackageBindingResolver.EffectivePackage(node), node.Name, fallbackContext: node.Name); + ctx.Claim($"the C# namespace {ns}", cls, node.ResolutionKey(), + "map the packages to distinct namespaces (csharp.packageNamespaces, or GenConfig.PackageNamespaces), or rename one"); + return ns; + } + + private static void WriteGroup(CsWriter w, string cls, string doc, string scope, IEnumerable<(string Value, string Node)> values) + { + var members = new Members(scope); + w.DocSummary(doc); + using (w.Braced($"public static class {cls}")) + { + foreach (var (value, node) in values) Const(w, members.Add(Ident(value), node), value); + } + } + + private static void Const(CsWriter w, string name, string value) => + w.Line($"public const string {name} = {Literal(value)};"); + + private static string Literal(string value) => $"\"{CSharpNaming.CSharpStringLiteral(value)}\""; + + /// The C# member a metadata name becomes: over_budget → OverBudget, + /// draft → Draft. A leading digit, which no rules name can start with today, is guarded. + protected static string Ident(string name) + { + var token = CSharpNaming.PascalToken(name); + return char.IsDigit(token[0]) ? "_" + token : token; + } + + /// + /// The members of one class, so two metadata names that fold to one C# member (in_review and + /// inReview) are refused naming both, instead of a file that does not compile. + /// + private sealed class Members(string scope) + { + private readonly Dictionary _seen = new(StringComparer.Ordinal); + + public string Add(string member, string node) + { + if (_seen.TryGetValue(member, out var first)) + throw new InvalidOperationException( + $"rules-names: {scope}: {first} and {node} both become the C# member \"{member}\". Rename one."); + _seen[member] = node; + return member; + } + } +} diff --git a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj index bf9cdad1ce..69052c7224 100644 --- a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj +++ b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj @@ -55,6 +55,7 @@ + diff --git a/server/csharp/MetaObjects/Config/MetadataLocation.cs b/server/csharp/MetaObjects/Config/MetadataLocation.cs index c044659352..ef2f0cca99 100644 --- a/server/csharp/MetaObjects/Config/MetadataLocation.cs +++ b/server/csharp/MetaObjects/Config/MetadataLocation.cs @@ -79,6 +79,7 @@ public LoadResult Load(bool strict = false) result.Root.WireFormat = Wire ?? WireFormat.Default; result.Root.Api = Api ?? ApiSettings.Default; result.Root.EnumDefaults = Enums ?? EnumDefaults.Default; + result.Root.Rules = Rules ?? RulesSettings.Default; if (Imports is null) return result; result.Root.ImportScope = Imports; diff --git a/server/csharp/MetaObjects/Core/Api/ApiConstants.cs b/server/csharp/MetaObjects/Core/Api/ApiConstants.cs index 909ab5a287..5ac913fcba 100644 --- a/server/csharp/MetaObjects/Core/Api/ApiConstants.cs +++ b/server/csharp/MetaObjects/Core/Api/ApiConstants.cs @@ -55,11 +55,17 @@ public static partial class ApiConstants public static readonly Regex BUSINESS_ERROR_CODE_PATTERN = new(@"^[a-z][a-z0-9]*(_[a-z0-9]+)*\z", RegexOptions.CultureInvariant); + /// The codes the enforcing shell answers on its own (ADR-0066 §6), in the order it checks them. + /// The rules-names generator writes them as constants. + public static readonly string[] SHELL_ERROR_CODES = + ["not_found", "forbidden", "invalid_transition", "transition_condition_failed", "state_managed"]; + + // Declared after SHELL_ERROR_CODES: static initializers run in textual order. /// Wire error codes an operation's route answers on its own, so a body may not declare them /// in @errors (O5): the enforcing shell's codes (ADR-0066) and the API contract's generic ones. public static readonly string[] RESERVED_ERROR_CODES = [ - "not_found", "forbidden", "invalid_transition", "transition_condition_failed", "state_managed", + .. SHELL_ERROR_CODES, "validation", "invalid_json", "invalid_id", "method_not_allowed", "constraint_violation", "internal", ]; } diff --git a/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs b/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs index d05970c8f7..06b922a570 100644 --- a/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs +++ b/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs @@ -258,6 +258,32 @@ private static void CheckPermissionNames(MetaData root, RulesSettings settings, } } + /// + /// The transitions of that derive a command of their own under + /// rules.lifecycle.commands, in effective field order. Empty for an abstract entity and for one + /// with no source, whose lifecycles are inert. The same derivation the permission-name check uses, so + /// codegen and verify agree on which commands exist. + /// + public static IReadOnlyList CommandTransitions(MetaData root, RulesSettings settings, MetaData entity) + { + if (settings.LifecycleCommands == "none" || entity.IsAbstract || !Lifecycles.LifecycleIsLive(entity)) return []; + var claimed = ClaimedTransitions(root); + return Lifecycles.EntityTransitions(entity).Where(t => DerivesCommand(claimed, settings, entity, t)).ToList(); + } + + /// The permission a transition's derived command asks the policy about: its @permission, + /// else <package>.<Entity>.<transition>. Null when it is @public. + public static string? TransitionCommandPermission(MetaData entity, MetaData transition) => + PermissionOf(transition, entity, $"{entity.Name}.{transition.Name}"); + + /// The permission an operation asks the policy about: its @permission, else + /// <package>.<operation>. Null when it is @public. + public static string? OperationPermission(MetaData op) => PermissionOf(op, op, op.Name); + + private static string? PermissionOf(MetaData node, MetaData owner, string path) => + node.Attr(OPERATION_ATTR_PUBLIC) is true ? null + : node.Attr(OPERATION_ATTR_PERMISSION) as string ?? DerivedPermissionName(owner, path); + /// The rules gate over a loaded model. public static RulesCheckResult Check(MetaData root, RulesSettings settings) { diff --git a/server/csharp/MetaObjects/Meta/MetaRoot.cs b/server/csharp/MetaObjects/Meta/MetaRoot.cs index 84a66e2bf2..f7280534fe 100644 --- a/server/csharp/MetaObjects/Meta/MetaRoot.cs +++ b/server/csharp/MetaObjects/Meta/MetaRoot.cs @@ -31,6 +31,12 @@ public class MetaRoot(TypeId typeId, string name) : MetaData(typeId, name) /// project-aware load as and read by codegen through . public ApiSettings Api { get; set; } = ApiSettings.Default; + /// ADR-0066 — the project's business-rules settings (rules and verify in + /// .metaobjects/config.json), set by the same project-aware load as . + /// Codegen reads rules.lifecycle.commands from here to know which transitions derive a + /// command. A tree loaded with no project keeps every default. + public MetaObjects.Config.RulesSettings Rules { get; set; } = MetaObjects.Config.RulesSettings.Default; + /// /// The project's enum storage defaults (enums in .metaobjects/config.json), set by /// the same project-aware load as and read through From f0486de1e0ffae081444b8ba29260b4d29283875 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 12:58:53 -0500 Subject: [PATCH 2/6] feat(csharp): contract-types generator for the create and update records (ADR-0067 layer 1) Each writable entity gets Create and Update sealed records with the entity's validation attributes and wire converters. Server-owned members (generated key, autoSet stamp, readOnly and derived fields, TPH discriminator) are on neither; keys are off the update record. Update.From records which keys a body carried, so an omitted member and an explicit null stay apart, and Validate refuses null on a required member. The lifecycle field stays so the service shell can refuse it with 409 state_managed. The validation and converter attribute writers move out of EntityGenerator into ContractMembers, an eject companion of both generators; the entity's output is unchanged. --- .claude/rules/cross-language-porting.md | 2 +- CHANGELOG.md | 13 + docs/features/business-rules.md | 5 +- docs/ports/csharp.md | 30 ++ .../registry.json | 7 + .../GenListAndSelectionTests.cs | 4 +- .../ContractTypesGeneratorTests.cs | 200 +++++++++++++ .../GeneratorRegistryTests.cs | 1 + .../MetaObjects.Codegen/GeneratorRegistry.cs | 15 +- .../Generators/ContractMembers.cs | 263 ++++++++++++++++ .../Generators/ContractTypesGenerator.cs | 255 ++++++++++++++++ .../Generators/EntityGenerator.cs | 280 ++---------------- .../MetaObjects.Codegen.csproj | 2 + 13 files changed, 819 insertions(+), 258 deletions(-) create mode 100644 server/csharp/MetaObjects.Codegen.Tests/ContractTypesGeneratorTests.cs create mode 100644 server/csharp/MetaObjects.Codegen/Generators/ContractMembers.cs create mode 100644 server/csharp/MetaObjects.Codegen/Generators/ContractTypesGenerator.cs diff --git a/.claude/rules/cross-language-porting.md b/.claude/rules/cross-language-porting.md index a49a4b733d..c2ae2489a4 100644 --- a/.claude/rules/cross-language-porting.md +++ b/.claude/rules/cross-language-porting.md @@ -26,7 +26,7 @@ Preserve the following contracts exactly across all language ports: - Relationship subtypes: `association`, `aggregation`, `composition`. Cardinality via `@cardinality: one|many`; target via `@objectRef`. **M:N (FR-018) slim vocabulary:** `@cardinality: "many"` + `@objectRef` (target) + `@through` (the junction/through entity — a third entity that MUST declare two `identity.reference` children, one per FK side). The relationship's FK fields are **derived** from those references (the `identity.reference` SSOT for FK direction), never restated. `@sourceRefField` (optional) disambiguates a *directed* self-join by naming the source-side FK field on the junction (the other reference is the target side); on a `@cardinality: one` relationship it instead names which of several `identity.reference` nodes onto the same target this relationship navigates, short-circuiting the unique-candidate/`@sourceRefField`/name-pairing ladder (#368, [ADR-0029](spec/decisions/ADR-0029-entity-child-extends-and-via-inference.md) Amendment 1) — an unresolvable 1:N reference set is `ERR_INVALID_RELATIONSHIP` at load. `@symmetric` (optional boolean) marks an *undirected* self-join (union-on-read) — valid only when `@objectRef` == the declaring entity, and mutually exclusive with `@sourceRefField`. The pre-FR-018 `@joinEntity`/`@joinFields` attrs are REMOVED. Validation errors: symmetric-on-hetero / symmetric+sourceRefField → `ERR_BAD_ATTR_VALUE`; junction-missing-two-references / sourceRefField-not-matching / M:N-attr-on-1:N / **junction-unpairable** → `ERR_INVALID_RELATIONSHIP`. **Unpairable means the junction declares its two references but neither resolves to the navigating entity, or neither to the `@objectRef` target** — declaring two references is NOT enough, and the loader now checks WHAT they point at (owner ruling 2026-09-20). It does so by running the real FK derivation and converting its failure, never a parallel re-implementation, so the loader and the derivation cannot drift; scope mirrors codegen's own iteration exactly — every CONCRETE, non-projection object crossed with its EFFECTIVE relationships, NOT deduped by declaration, because pairing is a property of the navigating entity and an inherited M:N can pair from one subtype and not another. Before the ruling this loaded clean and then diverged: TS and C# warned and emitted no traversal route (a silent 404), while Java, Kotlin and Python failed the build. Gated by `fixtures/conformance/error-relationship-m2m-junction-unpairable/`. - Index subtypes: `index.lookup` (non-unique retrieval index; uniqueness is encoded in the **type**: `identity.secondary` = unique alternate key, `index.lookup` = non-unique; `@unique` is REMOVED from `identity.secondary` — `ERR_UNKNOWN_ATTR` on any legacy `@unique`). RDB-physical escapes `@using`/`@expr`/`@where`/`@orders` are registered by the db provider on **both** `identity.secondary` and `index.lookup`. `index.fulltext` / `index.vector` / `index.spatial` are reserved on the subtype axis — documented, NOT registered (YAGNI + 1.0 vocab freeze). See [ADR-0040](spec/decisions/ADR-0040-index-type-and-secondary-key-purity.md). - Layout subtypes: `dataGrid` -- API subtypes: `api.base` / `api.operational` (request/response surface, a root child; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `binding.rest` (`@method`, `@path`) now, `messaging`/`grpc` reserved; the event/streaming sibling of `api.operational` is reserved). Children: `operation.query` (`@outputRef`, `@many`) / `operation.command` (`@inputRef` → `object.value`, `@transitions`, `@errors`); both take `@inputRef`, `@outputRef`, `@objectRef` (only when the target cannot be derived), `@permission`, `@public`. Derived CRUD (FR-008/009) stays the zero-config default; declared `api` extends it. Org-tier modeling (application/service/network/deployment) stays OUT of core — provider SPI, FQN references. See [ADR-0030](spec/decisions/ADR-0030-declared-api-surface-and-org-tier-boundary.md). **Registered in all five ports since 1.3.0, experimental** (may change in a MINOR) ([ADR-0066](spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)), with the loader rules (`error-rules-*` fixtures) and the `verify` rules gate (`fixtures/rules-check-conformance/`); the flat generators generate nothing from it (`fixtures/codegen-noop/rules/`); the ADR-0067 layer generators do (C# `rules-names` so far). +- API subtypes: `api.base` / `api.operational` (request/response surface, a root child; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `binding.rest` (`@method`, `@path`) now, `messaging`/`grpc` reserved; the event/streaming sibling of `api.operational` is reserved). Children: `operation.query` (`@outputRef`, `@many`) / `operation.command` (`@inputRef` → `object.value`, `@transitions`, `@errors`); both take `@inputRef`, `@outputRef`, `@objectRef` (only when the target cannot be derived), `@permission`, `@public`. Derived CRUD (FR-008/009) stays the zero-config default; declared `api` extends it. Org-tier modeling (application/service/network/deployment) stays OUT of core — provider SPI, FQN references. See [ADR-0030](spec/decisions/ADR-0030-declared-api-surface-and-org-tier-boundary.md). **Registered in all five ports since 1.3.0, experimental** (may change in a MINOR) ([ADR-0066](spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)), with the loader rules (`error-rules-*` fixtures) and the `verify` rules gate (`fixtures/rules-check-conformance/`); the flat generators generate nothing from it (`fixtures/codegen-noop/rules/`); the ADR-0067 layer generators do (C# `rules-names` and `contract-types` so far). - Transition subtypes: `transition.action` (a child of `field.enum` on an `object.entity`: `@from`, `@to`, `@condition` in the validators' grammar, `@permission`, `@public`); `transition.base` is the abstract root and `transition.timed` is reserved, not registered. An enum with a transition IS a lifecycle — states, initial state (`@default`), terminal states and each unclaimed transition's command are derived, never declared (ADR-0066). A transition's `@from` lists enum members, not object references: every port's ref-bearing-attr check excludes `transition.*` nodes. A lifecycle belongs to the declaring entity and its `extends` descendants, NEVER to an entity whose field merely `extends` the lifecycle field (filter by the declaring field's owner); a command claims a transition NODE for its target and every entity extending it. Transition and operation names compare case-insensitively; operation names are unique per PACKAGE across its APIs, except one operation declared identically in two APIs (a versioned API). A lifecycle on an entity with no source loads and is inert (no derived command, no permission checks); the writable-source check applies once a source exists. A `@permission` is a dotted identifier path (a package prefix may use `::`); an absent one derives `.` for an operation and `..` for a transition's command. - Currency attrs: `@currency` (ISO 4217), `@locale` (BCP 47) - Schema attrs: `@schema` on `source.rdb` (DB schema name; Postgres default `public`, SQLite rejects non-default values) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a49cb1421..b81bdd5a61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,19 @@ here.** exactly the reference content is left alone and reported as identical, with or without `force`. The codegen fingerprint, `metaobjects:fmt` and `metaobjects:init` also compare before they write. +- **C#: a `contract-types` generator writes each entity's create and update records (ADR-0067 layer 1).** + Opt-in, beside `entity`: add `new ContractTypesGenerator()` to `codegen/Generators.cs`. For each + writable entity it writes `Contracts.g.cs` with `Create` and `Update`, + `sealed record`s carrying the entity's validation attributes and wire converters. Neither carries + what the server owns: a generated key, an `@autoSet` stamp, a `readOnly` or derived field, a TPH + discriminator. A required member with no `@default` is a `required` member of the create record, so + a body that omits it does not bind. Every update member is optional; `Update.From` binds a + body and records which keys it carried, so `Has` tells an omitted member (untouched) from an + explicit null (cleared), and validation refuses null on a required member. The lifecycle field + stays on both, so the service shell can check it and refuse a change with `409 state_managed`. The + validation and converter attributes moved out of `EntityGenerator` into `ContractMembers`, which + eject hands over with either generator; the entity's output is unchanged. The shared generator + manifest gains the `contract-types` entry (C# only for now). - **C#: a `rules-names` generator writes the business-rules names as constants (ADR-0067 layer 0).** It is opt-in, like any generator: add `new RulesNamesGenerator()` to `codegen/Generators.cs`. For each entity with a lifecycle it writes `Rules.g.cs`, with each lifecycle's states, initial diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index 02a7d3bf9d..fc86d1cc4d 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -14,8 +14,9 @@ The Rust port loads the vocabulary and runs the same loader rules, and its `veri same rules gate, held to `fixtures/rules-check-conformance/` ([Rust port](../ports/rust.md)). A requirement can claim an operation or a transition. The flat generators generate nothing from the vocabulary. The layer generators of ADR-0067 do, and an app adds them to its generator list as -it adds any generator. The first is C#'s `rules-names`, which writes the states, transitions, -permissions and error codes as constants ([C# port](../ports/csharp.md)). The service shells that +it adds any generator. The first are C#'s `rules-names`, which writes the states, transitions, +permissions and error codes as constants, and `contract-types`, which writes each entity's create +and update records ([C# port](../ports/csharp.md)). The service shells that enforce these rules at run time are later work. A lifecycle in a project that wires none will be advised by `verify` once that check lands; today the flat routes enforce nothing and `verify` says nothing about it. Every flat generator writes byte-identical code for diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 78328504f8..e8b0cefad1 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -800,6 +800,36 @@ it does any generator: an entity's file follows the entity, and an API's file fo This is a layer generator, separate from the flat ones (ADR-0067 §5), so adding it changes no other generator's output. +### `contract-types` — the create and update records + +The `contract-types` generator (`ContractTypesGenerator`) is ADR-0067's layer 1 for writes. For +each writable entity (a concrete `object.entity` with a writable primary source) it writes +`Contracts.g.cs`, next to the entity, with two `sealed record`s: + +- `Create`: what a client sends to create a row. It leaves off what the server owns (a + derived field, an `@autoSet` stamp, a `readOnly` field, the TPH discriminator) and a key the + server generates (`@generation: increment` or `uuid`). A key the client chooses stays. A member + that is required and has no `@default` is a C# `required` member, so System.Text.Json refuses a + body that omits it. +- `Update`: what a client may change. It leaves off the same server-owned members and every + key field, since the route names the row. Every member is optional. Bind it with + `Update.From(body, options)`, which records the keys the body carried: `Has("note")` is + true for `{"note": null}` and false for `{}`, so a PATCH can leave an omitted member alone and + clear an explicit null. `Validate` refuses null on a required member. + +Both records carry the entity's validation attributes (`[MaxLength]`, `[StringLength]`, `[Range]`, +`[RegularExpression]`, `[EmailAddress]`, the array counts) and its wire converters (decimal, +duration, strict uri/inet), written by `ContractMembers`, the one copy `EntityGenerator` writes its +own from. A required string keeps its non-empty floor in both: on update it applies when the member +is sent. Enum, value-object and map members name the entity's own types, so `entity` runs in the +same project (`Requires: entity`). Bind with the application's JSON options; a generated server +registers `JsonStringEnumConverter`, which an enum member needs. + +The lifecycle field stays on both records. The service shell checks a create against the initial +state and refuses a change on the generic update with `409 state_managed` (ADR-0066 §6), so it has +to see the member. This is a layer generator, separate from the flat ones (ADR-0067 §5), so adding +it changes no other generator's output. Eject hands `ContractMembers` over with either generator. + ### Report export A served report (a view-backed `object.report`) can be downloaded as a file: diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index ccdf349ec9..3326538dd9 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -111,6 +111,13 @@ "eject": "full", "ports": ["csharp"] }, + "contract-types": { + "concept": "Per-entity create and update records (ADR-0067 layer 1): the members a client sends to create a row and may change on update, with the entity's validation; the server-owned members (generated key, @autoSet stamp, readOnly and derived fields, TPH discriminator) are on neither, and the update record tells an omitted member from an explicit null.", + "tier": "native", + "layer": "model", + "eject": "full", + "ports": ["csharp"] + }, "prompt-render": { "concept": "Per-template.prompt render handle over the render engine, aggregated into one module. TYPESCRIPT ONLY by design: the other four ports emit a prompt's render helper from `render-helper` (see its note) rather than a second generator.", "tier": "native", diff --git a/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs index bc04c0b3de..695ff213e7 100644 --- a/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs @@ -47,7 +47,7 @@ public void ListHeader_says_generators_are_owned_via_eject() public void ListLines_prints_all_generators_with_stable_names_and_descriptions() { var lines = GenCommand.ListLines(_tmp); - Assert.Equal(17, lines.Count); + Assert.Equal(18, lines.Count); foreach (var name in new[] { "entity", "db-context", "routes", "output-parser", "extractor", @@ -58,6 +58,8 @@ public void ListLines_prints_all_generators_with_stable_names_and_descriptions() "names", // ADR-0067 layer 0 — the business-rules names (states, transitions, permissions, errors). "rules-names", + // ADR-0067 layer 1 — the per-entity create and update records. + "contract-types", // ADR-0057 — per-requirement xUnit tests calling a project-owned witness. "requirement-tests", "report-export", diff --git a/server/csharp/MetaObjects.Codegen.Tests/ContractTypesGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ContractTypesGeneratorTests.cs new file mode 100644 index 0000000000..7641bef154 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/ContractTypesGeneratorTests.cs @@ -0,0 +1,200 @@ +// ADR-0067 layer 1 for writes: the contract-types generator's create and update records. +// +// The expectations come from the write contract the generated routes already serve and ADR-0066, +// not from the generator: a create body never carries what the server owns (a generated key, an +// @autoSet stamp, a readOnly or derived field), a required member with no @default must be sent, +// the update body never carries a key, and a PATCH tells an omitted member (untouched) from an +// explicit null (cleared) and refuses null on a required member. The lifecycle field stays on the +// update record so the service can refuse it with 409 state_managed (ADR-0066 §6). +// +// Each test compiles the emitted entity and contract files with Roslyn, then binds real JSON with +// System.Text.Json and validates with the DataAnnotations Validator, so what is checked is what a +// consumer's endpoint would see. + +using System.ComponentModel.DataAnnotations; +using System.Reflection; +using System.Text.Json; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class ContractTypesGeneratorTests +{ + private const string Ns = "Acme.Orders"; + + private const string Model = """ + { "metadata.root": { "package": "acme::orders", "children": [ + { "object.value": { "name": "Address", "children": [ + { "field.string": { "name": "city", "@required": true } } ] } }, + { "object.entity": { "name": "Order", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } }, + { "field.string": { "name": "title", "@required": true, "@maxLength": 20 } }, + { "field.string": { "name": "note" } }, + { "field.int": { "name": "quantity", "@required": true, "children": [ + { "validator.numeric": { "@min": 1, "@max": 99 } } ] } }, + { "field.string": { "name": "channel", "@required": true, "@default": "web" } }, + { "field.string": { "name": "tags", "isArray": true } }, + { "field.object": { "name": "shipTo", "@objectRef": "Address", "@storage": "jsonb" } }, + { "field.timestamp": { "name": "createdAt", "@autoSet": "onCreate" } }, + { "field.string": { "name": "legacyCode", "@mutability": "readOnly" } }, + { "field.enum": { "name": "status", "@values": ["open", "closed"], "@default": "open", "children": [ + { "transition.action": { "name": "close", "@from": ["open"], "@to": "closed" } } ] } } + ] } }, + { "object.entity": { "name": "Tag", "children": [ + { "source.rdb": { "@table": "tags" } }, + { "field.string": { "name": "code", "@required": true } }, + { "identity.primary": { "name": "pk", "@fields": ["code"] } }, + { "field.string": { "name": "label" } } ] } } + ] } } + """; + + // The application's options: web defaults plus the string enum converter every generated + // server registers (ConfigureHttpJsonOptions), as the entity itself is bound. + private static readonly JsonSerializerOptions Web = new(JsonSerializerDefaults.Web) + { + Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() }, + }; + + private static List Emit() + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(Model, id: "orders.json")]); + Assert.True(r.Errors.Count == 0, string.Join("\n", r.Errors.Select(e => $"{e.Code}: {e.Message}"))); + var ctx = new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig { OutDir = "/unused", Namespace = Ns }, + }; + return new IGenerator[] { new EntityGenerator(), new ContractTypesGenerator() }.SelectMany(g => g.Generate(ctx)).ToList(); + } + + private static readonly Lazy Asm = new(() => + { + var trees = Emit().Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12), path: f.Path)); + var comp = CSharpCompilation.Create("contract_types_" + Guid.NewGuid().ToString("N"), trees, + DbContextCompileTests.BuildReferences(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + using var ms = new MemoryStream(); + var result = comp.Emit(ms); + Assert.True(result.Success, string.Join("\n", result.Diagnostics + .Where(d => d.Severity == DiagnosticSeverity.Error).Select(d => $"{d.Id}: {d.GetMessage()}"))); + return Assembly.Load(ms.ToArray()); + }); + + private static Type T(string name) => Asm.Value.GetType($"{Ns}.{name}") ?? throw new Xunit.Sdk.XunitException($"no type {Ns}.{name}"); + + private static string[] WireNames(Type t) => + t.GetProperties().Select(p => p.GetCustomAttribute()?.Name) + .OfType().ToArray(); + + private static object Create(string json) => JsonSerializer.Deserialize(json, T("OrderCreate"), Web)!; + + private static object Update(string json) => + T("OrderUpdate").GetMethod("From")!.Invoke(null, [JsonDocument.Parse(json).RootElement, Web])!; + + private static List Errors(object instance) + { + var results = new List(); + Validator.TryValidateObject(instance, new ValidationContext(instance), results, validateAllProperties: true); + return results.SelectMany(r => r.MemberNames).ToList(); + } + + private static object? Get(object o, string prop) => o.GetType().GetProperty(prop)!.GetValue(o); + + [Fact] + public void The_create_record_carries_what_a_client_sends_and_nothing_the_server_owns() + { + // Generated key, @autoSet stamp and readOnly field are the server's; the lifecycle field stays. + Assert.Equal(["title", "note", "quantity", "channel", "tags", "shipTo", "status"], WireNames(T("OrderCreate"))); + // A key the client chooses (no @generation) is part of the create body. + Assert.Equal(["code", "label"], WireNames(T("TagCreate"))); + } + + [Fact] + public void The_update_record_never_carries_a_key() + { + Assert.Equal(["title", "note", "quantity", "channel", "tags", "shipTo", "status"], WireNames(T("OrderUpdate"))); + Assert.Equal(["label"], WireNames(T("TagUpdate"))); + } + + [Fact] + public void A_create_without_a_required_member_is_refused_unless_it_has_a_default() + { + // title and quantity are required with no default; channel is required but defaults. + var ex = Assert.ThrowsAny(() => Create("""{"quantity": 2}""")); + Assert.Contains("title", ex.Message); + Assert.ThrowsAny(() => Create("""{"title": "a"}""")); + + var ok = Create("""{"title": "a", "quantity": 2}"""); + Assert.Empty(Errors(ok)); + Assert.Null(Get(ok, "Channel")); + } + + [Fact] + public void A_create_is_validated_like_the_entity() + { + // @maxLength 20 and validator.numeric 1..99, the bounds the entity enforces. + Assert.Contains("Title", Errors(Create("""{"title": "this title is far too long", "quantity": 2}"""))); + Assert.Contains("Quantity", Errors(Create("""{"title": "a", "quantity": 100}"""))); + Assert.Contains("Title", Errors(Create("""{"title": "", "quantity": 2}"""))); + } + + [Fact] + public void A_create_binds_enums_value_objects_and_arrays_as_the_entity_types() + { + var c = Create("""{"title": "a", "quantity": 2, "status": "closed", "tags": ["x", "y"], "shipTo": {"city": "Oslo"}}"""); + Assert.Equal("closed", Get(c, "Status")!.ToString()); + Assert.Equal(T("Order").GetNestedTypes().Single(t => t.IsEnum), Nullable.GetUnderlyingType(c.GetType().GetProperty("Status")!.PropertyType)); + Assert.Equal(T("Address"), c.GetType().GetProperty("ShipTo")!.PropertyType); + Assert.Equal(["x", "y"], ((IEnumerable)Get(c, "Tags")!).ToArray()); + } + + [Fact] + public void An_update_tells_an_omitted_member_from_an_explicit_null() + { + var u = Update("""{"note": null, "quantity": 3}"""); + var has = u.GetType().GetMethod("Has")!; + Assert.True((bool)has.Invoke(u, ["note"])!); + Assert.True((bool)has.Invoke(u, ["quantity"])!); + Assert.False((bool)has.Invoke(u, ["title"])!); + Assert.Null(Get(u, "Note")); + Assert.Equal(3, Get(u, "Quantity")); + Assert.Empty(Errors(u)); + + // An unknown key and a key are not members, so Has never reports them. + var other = Update("""{"id": 5, "bogus": 1}"""); + Assert.False((bool)has.Invoke(other, ["id"])!); + Assert.Empty((IEnumerable)Get(other, "Present")!); + } + + [Fact] + public void An_update_cannot_clear_a_required_member_and_is_validated_when_it_sends_one() + { + Assert.Contains("Title", Errors(Update("""{"title": null}"""))); + Assert.Contains("Title", Errors(Update("""{"title": ""}"""))); + Assert.Contains("Quantity", Errors(Update("""{"quantity": 0}"""))); + // An optional member may be cleared. + Assert.Empty(Errors(Update("""{"note": null, "tags": null}"""))); + } + + [Fact] + public void An_update_keeps_the_lifecycle_field_so_the_service_can_refuse_it() + { + var u = Update("""{"status": "closed"}"""); + Assert.True((bool)u.GetType().GetMethod("Has")!.Invoke(u, ["status"])!); + Assert.Equal("closed", Get(u, "Status")!.ToString()); + } + + [Fact] + public void A_projection_and_a_value_object_get_no_records() + { + var paths = Emit().Select(f => f.Path).ToList(); + Assert.Contains("OrderContracts.g.cs", paths); + Assert.Contains("TagContracts.g.cs", paths); + Assert.DoesNotContain("AddressContracts.g.cs", paths); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs index a28b0abd3d..595a20f80b 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs @@ -23,6 +23,7 @@ public sealed class GeneratorRegistryTests // Program A / §A5 — per-object physical database name constants. "names", "rules-names", + "contract-types", // The @expr indexes the EF model cannot carry, as SQL (C#-only). "expression-indexes", // ADR-0057 — per-requirement xUnit tests calling a project-owned witness. diff --git a/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs b/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs index e291a68c75..6a6e57b4b1 100644 --- a/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs +++ b/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs @@ -166,7 +166,7 @@ private static IGenerator RenderHelper(GeneratorBuildContext ctx) => Layer = GeneratorLayer.Model, Factory = _ => new EntityGenerator(), SourceFileName = "EntityGenerator.cs", - Companions = ["Generators/Fr019SharedEnum.cs", "Generators/M2MNavigation.cs", "Generators/ReverseFinders.cs", "Docs/XmlDocBuilder.cs"], + Companions = ["Generators/ContractMembers.cs", "Generators/Fr019SharedEnum.cs", "Generators/M2MNavigation.cs", "Generators/ReverseFinders.cs", "Docs/XmlDocBuilder.cs"], }, ["db-context"] = new() { @@ -271,6 +271,19 @@ private static IGenerator RenderHelper(GeneratorBuildContext ctx) => Factory = _ => new RulesNamesGenerator(), SourceFileName = "RulesNamesGenerator.cs", }, + // ADR-0067 layer 1 for writes: the create and update records, a layer generator. They name + // the entity's enum and value-object types, so entity runs with it. + ["contract-types"] = new() + { + Name = "contract-types", + Description = "Per-entity create and update records with the entity's validation (ADR-0067 layer 1).", + Tier = GeneratorTier.Native, + Layer = GeneratorLayer.Model, + Requires = ["entity"], + Factory = _ => new ContractTypesGenerator(), + SourceFileName = "ContractTypesGenerator.cs", + Companions = ["Generators/ContractMembers.cs", "Generators/Fr019SharedEnum.cs", "Docs/XmlDocBuilder.cs"], + }, // The indexes the EF model cannot carry (an @expr key), as one SQL file to apply after the // schema EF builds. C#-only: meta migrate writes them into its own DDL. ["expression-indexes"] = new() diff --git a/server/csharp/MetaObjects.Codegen/Generators/ContractMembers.cs b/server/csharp/MetaObjects.Codegen/Generators/ContractMembers.cs new file mode 100644 index 0000000000..805a24b172 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Generators/ContractMembers.cs @@ -0,0 +1,263 @@ +// The attributes and type references a generated member carries, shared by every generator that +// writes a model member: the entity, value-object and TPH classes (EntityGenerator) and the create +// and update records (ContractTypesGenerator). One copy, so a create record validates and binds the +// wire exactly as the entity it creates does. +// +// What lives here: the validation DataAnnotations a field's validators and attributes imply +// ([MaxLength], [StringLength], [Range], [RegularExpression], [EmailAddress], array counts), the +// per-property wire converters (decimal, duration, strict uri/inet), and the type a property names +// for an enum or a map value. Each method is what EntityGenerator wrote inline before, moved +// unchanged. Eject hands it over with either generator, as a companion. + +using MetaObjects.Codegen.Writer; +using MetaObjects.Meta; +using static MetaObjects.Core.Field.FieldConstants; +using static MetaObjects.Core.Validator.ValidatorConstants; + +namespace MetaObjects.Codegen.Generators; + +/// The attributes and type references a generated model member carries (see the file header). +public static class ContractMembers +{ + // FR-019 — the C# enum type a property of is typed by: + // • shared (root-level abstract, non-@provided) → the materialized type, global::-qualified + // in its package's namespace (rc.19 R65). + // • @provided → . (codegen error if unset). + // • inline (the common case) → the per-object nested type name. + public static string EnumPropertyTypeName(MetaObject owner, MetaField field, GenConfig config) + { + if (Fr019SharedEnum.SharedEnumForField(field) is { } shared) + return Fr019SharedEnum.SharedEnumTypeReference(shared, config); + return CSharpNaming.EnumTypeName(owner, field); + } + + // #234 — true iff FIELD is a (single, non-array) STRICT field.uri / field.inet — the fields + // carrying the generated [JsonConverter] + backing MetaNetValidation. A @lenient uri/inet is a + // plain string with no converter, so it does not count. Single SSOT predicate for both the + // per-entity emit gate and the per-property attribute guard (mirrors the Java/Kotlin ports' + // own isStrictNetField). + public static bool IsStrictNetField(MetaField field) => + !field.ResolvedIsArray() + && (field.SubType == FIELD_SUBTYPE_URI || field.SubType == FIELD_SUBTYPE_INET) + && !CSharpNaming.IsLenientNet(field); + + // #234 — write the [JsonConverter(typeof(…))] binding a strict field.uri / field.inet property + // to the same-namespace generated MetaNetValidation converter. Nothing for a @lenient uri/inet + // (a plain string) or any other field. An @isArray uri/inet (element-wise converter) is a + // follow-up (no validation-conformance case). + public static void WriteNetConverterAttribute(CsWriter w, MetaField field) + { + if (!IsStrictNetField(field)) return; // strict predicate guarantees a non-array uri/inet + if (field.SubType == FIELD_SUBTYPE_URI) + w.Line("[JsonConverter(typeof(MetaNetValidation.AbsoluteUriJsonConverter))]"); + else if (field.SubType == FIELD_SUBTYPE_INET) + w.Line("[JsonConverter(typeof(MetaNetValidation.IPAddressJsonConverter))]"); + } + + // true iff FIELD is a field.duration (single or @isArray): a System.TimeSpan property carrying + // the per-property ISO-8601 converter. + public static bool IsDurationField(MetaField field) => + field.SubType == FIELD_SUBTYPE_DURATION && CSharpNaming.DbColumnTypeClrOverride(field) is null; + + // Under `wire.durations: iso` the per-property converter writes and reads ISO-8601 (host JSON + // options cannot drop a property attribute). One attribute serves TimeSpan, TimeSpan? and + // IList. Under the default `native` there is no attribute: System.Text.Json's own + // TimeSpan form ("01:30:00") is the wire form, both ways. + public static void WriteDurationConverterAttribute(CsWriter w, MetaField field, WireFormat wire) + { + if (wire.Durations == DurationWireForm.Iso && IsDurationField(field)) w.Line("[DurationWire.Iso]"); + } + + // true iff FIELD surfaces as a CLR decimal (single or @isArray) and so carries the + // per-property wire converter. A jsonb override keeps the JsonDocument type, not decimal. + public static bool IsDecimalWireField(MetaField field) => + field.SubType == FIELD_SUBTYPE_DECIMAL && CSharpNaming.DbColumnTypeClrOverride(field) is null; + + // The per-property converter: host JSON options cannot drop it. `required` decides which + // closed type the property has (decimal, decimal?, IList). Under the default + // `wire.decimals: native` (ADR-0019 Amendment 2) it writes what System.Text.Json writes, a + // JSON number, and keeps only the input rules; `string` writes the canonical string. + public static void WriteDecimalConverterAttribute(CsWriter w, MetaField field, bool nullable, WireFormat wire) + { + if (!IsDecimalWireField(field)) return; + if (wire.Decimals == DecimalWireForm.Native) + { + w.Line(field.Precision is long p + ? $"[DecimalWire.Number({p}, {field.Scale ?? 0})]" + : "[DecimalWire.Number]"); + return; + } + // W3: a declared @precision and @scale bound the input; the attribute carries both. + if (field.Precision is long precision) + { + w.Line($"[DecimalWire.Declared({precision}, {field.Scale ?? 0})]"); + return; + } + var converter = field.ResolvedIsArray() ? "DecimalListJsonConverter" + : nullable ? "NullableDecimalJsonConverter" : "DecimalJsonConverter"; + w.Line($"[System.Text.Json.Serialization.JsonConverter(typeof(DecimalWire.{converter}))]"); + } + + // String length + pattern DataAnnotations for a string scalar, combining the field + // @maxLength attr with validator.length (@min/@max) and validator.regex (@pattern). + // + // Length: when both a validator.length @min AND a maximum (@maxLength or validator.length + // @max) apply, emit a single [StringLength(max, MinimumLength = min)] — the form + // TryValidateObject enforces on BOTH ends. Validator-@min-only → [MinLength]; max-only → + // [MaxLength] (preserving the existing @maxLength semantics). + // + // FR-036 A3 — when @maxLength AND validator.length @max both apply, the effective max is + // the STRICTEST (min of the two), not one-wins. + // + // FR-036 A1 — is the implicit non-empty floor for a + // @required string (1), applied ONLY when no validator.length @min was authored at all. + // An explicitly authored @min is always AUTHORITATIVE over the floor (#224 / ADR-0044): + // when present it is used as-is (never raised to the floor), and an authored @min: 0 + // opts back to presence-only, emitting no minimum constraint whatsoever. When the floor + // does apply (no @min authored), it becomes a standalone [MinLength] alongside the + // [MaxLength] (so the max attribute is undisturbed). + public static void WriteStringValidatorAttributes( + CsWriter w, MetaField field, long requiredMinFloor = 0) + { + // ADR-0036 Wave 3 — @stringFormat narrows a plain string to a closed validated + // format. The canonical matcher per format lives HERE (codegen), never author + // validator.regex (cross-language regex engines diverge). The field stays a plain + // string: email → [EmailAddress]; hostname → the canonical RFC-1123 [RegularExpression]. + // ADR-0039: resolving — @stringFormat may be inherited via extends (TS reads field.attr). + switch (field.Attr(FIELD_ATTR_STRING_FORMAT) as string) + { + case STRING_FORMAT_EMAIL: + w.Line("[EmailAddress]"); + break; + case STRING_FORMAT_HOSTNAME: + w.Line($"[RegularExpression(@\"{CSharpNaming.HostnameRegex}\")]"); + break; + } + + long? validatorMin = null; + long? max = field.MaxLength; + foreach (var v in field.Validators()) + { + if (v.SubType == VALIDATOR_SUBTYPE_LENGTH) + { + if (v.Min is long lmin) + validatorMin = validatorMin is long curMin ? System.Math.Max(curMin, lmin) : lmin; + // FR-036 A3 — strictest-wins: effective max = min(@maxLength, validator.length @max). + if (v.Max is long lmax) + max = max is long curMax ? System.Math.Min(curMax, lmax) : lmax; + } + else if (v.SubType == VALIDATOR_SUBTYPE_REGEX + && v is MetaRegexValidator { Pattern: { } pattern }) + { + // FR-036 Pin-2 — ALWAYS anchor the emitted pattern as a FULL match ^(?:…)$. + // .NET's RegularExpressionAttribute is valid only when the match starts at + // index 0 AND spans the whole value; for an UNanchored ordered-alternation + // whose earlier branch is a prefix of a later one (e.g. (a|ab) vs "ab") the + // engine matches the shorter branch ("a", length 1 ≠ 2) and REJECTS a string + // the anchored TS/Python (^(?:…)$) and Java/Kotlin (Matcher.matches) ports + // ACCEPT. Wrapping forces the engine to backtrack to a full match. Redundant + // on an already-anchored authored pattern (^(?:^…$)$ matches identically). + w.Line($"[RegularExpression(\"^(?:{EscapeAttrString(pattern)})$\")]"); + } + } + + long? min = validatorMin; + if (requiredMinFloor > 0) + { + // FR-036 A1 — the @required non-empty floor applies ONLY when no + // validator.length @min was authored at all. An explicitly authored + // @min is always AUTHORITATIVE over the implicit floor (#224 / + // ADR-0044): @min: 0 opts back to presence-only and, per the + // cross-port emission pin, emits NO minimum constraint at all (no + // [MinLength(0)] / MinimumLength = 0) — cleanest, deterministic + // output across ports. An authored @min > 0 already satisfies + // (exceeds) the floor and needs no further clamping. + min = validatorMin switch + { + null => requiredMinFloor, + 0 => null, + _ => validatorMin, + }; + } + + if (min is long mn && max is long mx) + { + // A validator.length @min + a max → a single [StringLength] gating both ends. + // A pure required-floor min (no validator @min) keeps [MaxLength] and adds a + // standalone [MinLength], leaving the max attribute unchanged. + if (validatorMin is not null) + w.Line($"[StringLength({mx}, MinimumLength = {mn})]"); + else + { + w.Line($"[MaxLength({mx})]"); + w.Line($"[MinLength({mn})]"); + } + } + else if (min is long mn2) + w.Line($"[MinLength({mn2})]"); + else if (max is long mx2) + w.Line($"[MaxLength({mx2})]"); + } + + // Numeric value bounds for a non-string scalar: validator.numeric (@min/@max) → + // [Range(min, max)]. Both bounds present in the canonical corpus; when only one is + // declared the other defaults to the type's extreme so the single bound still gates. + public static void WriteNumericValidatorAttributes(CsWriter w, MetaField field) + { + foreach (var v in field.Validators()) + { + if (v.SubType != VALIDATOR_SUBTYPE_NUMERIC) continue; + if (v.Min is null && v.Max is null) continue; + long lo = v.Min ?? long.MinValue; + long hi = v.Max ?? long.MaxValue; + w.Line($"[Range({lo}, {hi})]"); + return; + } + } + + // Element-count bounds for an array field: validator.array (@min/@max) → + // [MinLength(min)] + [MaxLength(max)] on the List property. + public static void WriteArrayValidatorAttributes(CsWriter w, MetaField field) + { + foreach (var v in field.Validators()) + { + if (v.SubType != VALIDATOR_SUBTYPE_ARRAY) continue; + if (v.Min is long amin) w.Line($"[MinLength({amin})]"); + if (v.Max is long amax) w.Line($"[MaxLength({amax})]"); + return; + } + } + + // Escapes a regex pattern or default for embedding in a C# string-literal attribute argument. + // A raw newline, any other control character, or a Unicode line separator would end the + // literal and emit source that does not compile. + public static string EscapeAttrString(string s) + { + var sb = new System.Text.StringBuilder(s.Length + 8); + foreach (var c in s) + { + switch (c) + { + case '\\': sb.Append("\\\\"); break; + case '"': sb.Append("\\\""); break; + case (char)10: sb.Append("\\n"); break; // the escape for a line feed, not a line break + case (char)13: sb.Append("\\r"); break; // the escape for a carriage return + case '\t': sb.Append("\\t"); break; + default: + if (char.IsControl(c) || c is '\u2028' or '\u2029') + sb.Append("\\u").Append(((int)c).ToString("x4", System.Globalization.CultureInfo.InvariantCulture)); + else + sb.Append(c); + break; + } + } + return sb.ToString(); + } + + // A map's value object is named as the owner's file sees it: global::-qualified when another + // object shares its short name (both namespaces' `using`s are in scope; CS0104 otherwise). + public static string MapValueTypeRef(MetaField field, MetaData owner, GenContext ctx) => + field.ObjectRef is { Length: > 0 } && ValueObjectNames.ResolveFieldRef(field, ctx.Root) is { } vo + ? ValueObjectNames.ShortRef(vo, ctx.Root, ctx.Config, ValueObjectNames.Namespace(owner, ctx.Config)) + : CSharpNaming.MapValueType(field, ctx.Root); +} diff --git a/server/csharp/MetaObjects.Codegen/Generators/ContractTypesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ContractTypesGenerator.cs new file mode 100644 index 0000000000..64045e10f1 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Generators/ContractTypesGenerator.cs @@ -0,0 +1,255 @@ +// contract-types-generator — ADR-0067 layer 1 for writes: one Contracts.g.cs per writable +// entity, holding a create record and an update record, each a `sealed record` with the same +// validation DataAnnotations and wire converters the entity carries (ContractMembers, the one copy +// both generators write from). +// +// Create the members a client sends to create a row. A required member with no @default +// is a C# `required` member, so System.Text.Json refuses a body that omits it. +// Update the members a client may change. Every member is optional. `From` binds a body +// and records which keys it carried, so an omitted member and an explicit null +// stay apart (the PATCH contract: omitted is untouched, null clears, and null on +// a required member is refused, which `Validate` reports). +// +// Neither carries what the server owns: a derived (origin.*) field, an @autoSet stamp, a readOnly +// field, a TPH discriminator. A generated key (@generation increment or uuid) is left off the +// create record; every key is left off the update record, because the route names the row. +// A lifecycle field is on both: the service shell checks a create against the initial state and +// refuses a change on the generic update with 409 state_managed (ADR-0066 §6), and to refuse it the +// shell has to see it. +// +// A layer generator, separate from the flat ones (ADR-0067 §5.2). The records name the entity's +// enum and value-object types and its wire helpers, so `entity` runs in the same project. + +using MetaObjects.Codegen.Docs; +using MetaObjects.Codegen.Writer; +using MetaObjects.Meta; +using static MetaObjects.Core.Field.FieldConstants; +using static MetaObjects.Core.Identity.IdentityConstants; + +namespace MetaObjects.Codegen.Generators; + +/// Generates the create and update records of each writable entity. +public class ContractTypesGenerator : PerEntityGenerator +{ + public override string Name => "contract-types"; + + /// A concrete entity the generated routes write: a writable primary source and instance artifacts. + public override bool Filter(MetaObject entity) => + entity.IsEntity() && !entity.IsAbstract && !entity.IsReadOnlyProjection() + && entity.FindPrimaryWritableSource() is not null && InstanceArtifacts.EmitsInstanceArtifacts(entity); + + /// Which record a member is written for. + protected enum Shape { Create, Update } + + protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) + { + var cls = CSharpNaming.Pascal(entity.Name); + var ns = PackageBindingResolver.Resolve(ctx.Config, PackageBindingResolver.EffectivePackage(entity), entity.Name, fallbackContext: entity.Name); + var create = CreateFields(entity, ctx); + var update = UpdateFields(entity, ctx); + foreach (var name in new[] { CreateName(entity), UpdateName(entity) }) + ctx.Claim($"the C# namespace {ns}", name, entity.ResolutionKey(), + "map the packages to distinct namespaces (csharp.packageNamespaces, or GenConfig.PackageNamespaces), or rename one"); + + var w = NewWriter(); + WriteFileHeader(w, entity, ctx); + w.Blank(); + w.Line($"namespace {ns};"); + w.Blank(); + WriteCreateRecord(w, entity, create, ctx); + w.Blank(); + WriteUpdateRecord(w, entity, update, ctx); + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}Contracts.g.cs"), w.ToString()); + } + + /// The create record's type name. + protected virtual string CreateName(MetaObject entity) => CSharpNaming.Pascal(entity.Name) + "Create"; + + /// The update record's type name. + protected virtual string UpdateName(MetaObject entity) => CSharpNaming.Pascal(entity.Name) + "Update"; + + // ---- which members --------------------------------------------------------------------------- + + /// Whether the server owns the field, so neither record carries it. + protected virtual bool ServerOwned(MetaObject entity, MetaField field, GenContext ctx) => + field.IsDerived() || field.AutoSet is not null || field.IsReadOnlyMutability + || (TphPlanBuilder.DiscriminatorRoot(entity) is { } root + && TphPlanBuilder.For(root, ctx.Root)?.DiscriminatorField == field.Name); + + /// The create record's members, in effective field order. + protected virtual IReadOnlyList CreateFields(MetaObject entity, GenContext ctx) + { + var generatedKey = entity.PrimaryIdentity() is MetaPrimaryIdentity { Generation: GENERATION_INCREMENT or GENERATION_UUID } pk + ? pk.Fields.ToHashSet(StringComparer.Ordinal) + : []; + return entity.Fields().Where(f => !ServerOwned(entity, f, ctx) && !generatedKey.Contains(f.Name)).ToList(); + } + + /// The update record's members, in effective field order. + protected virtual IReadOnlyList UpdateFields(MetaObject entity, GenContext ctx) + { + var key = (entity.PrimaryIdentity()?.Fields ?? []).ToHashSet(StringComparer.Ordinal); + return entity.Fields().Where(f => !ServerOwned(entity, f, ctx) && !key.Contains(f.Name)).ToList(); + } + + /// Whether a create body must carry the member: it is required and has no @default to fall back to. + protected static bool RequiredOnCreate(MetaObject entity, MetaField field) => + CSharpNaming.IsRequired(entity, field) && field.Default is null; + + // ---- the records ----------------------------------------------------------------------------- + + /// The usings: the BCL namespaces the members need and every other package they name. + protected virtual void WriteFileHeader(CsWriter w, MetaObject entity, GenContext ctx) + { + w.GeneratedFileHeader("contract-types-generator"); + w.Using("System"); + w.Using("System.Collections.Generic"); + w.Using("System.ComponentModel.DataAnnotations"); + w.Using("System.Linq"); + w.Using("System.Text.Json"); + w.Using("System.Text.Json.Serialization"); + if (CSharpNaming.RequiresSystemNet(entity)) w.Using("System.Net"); + foreach (var ns in PackageBindingResolver.CrossPackageReferencedNamespaces(entity, ctx.Root, ctx.Config)) + w.Using(ns); + } + + /// The create record. + protected virtual void WriteCreateRecord(CsWriter w, MetaObject entity, IReadOnlyList fields, GenContext ctx) + { + w.DocSummary($"GENERATED — the body that creates a {CSharpNaming.Pascal(entity.Name)}. Bind it with System.Text.Json; " + + "a required member it omits is refused there, and the DataAnnotations hold the rest."); + using (w.Braced($"public sealed record {CreateName(entity)}")) + { + var first = true; + foreach (var f in fields) + { + if (!first) w.Blank(); + first = false; + WriteMember(w, entity, f, Shape.Create, ctx); + } + } + } + + /// The update record, with its From binder and the present-null check. + protected virtual void WriteUpdateRecord(CsWriter w, MetaObject entity, IReadOnlyList fields, GenContext ctx) + { + var name = UpdateName(entity); + w.DocSummary($"GENERATED — the body that changes a {CSharpNaming.Pascal(entity.Name)}. Every member is optional: " + + "bind it with From, and Has tells an omitted member (untouched) from an explicit null (cleared)."); + using (w.Braced($"public sealed record {name} : IValidatableObject")) + { + w.DocSummary("The wire names of the members."); + w.Line("public static readonly IReadOnlySet Fields = new HashSet(StringComparer.Ordinal)"); + using (w.Braced("", "};")) + { + foreach (var f in fields) w.Line($"\"{CSharpNaming.CSharpStringLiteral(f.Name)}\","); + } + w.Blank(); + w.DocSummary("The wire names the bound body carried."); + w.Line("[JsonIgnore]"); + w.Line("public IReadOnlySet Present { get; init; } = new HashSet(StringComparer.Ordinal);"); + w.Blank(); + w.DocSummary("Whether the body carried the member named (its wire name), null included."); + w.Line("public bool Has(string field) => Present.Contains(field);"); + w.Blank(); + w.DocSummary("Bind a body with the application's JSON options and record which members it carried."); + using (w.Braced($"public static {name} From(JsonElement body, JsonSerializerOptions? options = null)")) + { + w.Line($"var bound = body.Deserialize<{name}>(options) ?? new {name}();"); + w.Line("var comparer = options?.PropertyNameCaseInsensitive == true ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;"); + w.Line("var present = new HashSet(StringComparer.Ordinal);"); + using (w.Braced("foreach (var property in body.EnumerateObject())")) + { + w.Line("var match = Fields.FirstOrDefault(f => comparer.Equals(f, property.Name));"); + w.Line("if (match is not null) present.Add(match);"); + } + w.Line("return bound with { Present = present };"); + } + foreach (var f in fields) + { + w.Blank(); + WriteMember(w, entity, f, Shape.Update, ctx); + } + w.Blank(); + w.DocSummary("A required member the body set to null: it cannot be cleared."); + using (w.Braced("public IEnumerable Validate(ValidationContext validationContext)")) + { + var required = fields.Where(f => CSharpNaming.IsRequired(entity, f)).ToList(); + foreach (var f in required) + { + var prop = CSharpNaming.PropertyName(f, ctx.Config); + var wire = CSharpNaming.CSharpStringLiteral(f.Name); + w.Line($"if (Has(\"{wire}\") && {prop} is null) yield return new ValidationResult(\"{wire} is required and cannot be null.\", [nameof({prop})]);"); + } + if (required.Count == 0) w.Line("yield break;"); + } + } + } + + /// One member: its doc, wire name, validation and converter attributes, and declaration. + protected virtual void WriteMember(CsWriter w, MetaObject entity, MetaField field, Shape shape, GenContext ctx) + { + var mustSend = shape == Shape.Create && RequiredOnCreate(entity, field); + // A required member keeps its non-empty floor in both records: on update it applies when the member is sent. + var required = CSharpNaming.IsRequired(entity, field); + var wire = ctx.Root.WireFormat; + var type = ClrType(entity, field, optional: !mustSend, ctx); + + XmlDocBuilder.WriteTo(w, field); + w.Line($"[JsonPropertyName(\"{CSharpNaming.CSharpStringLiteral(field.Name)}\")]"); + if (CSharpNaming.ScalarFor(field.SubType) is not null) + { + if (field.ResolvedIsArray()) + ContractMembers.WriteArrayValidatorAttributes(w, field); + else if (ElementType(field) == "string") + { + if (mustSend) w.Line("[Required(AllowEmptyStrings = true)]"); + ContractMembers.WriteStringValidatorAttributes(w, field, requiredMinFloor: required ? 1 : 0); + } + else + { + ContractMembers.WriteNumericValidatorAttributes(w, field); + if (mustSend && !CSharpNaming.IsValueType(ElementType(field))) w.Line("[Required]"); + } + ContractMembers.WriteDecimalConverterAttribute(w, field, nullable: !mustSend, wire); + ContractMembers.WriteDurationConverterAttribute(w, field, wire); + ContractMembers.WriteNetConverterAttribute(w, field); + } + else if (mustSend && field.SubType is FIELD_SUBTYPE_OBJECT or FIELD_SUBTYPE_MAP) + w.Line("[Required]"); + + var prop = CSharpNaming.PropertyName(field, ctx.Config); + w.Line($"public {(mustSend ? "required " : "")}{type} {prop} {{ get; init; }}"); + } + + /// A scalar's element type: the override a @dbColumnType implies, else the logical one. + protected static string ElementType(MetaField field) => + CSharpNaming.DbColumnTypeClrOverride(field) ?? CSharpNaming.ScalarForField(field)!; + + /// The member's CLR type; adds the ?. + protected virtual string ClrType(MetaObject entity, MetaField field, bool optional, GenContext ctx) + { + var q = optional ? "?" : ""; + string element; + if (CSharpNaming.ScalarFor(field.SubType) is not null) + element = ElementType(field); + else if (field.SubType == FIELD_SUBTYPE_ENUM) + { + element = ContractMembers.EnumPropertyTypeName(entity, field, ctx.Config); + // An inline enum is nested in the entity's class; a shared one is already qualified. + if (Fr019SharedEnum.SharedEnumForField(field) is null) element = $"{CSharpNaming.Pascal(entity.Name)}.{element}"; + } + else if (field.SubType == FIELD_SUBTYPE_OBJECT) + element = ValueObjectNames.ResolveFieldRef(field, ctx.Root) is { } target + ? ValueObjectNames.ShortRef(target, ctx.Root, ctx.Config, ValueObjectNames.Namespace(entity, ctx.Config)) + : CSharpNaming.Pascal(CSharpNaming.StripPkg(field.ObjectRef ?? field.Name)); + else if (field.SubType == FIELD_SUBTYPE_MAP) + return $"Dictionary{q}"; + else + element = CSharpNaming.ScalarForField(field) ?? "object"; + return field.ResolvedIsArray() ? $"IList<{element}>{q}" : element + q; + } + + /// The writer the file is written on. + protected virtual CsWriter NewWriter() => new(); +} diff --git a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs index 8fe19675d7..54ebf7af3b 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs @@ -746,8 +746,8 @@ protected virtual void WriteTphSubtypeScalarProperty( w.Line(arrColumn); } WriteArrayValidatorAttributes(w, field); - WriteDecimalConverterAttribute(w, field, nullable: false, _wire); - WriteDurationConverterAttribute(w, field, _wire); + ContractMembers.WriteDecimalConverterAttribute(w, field, nullable: false, _wire); + ContractMembers.WriteDurationConverterAttribute(w, field, _wire); // A NON-required decimal array is nullable (no initializer) so PATCH null / an omitted // POST value stays a NULL column instead of failing as a required collection. WritePropertyDeclaration(w, entity, field, propName, SetterFor(field)); @@ -763,8 +763,8 @@ protected virtual void WriteTphSubtypeScalarProperty( else WriteNumericValidatorAttributes(w, field); var required = CSharpNaming.IsRequired(entity, field); - WriteDecimalConverterAttribute(w, field, nullable: !required, _wire); - WriteDurationConverterAttribute(w, field, _wire); + ContractMembers.WriteDecimalConverterAttribute(w, field, nullable: !required, _wire); + ContractMembers.WriteDurationConverterAttribute(w, field, _wire); // Mirrors WriteScalarProperty's own initializer handling (its non-TPH sibling): a // literal-safe @default (bool/int/long/double/float/decimal/string) wins over the // `= default!;` filler a required REFERENCE-type property would otherwise need. @@ -1042,18 +1042,6 @@ protected static List CollectEnumDecls(MetaObject owner) return decls; } - // FR-019 — the C# enum type a property of is typed by: - // • shared (root-level abstract, non-@provided) → the materialized type, global::-qualified - // in its package's namespace (rc.19 R65). - // • @provided → . (codegen error if unset). - // • inline (the common case) → the per-object nested type name. - private static string EnumPropertyTypeName(MetaObject owner, MetaField field, GenConfig config) - { - if (Fr019SharedEnum.SharedEnumForField(field) is { } shared) - return Fr019SharedEnum.SharedEnumTypeReference(shared, config); - return CSharpNaming.EnumTypeName(owner, field); - } - // FR-019 — the materialized shared enums, one file each (item 12): /.g.cs // (OutputPaths.Of, ruling R39), emitted when the model has a consumed, non-@provided root-level // abstract field.enum; none otherwise, so a model with only inline enums emits nothing here. @@ -1730,31 +1718,8 @@ private void BeginMember(CsWriter w, MetaObject owner, MetaField field) // The value-object emitter's request for the next member's lead (see BeginMember). private (MetaObject Vo, GenContext Ctx)? _voLead; - // #234 — true iff FIELD is a (single, non-array) STRICT field.uri / field.inet — the fields - // carrying the generated [JsonConverter] + backing MetaNetValidation. A @lenient uri/inet is a - // plain string with no converter, so it does not count. Single SSOT predicate for both the - // per-entity emit gate and the per-property attribute guard (mirrors the Java/Kotlin ports' - // own isStrictNetField). - private static bool IsStrictNetField(MetaField field) => - !field.ResolvedIsArray() - && (field.SubType == FIELD_SUBTYPE_URI || field.SubType == FIELD_SUBTYPE_INET) - && !CSharpNaming.IsLenientNet(field); - // #234 — true iff the entity has any strict field.uri / field.inet (needs MetaNetValidation). - private static bool HasStrictNetField(MetaObject entity) => entity.Fields().Any(IsStrictNetField); - - // #234 — write the [JsonConverter(typeof(…))] binding a strict field.uri / field.inet property - // to the same-namespace generated MetaNetValidation converter. Nothing for a @lenient uri/inet - // (a plain string) or any other field. An @isArray uri/inet (element-wise converter) is a - // follow-up (no validation-conformance case). - private static void WriteNetConverterAttribute(CsWriter w, MetaField field) - { - if (!IsStrictNetField(field)) return; // strict predicate guarantees a non-array uri/inet - if (field.SubType == FIELD_SUBTYPE_URI) - w.Line("[JsonConverter(typeof(MetaNetValidation.AbsoluteUriJsonConverter))]"); - else if (field.SubType == FIELD_SUBTYPE_INET) - w.Line("[JsonConverter(typeof(MetaNetValidation.IPAddressJsonConverter))]"); - } + private static bool HasStrictNetField(MetaObject entity) => entity.Fields().Any(ContractMembers.IsStrictNetField); // ADR-0019 Amendment 1 — the decimal wire form. This text is the Runtime/DecimalWire.cs // source with its namespace swapped in; DecimalWireTests gates the two byte-for-byte. @@ -2369,53 +2334,9 @@ public override void Write(Utf8JsonWriter writer, IList value, JsonSer return new EmittedFile(fileName, w.ToString()) { WholeModel = true }; } - // true iff FIELD is a field.duration (single or @isArray): a System.TimeSpan property carrying - // the per-property ISO-8601 converter. - private static bool IsDurationField(MetaField field) => - field.SubType == FIELD_SUBTYPE_DURATION && CSharpNaming.DbColumnTypeClrOverride(field) is null; + private static bool HasDurationField(MetaObject entity) => entity.Fields().Any(ContractMembers.IsDurationField); - private static bool HasDurationField(MetaObject entity) => entity.Fields().Any(IsDurationField); - - // Under `wire.durations: iso` the per-property converter writes and reads ISO-8601 (host JSON - // options cannot drop a property attribute). One attribute serves TimeSpan, TimeSpan? and - // IList. Under the default `native` there is no attribute: System.Text.Json's own - // TimeSpan form ("01:30:00") is the wire form, both ways. - private static void WriteDurationConverterAttribute(CsWriter w, MetaField field, WireFormat wire) - { - if (wire.Durations == DurationWireForm.Iso && IsDurationField(field)) w.Line("[DurationWire.Iso]"); - } - - // true iff FIELD surfaces as a CLR decimal (single or @isArray) and so carries the - // per-property wire converter. A jsonb override keeps the JsonDocument type, not decimal. - private static bool IsDecimalWireField(MetaField field) => - field.SubType == FIELD_SUBTYPE_DECIMAL && CSharpNaming.DbColumnTypeClrOverride(field) is null; - - private static bool HasDecimalWireField(MetaObject entity) => entity.Fields().Any(IsDecimalWireField); - - // The per-property converter: host JSON options cannot drop it. `required` decides which - // closed type the property has (decimal, decimal?, IList). Under the default - // `wire.decimals: native` (ADR-0019 Amendment 2) it writes what System.Text.Json writes, a - // JSON number, and keeps only the input rules; `string` writes the canonical string. - private static void WriteDecimalConverterAttribute(CsWriter w, MetaField field, bool nullable, WireFormat wire) - { - if (!IsDecimalWireField(field)) return; - if (wire.Decimals == DecimalWireForm.Native) - { - w.Line(field.Precision is long p - ? $"[DecimalWire.Number({p}, {field.Scale ?? 0})]" - : "[DecimalWire.Number]"); - return; - } - // W3: a declared @precision and @scale bound the input; the attribute carries both. - if (field.Precision is long precision) - { - w.Line($"[DecimalWire.Declared({precision}, {field.Scale ?? 0})]"); - return; - } - var converter = field.ResolvedIsArray() ? "DecimalListJsonConverter" - : nullable ? "NullableDecimalJsonConverter" : "DecimalJsonConverter"; - w.Line($"[System.Text.Json.Serialization.JsonConverter(typeof(DecimalWire.{converter}))]"); - } + private static bool HasDecimalWireField(MetaObject entity) => entity.Fields().Any(ContractMembers.IsDecimalWireField); // #234 — emit the codegen-owned MetaNetValidation.cs into `ns`: two strict System.Text.Json // converters implementing the Contract-A rules (absolute-scheme URI; IPv4/IPv6 literal, no DNS) @@ -2555,7 +2476,7 @@ protected virtual string PropertyClrType(MetaObject owner, MetaField field, GenC } if (field.SubType == FIELD_SUBTYPE_ENUM) { - var typeName = EnumPropertyTypeName(owner, field, ctx.Config); + var typeName = ContractMembers.EnumPropertyTypeName(owner, field, ctx.Config); if (field.ResolvedIsArray()) { return $"IList<{typeName}>" + (EnumArrayIsNullable(owner, field) ? "?" : string.Empty); @@ -2575,7 +2496,7 @@ protected virtual string PropertyClrType(MetaObject owner, MetaField field, GenC } if (field.SubType == FIELD_SUBTYPE_MAP) { - return $"Dictionary" + (required ? string.Empty : "?"); + return $"Dictionary" + (required ? string.Empty : "?"); } return CSharpNaming.ScalarForField(field) ?? "object"; } @@ -2605,7 +2526,7 @@ protected virtual string PropertyClrType(MetaObject owner, MetaField field, GenC } if (field.SubType == FIELD_SUBTYPE_ENUM) { - var typeName = EnumPropertyTypeName(owner, field, ctx.Config); + var typeName = ContractMembers.EnumPropertyTypeName(owner, field, ctx.Config); if (!field.ResolvedIsArray()) { // A scalar enum starts at its @default, as a scalar does. The DbContext makes @@ -2666,7 +2587,7 @@ private bool ScalarIsNonNull(MetaObject owner, MetaField field) => // stays a NULL column instead of failing as a required collection; so is a NON-required // value-object array under `wire.nullMembers: omit`, so a null member is omitted on the wire. private bool ArrayIsNullable(MetaObject owner, MetaField field) => - (IsDecimalWireField(field) || (_site.ValueObject && _wire.NullMembers == NullMemberForm.Omit)) + (ContractMembers.IsDecimalWireField(field) || (_site.ValueObject && _wire.NullMembers == NullMemberForm.Omit)) && !CSharpNaming.IsRequired(owner, field); // A NON-required int-backed enum array (@intValueMap, read resolving) is nullable. @@ -2777,8 +2698,8 @@ protected virtual void WriteScalarProperty( WriteArrayValidatorAttributes(w, field); // EF Core 8 on SQLite materializes a primitive collection only through IList (an // ICollection property throws at query compile time), so a scalar array is an IList. - WriteDecimalConverterAttribute(w, field, nullable: false, _wire); - WriteDurationConverterAttribute(w, field, _wire); + ContractMembers.WriteDecimalConverterAttribute(w, field, nullable: false, _wire); + ContractMembers.WriteDurationConverterAttribute(w, field, _wire); // A NON-required decimal array is nullable (no initializer) so PATCH null / an omitted // POST value stays a NULL column instead of failing as a required collection; a // NON-required value-object array is nullable so a null member is omitted on the wire. @@ -2835,13 +2756,13 @@ protected virtual void WriteScalarProperty( // JsonConverter (absolute-scheme URI / IPv4-or-IPv6 literal, no DNS) so a malformed value // is rejected at the wire tier — aligning the C# entity with the TS/Python strict contract. if (emitValidation) - WriteNetConverterAttribute(w, field); + ContractMembers.WriteNetConverterAttribute(w, field); // ADR-0019 Amendment 1: a decimal crosses JSON as a canonical string. Attached per // property (not through host JsonSerializerOptions) so no host configuration drops it. - WriteDecimalConverterAttribute(w, field, nullable: !ScalarIsNonNull(owner, field), _wire); + ContractMembers.WriteDecimalConverterAttribute(w, field, nullable: !ScalarIsNonNull(owner, field), _wire); // field.duration: a TimeSpan crosses JSON as its canonical ISO-8601 string, never as // System.Text.Json's own "01:30:00". - WriteDurationConverterAttribute(w, field, _wire); + ContractMembers.WriteDurationConverterAttribute(w, field, _wire); // The type and initializer are the hooks' defaults: nullable unless required (or // origin-guaranteed non-null), a literal-safe @default as the initializer (e.g. `= false;`) @@ -2855,135 +2776,17 @@ protected virtual void WriteScalarProperty( WritePropertyDeclaration(w, owner, field, propName, setter); } - // String length + pattern DataAnnotations for a string scalar, combining the field - // @maxLength attr with validator.length (@min/@max) and validator.regex (@pattern). - // - // Length: when both a validator.length @min AND a maximum (@maxLength or validator.length - // @max) apply, emit a single [StringLength(max, MinimumLength = min)] — the form - // TryValidateObject enforces on BOTH ends. Validator-@min-only → [MinLength]; max-only → - // [MaxLength] (preserving the existing @maxLength semantics). - // - // FR-036 A3 — when @maxLength AND validator.length @max both apply, the effective max is - // the STRICTEST (min of the two), not one-wins. - // - // FR-036 A1 — is the implicit non-empty floor for a - // @required string (1), applied ONLY when no validator.length @min was authored at all. - // An explicitly authored @min is always AUTHORITATIVE over the floor (#224 / ADR-0044): - // when present it is used as-is (never raised to the floor), and an authored @min: 0 - // opts back to presence-only, emitting no minimum constraint whatsoever. When the floor - // does apply (no @min authored), it becomes a standalone [MinLength] alongside the - // [MaxLength] (so the max attribute is undisturbed). - protected static void WriteStringValidatorAttributes( - CsWriter w, MetaField field, long requiredMinFloor = 0) - { - // ADR-0036 Wave 3 — @stringFormat narrows a plain string to a closed validated - // format. The canonical matcher per format lives HERE (codegen), never author - // validator.regex (cross-language regex engines diverge). The field stays a plain - // string: email → [EmailAddress]; hostname → the canonical RFC-1123 [RegularExpression]. - // ADR-0039: resolving — @stringFormat may be inherited via extends (TS reads field.attr). - switch (field.Attr(FIELD_ATTR_STRING_FORMAT) as string) - { - case STRING_FORMAT_EMAIL: - w.Line("[EmailAddress]"); - break; - case STRING_FORMAT_HOSTNAME: - w.Line($"[RegularExpression(@\"{CSharpNaming.HostnameRegex}\")]"); - break; - } + /// The string length, format and pattern attributes of a field: . + protected static void WriteStringValidatorAttributes(CsWriter w, MetaField field, long requiredMinFloor = 0) => + ContractMembers.WriteStringValidatorAttributes(w, field, requiredMinFloor); - long? validatorMin = null; - long? max = field.MaxLength; - foreach (var v in field.Validators()) - { - if (v.SubType == VALIDATOR_SUBTYPE_LENGTH) - { - if (v.Min is long lmin) - validatorMin = validatorMin is long curMin ? System.Math.Max(curMin, lmin) : lmin; - // FR-036 A3 — strictest-wins: effective max = min(@maxLength, validator.length @max). - if (v.Max is long lmax) - max = max is long curMax ? System.Math.Min(curMax, lmax) : lmax; - } - else if (v.SubType == VALIDATOR_SUBTYPE_REGEX - && v is MetaRegexValidator { Pattern: { } pattern }) - { - // FR-036 Pin-2 — ALWAYS anchor the emitted pattern as a FULL match ^(?:…)$. - // .NET's RegularExpressionAttribute is valid only when the match starts at - // index 0 AND spans the whole value; for an UNanchored ordered-alternation - // whose earlier branch is a prefix of a later one (e.g. (a|ab) vs "ab") the - // engine matches the shorter branch ("a", length 1 ≠ 2) and REJECTS a string - // the anchored TS/Python (^(?:…)$) and Java/Kotlin (Matcher.matches) ports - // ACCEPT. Wrapping forces the engine to backtrack to a full match. Redundant - // on an already-anchored authored pattern (^(?:^…$)$ matches identically). - w.Line($"[RegularExpression(\"^(?:{EscapeAttrString(pattern)})$\")]"); - } - } + /// The numeric range attribute of a field: . + protected static void WriteNumericValidatorAttributes(CsWriter w, MetaField field) => + ContractMembers.WriteNumericValidatorAttributes(w, field); - long? min = validatorMin; - if (requiredMinFloor > 0) - { - // FR-036 A1 — the @required non-empty floor applies ONLY when no - // validator.length @min was authored at all. An explicitly authored - // @min is always AUTHORITATIVE over the implicit floor (#224 / - // ADR-0044): @min: 0 opts back to presence-only and, per the - // cross-port emission pin, emits NO minimum constraint at all (no - // [MinLength(0)] / MinimumLength = 0) — cleanest, deterministic - // output across ports. An authored @min > 0 already satisfies - // (exceeds) the floor and needs no further clamping. - min = validatorMin switch - { - null => requiredMinFloor, - 0 => null, - _ => validatorMin, - }; - } - - if (min is long mn && max is long mx) - { - // A validator.length @min + a max → a single [StringLength] gating both ends. - // A pure required-floor min (no validator @min) keeps [MaxLength] and adds a - // standalone [MinLength], leaving the max attribute unchanged. - if (validatorMin is not null) - w.Line($"[StringLength({mx}, MinimumLength = {mn})]"); - else - { - w.Line($"[MaxLength({mx})]"); - w.Line($"[MinLength({mn})]"); - } - } - else if (min is long mn2) - w.Line($"[MinLength({mn2})]"); - else if (max is long mx2) - w.Line($"[MaxLength({mx2})]"); - } - - // Numeric value bounds for a non-string scalar: validator.numeric (@min/@max) → - // [Range(min, max)]. Both bounds present in the canonical corpus; when only one is - // declared the other defaults to the type's extreme so the single bound still gates. - protected static void WriteNumericValidatorAttributes(CsWriter w, MetaField field) - { - foreach (var v in field.Validators()) - { - if (v.SubType != VALIDATOR_SUBTYPE_NUMERIC) continue; - if (v.Min is null && v.Max is null) continue; - long lo = v.Min ?? long.MinValue; - long hi = v.Max ?? long.MaxValue; - w.Line($"[Range({lo}, {hi})]"); - return; - } - } - - // Element-count bounds for an array field: validator.array (@min/@max) → - // [MinLength(min)] + [MaxLength(max)] on the List property. - protected static void WriteArrayValidatorAttributes(CsWriter w, MetaField field) - { - foreach (var v in field.Validators()) - { - if (v.SubType != VALIDATOR_SUBTYPE_ARRAY) continue; - if (v.Min is long amin) w.Line($"[MinLength({amin})]"); - if (v.Max is long amax) w.Line($"[MaxLength({amax})]"); - return; - } - } + /// The element-count attributes of an array field: . + protected static void WriteArrayValidatorAttributes(CsWriter w, MetaField field) => + ContractMembers.WriteArrayValidatorAttributes(w, field); // A C# property-initializer (` = ;`) for a field's @default, or "" when // there is no @default or the type isn't literal-safe. Scoped to bool / integer / @@ -3068,31 +2871,8 @@ protected static string DefaultInitializer(MetaField field, string baseType) => System.Globalization.CultureInfo.InvariantCulture, out _) ? s : null; } - // Escapes a regex pattern or default for embedding in a C# string-literal attribute argument. - // A raw newline, any other control character, or a Unicode line separator would end the - // literal and emit source that does not compile. - protected static string EscapeAttrString(string s) - { - var sb = new System.Text.StringBuilder(s.Length + 8); - foreach (var c in s) - { - switch (c) - { - case '\\': sb.Append("\\\\"); break; - case '"': sb.Append("\\\""); break; - case (char)10: sb.Append("\\n"); break; // the escape for a line feed, not a line break - case (char)13: sb.Append("\\r"); break; // the escape for a carriage return - case '\t': sb.Append("\\t"); break; - default: - if (char.IsControl(c) || c is '\u2028' or '\u2029') - sb.Append("\\u").Append(((int)c).ToString("x4", System.Globalization.CultureInfo.InvariantCulture)); - else - sb.Append(c); - break; - } - } - return sb.ToString(); - } + /// A pattern or default escaped for a C# attribute string: . + protected static string EscapeAttrString(string s) => ContractMembers.EscapeAttrString(s); // An owned-type navigation property for an object-typed field. Returns null (with // a warning) when the @objectRef can't be resolved. @@ -3263,10 +3043,4 @@ protected static List ValueShapes(IReadOnlyList referenc .OrderBy(o => ValueObjectNames.TypeName(o, ctx.Root), StringComparer.Ordinal) .ToList(); } - // A map's value object is named as the owner's file sees it: global::-qualified when another - // object shares its short name (both namespaces' `using`s are in scope; CS0104 otherwise). - private static string MapValueTypeRef(MetaField field, MetaData owner, GenContext ctx) => - field.ObjectRef is { Length: > 0 } && ValueObjectNames.ResolveFieldRef(field, ctx.Root) is { } vo - ? ValueObjectNames.ShortRef(vo, ctx.Root, ctx.Config, ValueObjectNames.Namespace(owner, ctx.Config)) - : CSharpNaming.MapValueType(field, ctx.Root); } diff --git a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj index 69052c7224..2c3e335636 100644 --- a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj +++ b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj @@ -56,6 +56,7 @@ + @@ -64,6 +65,7 @@ + From 4e83d3231101e412fdf23314f787b67a2f7953b6 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 12:19:24 -0500 Subject: [PATCH 3/6] feat(csharp): set every GenConfig option from the codegen project; warn on unknown config keys (T11-CS) dotnet meta init writes Generators.Configure beside the list, and codegen/Program.cs passes it to CodegenCli.Run. It receives the GenConfig a run builds from its flags and .metaobjects/config.json and returns the one the generators see, so options no flag or key sets (ContextTypeName, PropertyNaming, ProvidedEnumNamespace, PackageNamespaces, TypeOverrides, Convention, UnmappedStrategy, ...) are reachable on the normal path. gen and verify --codegen both apply it. An existing project keeps working. An unknown top-level key in .metaobjects/config.json now warns once per key, in TypeScript's words with its known-key list, and is still ignored: a newer MetaObjects may have written it. Keys inside C#-owned blocks stay refused. --- CHANGELOG.md | 14 +++- docs/ports/csharp.md | 23 +++++- .../GenConfigureTests.cs | 68 ++++++++++++++++ .../OneGeneratorListTests.cs | 2 +- .../MetaObjects.Cli.Tests/OwnedRunner.cs | 9 ++- server/csharp/MetaObjects.Cli/InitCommand.cs | 15 +++- .../csharp/MetaObjects.Codegen/CodegenCli.cs | 35 ++++++--- .../NeutralConfigUnknownKeyTests.cs | 77 +++++++++++++++++++ .../SourceResolverTests.cs | 11 +-- .../MetaObjects/Config/NeutralConfig.cs | 45 ++++++++++- 10 files changed, 270 insertions(+), 29 deletions(-) create mode 100644 server/csharp/MetaObjects.Cli.Tests/GenConfigureTests.cs create mode 100644 server/csharp/MetaObjects.Conformance.Tests/NeutralConfigUnknownKeyTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index b81bdd5a61..0aeb09a270 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,7 +46,6 @@ here.** owned generator, template, support or runtime file, or the `codegen/pom.xml`, that already holds exactly the reference content is left alone and reported as identical, with or without `force`. The codegen fingerprint, `metaobjects:fmt` and `metaobjects:init` also compare before they write. - - **C#: a `contract-types` generator writes each entity's create and update records (ADR-0067 layer 1).** Opt-in, beside `entity`: add `new ContractTypesGenerator()` to `codegen/Generators.cs`. For each writable entity it writes `Contracts.g.cs` with `Create` and `Update`, @@ -70,6 +69,19 @@ here.** transitions get one. A model with no rules vocabulary gets no file. It is a layer generator, so the flat generators' output is unchanged and the codegen-noop rules corpus still holds them. The shared generator manifest gains the `rules-names` entry (C# only for now). +- **C#: the codegen project sets every `GenConfig` option.** `dotnet meta init` now writes a + `Generators.Configure` method beside the generator list, and `codegen/Program.cs` passes it to + `CodegenCli.Run`. It receives the config a run builds from its flags and `.metaobjects/config.json` + and returns the one the generators see. That makes the options no flag or config key sets + reachable on the normal path: `ContextTypeName`, `PropertyNaming`, `ProvidedEnumNamespace`, + `PackageNamespaces`, `TypeOverrides`, `Convention`, `UnmappedStrategy` and the rest. `gen` and + `verify --codegen` both apply it. An existing codegen project keeps working unchanged; to use it, + add the method and pass `Generators.Configure` as the third argument in `Program.cs`. +- **C#: an unknown top-level key in `.metaobjects/config.json` warns.** It was ignored without a word, + so a misspelt key (`scopes` for `scope`) did nothing. It is still ignored, and nothing fails, + because a newer MetaObjects may have written it, but each one is now named once on standard error + with the known keys, in the words TypeScript uses. A key inside a block C# owns (`csharp`, + `naming`, `wire` and the rest) is refused as before. - **C#: a `@sequenceStart` whose migrations project lacks the design-time services line is a generation error.** When `dotnet meta gen` can see the context's `ModelSnapshot.cs` in another project and that project does not carry `[assembly: DesignTimeServicesReference]`, the next `dotnet ef migrations add` diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index e8b0cefad1..73e79ac087 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -198,9 +198,24 @@ public static class Generators ```csharp // codegen/Program.cs using MetaObjects.Codegen; -return CodegenCli.Run(args, Generators.All); +return CodegenCli.Run(args, Generators.All, Generators.Configure); ``` +**Settings every generator shares.** The `GenConfig` options that no flag and no +`.metaobjects/config.json` key sets (`ContextTypeName`, `PropertyNaming`, `ProvidedEnumNamespace`, +`PackageNamespaces`, `TypeOverrides`, `Convention`, `UnmappedStrategy` and the rest) are set in +`Generators.Configure`, which `dotnet meta init` writes beside the list. It receives the config a run +builds from its flags and the project config, and returns the one the generators see: + +```csharp +public static GenConfig Configure(GenConfig config) => + config with { ContextTypeName = "ShopDbContext", ProvidedEnumNamespace = "Shop.Domain" }; +``` + +`gen` and `verify --codegen` both apply it, so verify regenerates what gen wrote. A codegen project +from before 1.3.0 has no `Configure`: add the method, and pass it as the third argument in +`Program.cs`. `init` never edits a file that exists. + Replace the empty list `dotnet meta init` wrote with the one above before the first `gen`: with an empty list `gen` writes nothing, and it needs an output directory (`--out`, or `csharp.outDir` in `.metaobjects/config.json`, below). @@ -241,8 +256,8 @@ namespace. Setting `--namespace` or `csharp.namespace` switches the default off no binding places in that one flat namespace. The namespace must be a dotted path of C# identifiers. `dotnet meta gen` and `verify` read that flat namespace and, through `csharp.packageNamespaces`, the package bindings (below). The finer per-package bindings -(`TypeOverrides`, `Convention`, `UnmappedStrategy`) are `GenConfig` properties, set when you run -codegen from your own code with `CodegenRunner`. +(`TypeOverrides`, `Convention`, `UnmappedStrategy`) are `GenConfig` properties, set in +`Generators.Configure` (above). **Package-keyed output (opt-in).** Two more `csharp` keys change where files land and which namespace a packaged type takes; a project that sets neither keeps the flat layout and the @@ -475,7 +490,7 @@ The codegen emits: ### Entity and DbContext generator options **Renaming a property.** A field's C# property is its PascalCased name. To spell some -differently (an acronym, say), set one resolver on the config, `GenConfig.PropertyNaming` +differently (an acronym, say), set one resolver on the config in `Generators.Configure`, `GenConfig.PropertyNaming` (`Func`, returning the name). The entity classes, the composite `[PrimaryKey(nameof(...))]`, every `AppDbContext` model line and the reverse finders all read it, so the declaration and every reference agree. The hooks `EntityGenerator.PropertyName` and diff --git a/server/csharp/MetaObjects.Cli.Tests/GenConfigureTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenConfigureTests.cs new file mode 100644 index 0000000000..92c5cfc182 --- /dev/null +++ b/server/csharp/MetaObjects.Cli.Tests/GenConfigureTests.cs @@ -0,0 +1,68 @@ +using MetaObjects.Codegen; +using Xunit; + +namespace MetaObjects.Cli.Tests; + +/// +/// T11-CS: the codegen project dotnet meta init writes passes Generators.Configure to +/// , so a +/// option no flag or config key sets (here ) +/// reaches the generators. verify --codegen applies the same settings, so it agrees with gen. +/// +[Collection(OwnedRunnerCollection.Name)] +public sealed class GenConfigureTests : IDisposable +{ + private readonly string _tmp = Path.Combine(Path.GetTempPath(), "meta-gen-configure-" + Guid.NewGuid().ToString("N")); + private string MetaDir => Path.Combine(_tmp, "metaobjects"); + private string OutDir => Path.Combine(_tmp, "out"); + + private const string Model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Talk", "children": [ + { "source.rdb": { "@table": "talks" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "title" } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """; + + private static GenConfig Configure(GenConfig config) => + config with { PropertyNaming = f => f.Name == "title" ? "Headline" : char.ToUpperInvariant(f.Name[0]) + f.Name[1..] }; + + public GenConfigureTests() + { + Directory.CreateDirectory(MetaDir); + File.WriteAllText(Path.Combine(MetaDir, "meta.acme.json"), Model); + } + + public void Dispose() { try { Directory.Delete(_tmp, recursive: true); } catch { } } + + private string TalkSource() => File.ReadAllText(Directory.EnumerateFiles(OutDir, "Talk.g.cs", SearchOption.AllDirectories).Single()); + + [Fact] + public void Gen_applies_the_projects_settings_and_verify_agrees() + { + var declared = OwnedRunner.Declared(_tmp, "entity"); + var gen = OwnedRunner.Run(_tmp, declared, Configure, "gen", MetaDir, "--out", OutDir, "--namespace", "Acme"); + Assert.True(gen.ExitCode == 0, gen.Stderr); + Assert.Contains(" Headline ", TalkSource()); + Assert.DoesNotContain(" Title ", TalkSource()); + + var verify = OwnedRunner.Run(_tmp, declared, Configure, "verify", "--codegen", MetaDir, "--out", OutDir, "--namespace", "Acme", "--full"); + Assert.True(verify.ExitCode == 0, verify.Stderr); + + // Without the settings the same list writes the default name, so the committed output drifts. + var bare = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", MetaDir, "--out", OutDir, "--namespace", "Acme", "--full"); + Assert.Equal(1, bare.ExitCode); + Assert.Contains("Talk.g.cs", bare.Stderr); + } + + [Fact] + public void Without_settings_gen_writes_the_default_property_name() + { + var run = OwnedRunner.Run(_tmp, ["entity"], "gen", MetaDir, "--out", OutDir, "--namespace", "Acme"); + Assert.True(run.ExitCode == 0, run.Stderr); + Assert.Contains(" Title ", TalkSource()); + } +} diff --git a/server/csharp/MetaObjects.Cli.Tests/OneGeneratorListTests.cs b/server/csharp/MetaObjects.Cli.Tests/OneGeneratorListTests.cs index ff667317f2..0e4ca373b3 100644 --- a/server/csharp/MetaObjects.Cli.Tests/OneGeneratorListTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/OneGeneratorListTests.cs @@ -260,7 +260,7 @@ public void Init_writes_the_three_files_and_keeps_the_ones_that_exist() Assert.Contains(" wrote codegen/Codegen.csproj", lines); Assert.Equal(CodegenScaffold.ProgramCs, File.ReadAllText(Path.Combine(_tmp, "codegen", "Program.cs"))); Assert.Equal( - "using MetaObjects.Codegen;\nreturn CodegenCli.Run(args, Generators.All);", + "using MetaObjects.Codegen;\nreturn CodegenCli.Run(args, Generators.All, Generators.Configure);", string.Join("\n", CodegenScaffold.ProgramCs.Split('\n').Where(l => l.Length > 0 && !l.StartsWith("//", StringComparison.Ordinal)))); var list = File.ReadAllText(Path.Combine(_tmp, "codegen", "Generators.cs")); Assert.Equal(CodegenScaffold.GeneratorsCs([]), list); diff --git a/server/csharp/MetaObjects.Cli.Tests/OwnedRunner.cs b/server/csharp/MetaObjects.Cli.Tests/OwnedRunner.cs index 0b5a951579..2a6a5835f9 100644 --- a/server/csharp/MetaObjects.Cli.Tests/OwnedRunner.cs +++ b/server/csharp/MetaObjects.Cli.Tests/OwnedRunner.cs @@ -27,7 +27,12 @@ internal static IReadOnlyList Declared(string workingDir, params str /// Run CodegenCli.Run(args, declared) from , capturing /// stdout and stderr. internal static (int ExitCode, string Stdout, string Stderr) Run( - string workingDir, IReadOnlyList declared, params string[] args) + string workingDir, IReadOnlyList declared, params string[] args) => + Run(workingDir, declared, null, args); + + /// As above, with the project's Generators.Configure: CodegenCli.Run(args, declared, configure). + internal static (int ExitCode, string Stdout, string Stderr) Run( + string workingDir, IReadOnlyList declared, Func? configure, params string[] args) { lock (Gate) { @@ -38,7 +43,7 @@ internal static (int ExitCode, string Stdout, string Stderr) Run( Directory.SetCurrentDirectory(workingDir); Console.SetOut(outWriter); Console.SetError(errWriter); - var exit = CodegenCli.Run(args, declared); + var exit = CodegenCli.Run(args, declared, configure); return (exit, outWriter.ToString(), errWriter.ToString()); } finally diff --git a/server/csharp/MetaObjects.Cli/InitCommand.cs b/server/csharp/MetaObjects.Cli/InitCommand.cs index cd37d7e512..db6bac45d5 100644 --- a/server/csharp/MetaObjects.Cli/InitCommand.cs +++ b/server/csharp/MetaObjects.Cli/InitCommand.cs @@ -43,12 +43,12 @@ public static class CodegenScaffold /// codegen/Codegen.csproj, pinning MetaObjects.Codegen to the tool's own version. public static string Csproj() => CsprojTemplate.Replace("{VERSION}", EjectCommand.ToolVersion()); - /// codegen/Program.cs: the two-line entry point that runs the list. + /// codegen/Program.cs: the two-line entry point that runs the list with the project's settings. public const string ProgramCs = "// Runs the generator list in Generators.cs. `dotnet meta gen` and `dotnet meta verify --codegen`\n" + "// run this project (`dotnet run --project codegen -- `); see MetaObjects.Codegen.CodegenCli.Run.\n" + "using MetaObjects.Codegen;\n" + - "return CodegenCli.Run(args, Generators.All);\n"; + "return CodegenCli.Run(args, Generators.All, Generators.Configure);\n"; /// @@ -82,6 +82,17 @@ public static string GeneratorsCs(IEnumerable entries) " [\n" + lines + " ];\n" + + "\n" + + " // The settings every generator in the list shares (MetaObjects.Codegen.GenConfig). `config`\n" + + " // arrives filled in from the gen flags and .metaobjects/config.json; return it with the\n" + + " // options you want changed. `gen` and `verify --codegen` both apply it. For example:\n" + + " // config with\n" + + " // {\n" + + " // ContextTypeName = \"ShopDbContext\",\n" + + " // ProvidedEnumNamespace = \"Shop.Domain\",\n" + + " // PackageNamespaces = new() { [\"shop::billing\"] = \"Shop.Billing\" },\n" + + " // }\n" + + " public static GenConfig Configure(GenConfig config) => config;\n" + "}\n"; } diff --git a/server/csharp/MetaObjects.Codegen/CodegenCli.cs b/server/csharp/MetaObjects.Codegen/CodegenCli.cs index 961ed8aa47..0e9147c399 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenCli.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenCli.cs @@ -225,13 +225,18 @@ public static GenOutcome RunGen( /// is the project's WHOLE list, so a recorded file none of /// them emitted is stale output and is deleted when untouched (). /// + /// + /// The project's own settings (Generators.Configure in codegen/Generators.cs), + /// applied to the config this method builds, last. null keeps it as built. + /// public static GenOutcome RunGen( LoadResult load, string outDir, string? ns, bool emitAbstractShapes, IReadOnlyList generators, string? projectRoot = null, string baseline = "default", bool? includeNames = null, bool sweepOrphans = false, - IReadOnlyList? entities = null) + IReadOnlyList? entities = null, + Func? configure = null) { var loadErrors = load.Errors.Select(e => e.Code.ToString()).ToList(); if (loadErrors.Count > 0) return new GenOutcome(loadErrors, null); @@ -265,6 +270,7 @@ public static GenOutcome RunGen( ForeignKeyIndexes = neutralConfig?.MigrateForeignKeyIndexes ?? false, SchemaConventions = neutralConfig?.MigrateConventions, }.WithCSharpLayout(neutralConfig); + if (configure is not null) config = configure(config); CodegenRunner.RunResult result; try @@ -450,7 +456,16 @@ private static IReadOnlyList RegistryNames(IReadOnlyList gen /// CodegenCli.Run(args, Generators.All). Dispatches on args[0] ("gen" /// or "verify"), prints to the console, and returns the process exit code. /// - public static int Run(string[] args, IReadOnlyList generators) + public static int Run(string[] args, IReadOnlyList generators) => Run(args, generators, null); + + /// + /// , with the project's own settings: + /// receives the a run builds from its flags and + /// .metaobjects/config.json and returns the one the generators see. gen and + /// verify --codegen both apply it, so verify regenerates exactly what gen wrote. The + /// scaffold dotnet meta init writes passes Generators.Configure. + /// + public static int Run(string[] args, IReadOnlyList generators, Func? configure) { if (args.Length == 0) { @@ -464,8 +479,8 @@ public static int Run(string[] args, IReadOnlyList generators) } return args[0] switch { - "gen" => RunGenArgs(args[1..], generators), - "verify" => RunVerifyArgs(args[1..], generators), + "gen" => RunGenArgs(args[1..], generators, configure), + "verify" => RunVerifyArgs(args[1..], generators, configure), "docs" => Removed(), _ => Unknown(args[0]), }; @@ -680,10 +695,10 @@ private static bool TryConfiguredOutDir(string? metadataDir, out string? outDir) /// vouches for the output. private sealed class KeyGate { public string? ProjectRoot; public bool Keep; } - private static int RunGenArgs(string[] rest, IReadOnlyList declared) + private static int RunGenArgs(string[] rest, IReadOnlyList declared, Func? configure) { var gate = new KeyGate(); - try { return RunGenCore(rest, declared, gate); } + try { return RunGenCore(rest, declared, gate, configure); } finally { if (gate.ProjectRoot is { } root && !gate.Keep) GenFingerprint.Delete(root); } } @@ -694,7 +709,7 @@ private static int RunGenArgs(string[] rest, IReadOnlyList declared) TemplateSpec = a.TemplateSpecPath, Entities = a.Entities, EmitAbstractShapes = a.EmitAbstractShapes, Strict = a.Strict, Baseline = a.Baseline, }; - private static int RunGenCore(string[] rest, IReadOnlyList declared, KeyGate gate) + private static int RunGenCore(string[] rest, IReadOnlyList declared, KeyGate gate, Func? configure) { var a = OwnedArgs.Parse(rest, GenCommandName, GenValueFlags, GenBoolFlags); if (a.Refusal is not null) @@ -844,7 +859,8 @@ private static int RunGenCore(string[] rest, IReadOnlyList declared, // Only a run of the whole declared list can tell a stale file from one the // narrowing left out; --entities narrows the same way, so it never sweeps either. sweepOrphans: a.Selection is not { Count: > 0 } && a.Entities is null, - entities: a.Entities); + entities: a.Entities, + configure: configure); if (!outcome.Ok) { ReportFailure(outcome, GenCommandName); @@ -967,7 +983,7 @@ private static string WireDiffers(WireFormat committed, WireFormat used) => "JSON your API writes for decimals, durations or a value object's null members. Declare " + $"{committed.Block()} in .metaobjects/config.json, and gen and verify --codegen both read it."; - private static int RunVerifyArgs(string[] rest, IReadOnlyList declared) + private static int RunVerifyArgs(string[] rest, IReadOnlyList declared, Func? configure) { var a = OwnedArgs.Parse(rest, VerifyCommandName, VerifyValueFlags, VerifyBoolFlags); if (a.Refusal is not null) @@ -1071,6 +1087,7 @@ private static int RunVerifyArgs(string[] rest, IReadOnlyList declar ForeignKeyIndexes = neutralConfig?.MigrateForeignKeyIndexes ?? false, SchemaConventions = neutralConfig?.MigrateConventions, }.WithCSharpLayout(neutralConfig); + if (configure is not null) config = configure(config); // ADR-0064: locally, an unchanged key and output that still hashes to what gen recorded answer // "no drift" without rendering. CI and --full always render. if (a.Entities is null && suite.All(g => g.Cacheable) && GenFingerprint.MayAnswerNoDrift( diff --git a/server/csharp/MetaObjects.Conformance.Tests/NeutralConfigUnknownKeyTests.cs b/server/csharp/MetaObjects.Conformance.Tests/NeutralConfigUnknownKeyTests.cs new file mode 100644 index 0000000000..8d98d3a036 --- /dev/null +++ b/server/csharp/MetaObjects.Conformance.Tests/NeutralConfigUnknownKeyTests.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using MetaObjects; +using MetaObjects.Config; +using Xunit; + +namespace MetaObjects.Conformance.Tests; + +/// +/// An unknown top-level key in .metaobjects/config.json warns and is ignored, as in TypeScript's +/// loadConfig: the file is shared by every port and version, so a key a newer MetaObjects wrote +/// must not fail the load, while a misspelling is named. A key inside a block this port owns stays +/// refused. The oracle is TypeScript's behaviour and its warning text (sdk/src/config.ts). +/// +public sealed class NeutralConfigUnknownKeyTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "mo-cfg-unknown-" + Guid.NewGuid().ToString("N")); + private readonly List _warnings = []; + private readonly Action _previous; + + public NeutralConfigUnknownKeyTests() + { + Directory.CreateDirectory(Path.Combine(_root, ".metaobjects")); + _previous = NeutralConfig.WarningSink; + // Other test classes may read their own configs meanwhile: keep only this project's lines. + NeutralConfig.WarningSink = m => { lock (_warnings) if (m.Contains(_root, StringComparison.Ordinal)) _warnings.Add(m); }; + } + + public void Dispose() + { + NeutralConfig.WarningSink = _previous; + try { Directory.Delete(_root, recursive: true); } catch (IOException) { } + } + + private void WriteConfig(string json) => File.WriteAllText(Path.Combine(_root, ".metaobjects", "config.json"), json); + + [Fact] + public void An_unknown_top_level_key_warns_once_naming_it_and_the_load_succeeds() + { + WriteConfig("{\"schema_version\":1,\"scopes\":{\"include\":[]},\"futureKey\":1}"); + + Assert.NotNull(NeutralConfig.Read(_root)); + Assert.NotNull(NeutralConfig.Read(_root)); + + Assert.Equal(2, _warnings.Count); + var scopes = Assert.Single(_warnings, w => w.Contains("\"scopes\"", StringComparison.Ordinal)); + Assert.StartsWith("warning: ", scopes); + Assert.Contains("unknown top-level key \"scopes\" ignored", scopes); + Assert.Contains("remove the key if it is a misspelling", scopes); + Assert.Contains("Known keys: schema_version,", scopes); + Assert.Contains(" scope,", scopes); + Assert.Single(_warnings, w => w.Contains("unknown top-level key \"futureKey\" ignored", StringComparison.Ordinal)); + } + + [Fact] + public void Keys_TypeScript_owns_are_not_unknown() + { + // Keys this port never reads but TypeScript's schema declares: not a typo, no warning. + WriteConfig("{\"schema_version\":1,\"pending_in_git\":true,\"confidence_thresholds\":{},\"extract\":{}," + + "\"scope\":{\"exclude\":[]},\"migrate\":{\"dialect\":\"postgres\"}}"); + + Assert.NotNull(NeutralConfig.Read(_root)); + + Assert.Empty(_warnings); + } + + [Fact] + public void An_unknown_key_inside_a_block_this_port_owns_is_still_refused() + { + WriteConfig("{\"schema_version\":1,\"csharp\":{\"outDirr\":\"Generated\"}}"); + + var ex = Assert.Throws(() => NeutralConfig.Read(_root)); + Assert.Contains("\"csharp\" has an unknown key \"outDirr\"", ex.Message); + } +} diff --git a/server/csharp/MetaObjects.Conformance.Tests/SourceResolverTests.cs b/server/csharp/MetaObjects.Conformance.Tests/SourceResolverTests.cs index 19ccd427bc..4d836b0e7e 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/SourceResolverTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/SourceResolverTests.cs @@ -44,13 +44,10 @@ public void TwoUnresolvablePaths_ReportsTheContentFirstOne() } /// - /// A genuinely unknown top-level key resolves normally here, and THROWS in - /// TypeScript. That asymmetry is ruled INTENDED in the source-resolution corpus - /// README: TypeScript owns this file and models its whole vocabulary, so only it - /// can tell a typo from a key a sibling owns. This port models the neutral subset - /// (`schema_version` + `sources`), for which every other key is indistinguishable - /// from a TypeScript-owned one — imitating strictness would mean carrying TS's key - /// list and rejecting a config a newer `meta` had just written. + /// A genuinely unknown top-level key resolves normally here: it is never rejected, + /// because a newer `meta` may have just written it. Since 1.3.0 this port warns about + /// it, as TypeScript does (NeutralConfigUnknownKeyTests); the resolution itself is + /// unchanged. /// /// /// Deliberately NOT a shared corpus case: a shared case asserts one outcome and diff --git a/server/csharp/MetaObjects/Config/NeutralConfig.cs b/server/csharp/MetaObjects/Config/NeutralConfig.cs index f981c01bde..229f89b954 100644 --- a/server/csharp/MetaObjects/Config/NeutralConfig.cs +++ b/server/csharp/MetaObjects/Config/NeutralConfig.cs @@ -5,7 +5,10 @@ // TypeScript-owned keys (`pending_in_git`, `confidence_thresholds`, `extract`, and the rest of // `migrate` and `scope`); those are IGNORED rather than modeled, so a new TS-only key never becomes // a four-port change. See -// docs/superpowers/specs/2026-08-19-cross-port-metadata-sources-design.md §4. +// docs/superpowers/specs/2026-08-19-cross-port-metadata-sources-design.md §4. A top-level key that +// is in no port's vocabulary (TopLevelKeys, TypeScript's list) WARNS, as it does in TypeScript, and +// is still ignored: a new top-level key TypeScript adds is one line in TopLevelKeys, or this port +// names it in a warning until then. // // `dependencies` (FR-023) is read at EVERY rung of the source ladder, including the explicit // metadata directory a C# command is handed, because this port has no native config surface of its @@ -172,6 +175,39 @@ private NeutralConfig( /// not code, for this path. public static NeutralConfig? Read(string configDir) => Read(configDir, validateNaming: true); + /// + /// The top-level keys of .metaobjects/config.json any MetaObjects port reads. TypeScript owns + /// the file and models its whole vocabulary, so this is its schema's key list + /// (CONFIG_TOP_LEVEL_KEYS in @metaobjectsdev/sdk), in the same order. + /// + public static readonly IReadOnlyList TopLevelKeys = + [ + "schema_version", "pending_in_git", "confidence_thresholds", "sources", "dependencies", "libraries", + "scope", "extract", "migrate", "verify", "requirements", "naming", "wire", "api", "enums", "rules", "csharp", + ]; + + /// Where an unknown-key warning goes: standard error unless a host replaces it. + public static Action WarningSink { get; set; } = m => Console.Error.WriteLine(m); + + private static readonly HashSet WarnedKeys = []; + + /// + /// Warn once per file and key, through , for each top-level key not in + /// . The words are TypeScript's loadConfig warning. + /// + private static void WarnUnknownTopLevelKeys(JsonElement root, string path) + { + foreach (var p in root.EnumerateObject()) + { + if (TopLevelKeys.Contains(p.Name)) continue; + lock (WarnedKeys) + if (!WarnedKeys.Add(path + "\0" + p.Name)) continue; + WarningSink( + $"warning: {path}: unknown top-level key \"{p.Name}\" ignored. A newer MetaObjects may have written it; " + + $"upgrade this tool, or remove the key if it is a misspelling. Known keys: {string.Join(", ", TopLevelKeys)}."); + } + } + /// `migrate.checks.skipRedundant`, as the TypeScript `meta migrate` reads it; false when absent or not a boolean. private static bool ReadMigrateSkipRedundant(JsonElement root) => root.TryGetProperty("migrate", out var migrate) && migrate.ValueKind == JsonValueKind.Object @@ -382,8 +418,11 @@ private static bool ReadMigrateForeignKeyIndexes(JsonElement root) => } } - // Unknown top-level keys, and every key of `scope` / `migrate` but the two pattern - // lists read above, are IGNORED by design — see the file header. + // An unknown top-level key WARNS and is ignored, as in TypeScript: a newer MetaObjects or a + // sibling port may have written it, so it must not fail the load (forward tolerance), but a + // misspelling is named. Every key of `scope` / `migrate` but the pattern lists read above is + // TypeScript-owned and ignored. + WarnUnknownTopLevelKeys(root, path); return new NeutralConfig(specs, libraries, new PhysicalNaming(columns, tables) { Collections = collections }, ReadWire(root, path), ReadCSharp(root, path, configDir), dependencies, scopeInclude, migrateScope, Path.GetFullPath(configDir)) From 091d6eaf45a2d2111bd39dee0f9efc50cb7ce63a Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 16:35:37 -0500 Subject: [PATCH 4/6] no-mistakes(review): harden contract Update record binding and members --- .../ContractTypesGeneratorTests.cs | 44 ++++++++++++++++++- .../Generators/ContractTypesGenerator.cs | 13 +++++- 2 files changed, 53 insertions(+), 4 deletions(-) diff --git a/server/csharp/MetaObjects.Codegen.Tests/ContractTypesGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ContractTypesGeneratorTests.cs index 7641bef154..19b04d3bfc 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ContractTypesGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ContractTypesGeneratorTests.cs @@ -43,6 +43,7 @@ public class ContractTypesGeneratorTests { "field.object": { "name": "shipTo", "@objectRef": "Address", "@storage": "jsonb" } }, { "field.timestamp": { "name": "createdAt", "@autoSet": "onCreate" } }, { "field.string": { "name": "legacyCode", "@mutability": "readOnly" } }, + { "field.string": { "name": "sku", "@mutability": "writeOnce" } }, { "field.enum": { "name": "status", "@values": ["open", "closed"], "@default": "open", "children": [ { "transition.action": { "name": "close", "@from": ["open"], "@to": "closed" } } ] } } ] } }, @@ -108,8 +109,8 @@ private static List Errors(object instance) [Fact] public void The_create_record_carries_what_a_client_sends_and_nothing_the_server_owns() { - // Generated key, @autoSet stamp and readOnly field are the server's; the lifecycle field stays. - Assert.Equal(["title", "note", "quantity", "channel", "tags", "shipTo", "status"], WireNames(T("OrderCreate"))); + // Generated key, @autoSet stamp and readOnly field are the server's; writeOnce and the lifecycle field stay. + Assert.Equal(["title", "note", "quantity", "channel", "tags", "shipTo", "sku", "status"], WireNames(T("OrderCreate"))); // A key the client chooses (no @generation) is part of the create body. Assert.Equal(["code", "label"], WireNames(T("TagCreate"))); } @@ -189,6 +190,45 @@ public void An_update_keeps_the_lifecycle_field_so_the_service_can_refuse_it() Assert.Equal("closed", Get(u, "Status")!.ToString()); } + [Fact] + public void A_write_once_field_is_on_create_and_off_update() + { + Assert.Contains("sku", WireNames(T("OrderCreate"))); + Assert.DoesNotContain("sku", WireNames(T("OrderUpdate"))); + var u = Update("""{"sku": "x"}"""); + Assert.False((bool)u.GetType().GetMethod("Has")!.Invoke(u, ["sku"])!); + } + + [Fact] + public void An_update_from_a_body_that_is_not_an_object_is_a_JsonException() + { + var from = T("OrderUpdate").GetMethod("From")!; + foreach (var json in new[] { "null", "[]", "3" }) + { + var ex = Assert.Throws(() => from.Invoke(null, [JsonDocument.Parse(json).RootElement, Web])); + Assert.IsAssignableFrom(ex.InnerException); + } + } + + [Fact] + public void A_field_named_like_a_fixed_update_member_is_refused_at_generation() + { + const string clash = """ + { "metadata.root": { "package": "acme::forms", "children": [ + { "object.entity": { "name": "Form", "children": [ + { "source.rdb": { "@table": "forms" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } }, + { "field.string": { "name": "fields" } } ] } } ] } } + """; + var r = new MetaDataLoader().Load([new InMemoryStringSource(clash, id: "forms.json")]); + Assert.Empty(r.Errors); + var ctx = new GenContext { Entities = r.Root.Objects(), Root = r.Root, Config = new GenConfig { OutDir = "/unused", Namespace = Ns } }; + var ex = Assert.Throws(() => new ContractTypesGenerator().Generate(ctx).ToList()); + Assert.Contains("Form.fields", ex.Message); + Assert.Contains("FormUpdate", ex.Message); + } + [Fact] public void A_projection_and_a_value_object_get_no_records() { diff --git a/server/csharp/MetaObjects.Codegen/Generators/ContractTypesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ContractTypesGenerator.cs index 64045e10f1..94d216c66a 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ContractTypesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ContractTypesGenerator.cs @@ -12,7 +12,8 @@ // // Neither carries what the server owns: a derived (origin.*) field, an @autoSet stamp, a readOnly // field, a TPH discriminator. A generated key (@generation increment or uuid) is left off the -// create record; every key is left off the update record, because the route names the row. +// create record; every key is left off the update record, because the route names the row. A +// writeOnce field is frozen after create, so it is on the create record and not on the update record. // A lifecycle field is on both: the service shell checks a create against the initial state and // refuses a change on the generic update with 409 state_managed (ADR-0066 §6), and to refuse it the // shell has to see it. @@ -89,7 +90,7 @@ protected virtual IReadOnlyList CreateFields(MetaObject entity, GenCo protected virtual IReadOnlyList UpdateFields(MetaObject entity, GenContext ctx) { var key = (entity.PrimaryIdentity()?.Fields ?? []).ToHashSet(StringComparer.Ordinal); - return entity.Fields().Where(f => !ServerOwned(entity, f, ctx) && !key.Contains(f.Name)).ToList(); + return entity.Fields().Where(f => !ServerOwned(entity, f, ctx) && !f.IsWriteOnceMutability && !key.Contains(f.Name)).ToList(); } /// Whether a create body must carry the member: it is required and has no @default to fall back to. @@ -130,10 +131,17 @@ protected virtual void WriteCreateRecord(CsWriter w, MetaObject entity, IReadOnl } } + private static readonly string[] ReservedUpdateMembers = ["Fields", "Present", "Has", "From", "Validate"]; + /// The update record, with its From binder and the present-null check. protected virtual void WriteUpdateRecord(CsWriter w, MetaObject entity, IReadOnlyList fields, GenContext ctx) { var name = UpdateName(entity); + foreach (var f in fields) + if (ReservedUpdateMembers.Contains(CSharpNaming.PropertyName(f, ctx.Config))) + throw new InvalidOperationException( + $"contract-types: {entity.Name}.{f.Name} becomes the C# member \"{CSharpNaming.PropertyName(f, ctx.Config)}\", " + + $"which {name} already declares ({string.Join(", ", ReservedUpdateMembers)}). Rename the field."); w.DocSummary($"GENERATED — the body that changes a {CSharpNaming.Pascal(entity.Name)}. Every member is optional: " + "bind it with From, and Has tells an omitted member (untouched) from an explicit null (cleared)."); using (w.Braced($"public sealed record {name} : IValidatableObject")) @@ -155,6 +163,7 @@ protected virtual void WriteUpdateRecord(CsWriter w, MetaObject entity, IReadOnl w.DocSummary("Bind a body with the application's JSON options and record which members it carried."); using (w.Braced($"public static {name} From(JsonElement body, JsonSerializerOptions? options = null)")) { + w.Line("if (body.ValueKind != JsonValueKind.Object) throw new JsonException(\"The update body must be a JSON object.\");"); w.Line($"var bound = body.Deserialize<{name}>(options) ?? new {name}();"); w.Line("var comparer = options?.PropertyNameCaseInsensitive == true ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;"); w.Line("var present = new HashSet(StringComparer.Ordinal);"); From d63084c5894eed270eeca298d82f4da8f1b56177 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 16:36:40 -0500 Subject: [PATCH 5/6] no-mistakes(review): apply reviewer inline fixes --- CHANGELOG.md | 3 ++- docs/ports/csharp.md | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0aeb09a270..58140a2a8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,7 +52,8 @@ here.** `sealed record`s carrying the entity's validation attributes and wire converters. Neither carries what the server owns: a generated key, an `@autoSet` stamp, a `readOnly` or derived field, a TPH discriminator. A required member with no `@default` is a `required` member of the create record, so - a body that omits it does not bind. Every update member is optional; `Update.From` binds a + a body that omits it does not bind. A `writeOnce` field is on the create record and off the update + record, since it is frozen after create. Every update member is optional; `Update.From` binds a body and records which keys it carried, so `Has` tells an omitted member (untouched) from an explicit null (cleared), and validation refuses null on a required member. The lifecycle field stays on both, so the service shell can check it and refuse a change with `409 state_managed`. The diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 73e79ac087..9b6b438164 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -826,8 +826,9 @@ each writable entity (a concrete `object.entity` with a writable primary source) server generates (`@generation: increment` or `uuid`). A key the client chooses stays. A member that is required and has no `@default` is a C# `required` member, so System.Text.Json refuses a body that omits it. -- `Update`: what a client may change. It leaves off the same server-owned members and every - key field, since the route names the row. Every member is optional. Bind it with +- `Update`: what a client may change. It leaves off the same server-owned members, every + key field (the route names the row) and a `writeOnce` field (frozen after create; it stays on + `Create`). Every member is optional. Bind it with `Update.From(body, options)`, which records the keys the body carried: `Has("note")` is true for `{"note": null}` and false for `{}`, so a PATCH can leave an omitted member alone and clear an explicit null. `Validate` refuses null on a required member. From dc03fea2a107c796575944f5b19c54da55488ba9 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 16:52:00 -0500 Subject: [PATCH 6/6] no-mistakes(document): C# rules/contract generators; config warn docs --- docs/features/metadata-sources.md | 18 +++++++++++------- .../migrations/upgrading-1.0-to-1.1.md | 4 ++-- docs/features/own-your-codegen.md | 9 +++++---- docs/ports/csharp.md | 15 ++++++++++++--- 4 files changed, 30 insertions(+), 16 deletions(-) diff --git a/docs/features/metadata-sources.md b/docs/features/metadata-sources.md index 1155ce259b..0ae7b603b0 100644 --- a/docs/features/metadata-sources.md +++ b/docs/features/metadata-sources.md @@ -80,9 +80,10 @@ surfaces have no such limit. The non-TypeScript ports read a **neutral subset** of that file — `schema_version` and `sources` — and ignore every other top-level key, so the TypeScript-owned keys beside them (`migrate`, `extract`, and the rest) never -become a four-port concern. The Node CLI remains the file's only writer; -`meta init --config-only` writes it into a Maven- or pip-rooted project without -adding a TypeScript scaffold. +become a four-port concern. The C# port names an unknown top-level key on standard +error, once per key, and still ignores it ([C# port](../ports/csharp.md#configure)). +The Node CLI remains the file's only writer; `meta init --config-only` writes it into +a Maven- or pip-rooted project without adding a TypeScript scaffold. **`scope` and `migrate.scope` remain Node-CLI-only, but Java's `` name glob is the same grammar.** Since 8.2.0 the Maven plugin's `` patterns use `scope`'s @@ -173,8 +174,9 @@ Consequences worth knowing: Both parse (the config shape is fixed now so a later phase slots in without a config migration) and both throw `ERR_SOURCE_KIND_UNSUPPORTED` when the toolchain tries to resolve them. A misspelled key such as `{ "pathh": "model" }` is a **load error**, -not a silently ignored extra: `.metaobjects/config.json` is validated strictly, top -level and every nested block. +not a silently ignored extra: the TypeScript toolchain validates `.metaobjects/config.json` +strictly, top level and every nested block (the C# port warns on an unknown top-level key +instead; see [C# port](../ports/csharp.md#configure)). --- @@ -542,7 +544,8 @@ the per-level walk order layer 1 preserves is pinned by | `ERR_COLLECTION_NOT_FOUND` | No `sources` were declared **and** no default `metaobjects/` directory exists | A schema violation in `.metaobjects/config.json` itself (an unknown key, a wrong -type) surfaces as the config load error and stops the command. +type) surfaces as the TypeScript config load error and stops the command. The C# port +warns on an unknown top-level key and carries on. --- @@ -625,7 +628,8 @@ reproduce. `ConfigSchema` is `.strict()` at every level — the top level, `sources` entries, `scope`, `migrate`, and `migrate.d1`. A key that used to be silently dropped is now -a load error that stops the command. +a load error that stops the command. This is the TypeScript toolchain's rule; the C# port +keeps its top-level check a warning ([C# port](../ports/csharp.md#configure)). This is deliberate and it is the whole point: a stripped key means the setting you wrote does not exist, and the command runs as if you had never written it. diff --git a/docs/features/migrations/upgrading-1.0-to-1.1.md b/docs/features/migrations/upgrading-1.0-to-1.1.md index 7a6721c23c..036d95e9d8 100644 --- a/docs/features/migrations/upgrading-1.0-to-1.1.md +++ b/docs/features/migrations/upgrading-1.0-to-1.1.md @@ -21,8 +21,8 @@ skip them, so read the whole list before you regenerate. it ("Unrecognized key(s) in object: 'naming'"), but a 1.0.x C#, Java or Python tool ignores the unknown key without a word and keeps its old column names. A mixed estate therefore does not fail: the old port reads and writes columns named like the fields while the new ones use - `snake_case`. From 1.1.0 on, an unknown key there is a warning in TypeScript, so the next key - a release adds is not the same trap. + `snake_case`. From 1.1.0 on, an unknown key there is a warning in TypeScript, and from 1.3.0 on + in C#, so the next key a release adds is not the same trap. - **Mixed-version exports.** A 1.1 `meta export` file can hold a root-level reference written `::Name`, which 1.0.x refuses (`ERR_RELATIVE_REF_IN_CANONICAL`). Read 1.1 exports with 1.1 tools. diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index ae0eddd111..0fd4bf8f9c 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -1575,8 +1575,8 @@ writes its output through come with it The generator list is `codegen/Generators.cs` (ADR-0034 Amendment 9), compiled by the console project `codegen/Codegen.csproj` (referencing `MetaObjects.Codegen` at the tool's -version) and run by `codegen/Program.cs`, two lines that pass `Generators.All` to the public -runner. `dotnet meta init` writes the three files; eject writes each one that is missing, +version) and run by `codegen/Program.cs`, two lines that pass `Generators.All` and `Generators.Configure` +to the public runner. `dotnet meta init` writes the three files; eject writes each one that is missing, and when it writes `Generators.cs` the list holds the copies it just ejected, as `new Codegen.Generators.()`. After that all three are yours: eject never touches them again, even with `--force`, and prints the entry to add instead, in place of the packaged @@ -1613,7 +1613,8 @@ namespace: | Eject | Also writes | |---|---| -| `entity` | `Fr019SharedEnum.cs` (shared and provided enums), `M2MNavigation.cs` (the many-to-many navigation), `ReverseFinders.cs` (the reverse FK finders), `XmlDocBuilder.cs` (doc comments) | +| `entity` | `ContractMembers.cs` (the validation and wire-converter attributes), `Fr019SharedEnum.cs` (shared and provided enums), `M2MNavigation.cs` (the many-to-many navigation), `ReverseFinders.cs` (the reverse FK finders), `XmlDocBuilder.cs` (doc comments) | +| `contract-types` | `ContractMembers.cs`, `Fr019SharedEnum.cs`, `XmlDocBuilder.cs` | | `db-context` | `Fr019SharedEnum.cs`, `M2MNavigation.cs`, `XmlDocBuilder.cs` | | `routes` | `M2MNavigation.cs` | | `output-parser`, `extractor` | `ExtractDelegateEmitter.cs`, `Fr010FieldMapping.cs`; `extractor` also `Fr019SharedEnum.cs` | @@ -1651,7 +1652,7 @@ edits are untouched: ```bash scratch=$(mktemp -d) dotnet meta eject entity --root "$scratch" -cp "$scratch"/codegen/generators/{Fr019SharedEnum,M2MNavigation,ReverseFinders,XmlDocBuilder}.cs codegen/generators/ +cp "$scratch"/codegen/generators/{ContractMembers,Fr019SharedEnum,M2MNavigation,ReverseFinders,XmlDocBuilder}.cs codegen/generators/ dotnet meta gen --list # no longer reports an emitter missing ``` diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 9b6b438164..96b3cdd002 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -108,6 +108,12 @@ Drop metadata under `metaobjects/`, for example `metaobjects/meta.blog.json`: }} ``` +**Unknown top-level keys.** `dotnet meta` reads the top level of `.metaobjects/config.json` and +ignores any key the C# port does not model. A key in no port's vocabulary warns on standard error, +once per key, with the known keys, in TypeScript's words, and nothing fails: a newer MetaObjects may +have written the key. A key inside a block C# owns (`csharp`, `naming`, `wire` and the rest) is +refused as before. + ### Building on a shared model (optional) A model published from another repository is declared under `dependencies` in @@ -831,15 +837,18 @@ each writable entity (a concrete `object.entity` with a writable primary source) `Create`). Every member is optional. Bind it with `Update.From(body, options)`, which records the keys the body carried: `Has("note")` is true for `{"note": null}` and false for `{}`, so a PATCH can leave an omitted member alone and - clear an explicit null. `Validate` refuses null on a required member. + clear an explicit null. A body that is not a JSON object throws `JsonException`. `Validate` + refuses null on a required member. A field whose C# name is one of the record's own members + (`Fields`, `Present`, `Has`, `From`, `Validate`) is refused at generation, naming the entity and + the field; rename the field. Both records carry the entity's validation attributes (`[MaxLength]`, `[StringLength]`, `[Range]`, `[RegularExpression]`, `[EmailAddress]`, the array counts) and its wire converters (decimal, duration, strict uri/inet), written by `ContractMembers`, the one copy `EntityGenerator` writes its own from. A required string keeps its non-empty floor in both: on update it applies when the member is sent. Enum, value-object and map members name the entity's own types, so `entity` runs in the -same project (`Requires: entity`). Bind with the application's JSON options; a generated server -registers `JsonStringEnumConverter`, which an enum member needs. +same project (`Requires: entity`). Bind with the application's JSON options; an enum member needs the +`JsonStringEnumConverter` the application registers (see [Use](#use)). The lifecycle field stays on both records. The service shell checks a create against the initial state and refuses a change on the generic update with `409 state_managed` (ADR-0066 §6), so it has