Skip to content

Commit f045112

Browse files
committed
feat(csharp): ADR-0036 Wave 3 — field.uri, field.inet subtypes + @stringformat
Implements the C# port of ADR-0036 decision #2 / ADR-0037, matching the TS reference golden byte-for-byte (registry-conformance + descriptions). Metamodel / registry (matches the shared golden): - field.uri — a URI/URL string. Native CLR binding = System.Uri; DB column = text. - field.inet — an IP-address string (v4/v6). Native CLR = System.Net.IPAddress; DB column = Postgres-native inet. Both string-backed on the wire (DataType.String). - @stringformat on field.string — closed set {email|hostname}, emitted as allowedValues in the registry manifest (Wave-1 gate). Strict attr scoping keeps it on field.string only. - Descriptions / whenToUse byte-match the golden via the embedded SpecMetamodel/field.json copy (refreshed from spec/metamodel/field.json). Codegen (EntityGenerator / DbContextGenerator / CSharpNaming): - field.uri → Uri property; DbContext HasColumnType("text").HasConversion(Uri↔string). - field.inet → IPAddress property (+ using System.Net;); DbContext HasColumnType("inet"). - @stringformat email → [EmailAddress]; hostname → codegen-owned canonical RFC-1123 [RegularExpression] (byte-identical to the TS Zod source), never author regex. - Op-bands: uri = string-like (eq/ne/in/like/isNull); inet = uuid-like (eq/ne/in/isNull, no like/ordering). Tests: MetaObjects Conformance 670/670 (incl. new field-uri-inet-stringformat fixture + registry-manifest byte-match), Codegen 252/252, Render 290, CLI 42, IntegrationTests 82/82 (Testcontainers PG). Generated entity compile-verified. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GF9xLEQZaPus5Y6opk398n
1 parent 4b90500 commit f045112

8 files changed

Lines changed: 150 additions & 3 deletions

File tree

‎server/csharp/MetaObjects.Codegen/CSharpNaming.cs‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,27 @@ public static class CSharpNaming
5454
// (ADR-0001), independent of its string wire form. The native uuid DB
5555
// column is a separate migrate-engine concern (SubtypeToSqlType).
5656
[FIELD_SUBTYPE_UUID] = "Guid",
57+
// ADR-0036 Wave 3 — field.uri binds to the native System.Uri reference type
58+
// (DB column is text); field.inet binds to System.Net.IPAddress (DB column is
59+
// the Postgres-native inet type). Both are string-backed on the wire.
60+
[FIELD_SUBTYPE_URI] = "Uri",
61+
[FIELD_SUBTYPE_INET] = "IPAddress",
5762
};
5863

5964
/// <summary>Value types that take a <c>?</c> suffix when nullable (vs. reference types).</summary>
6065
private static readonly HashSet<string> ValueTypes = new(StringComparer.Ordinal)
6166
{ "int", "long", "double", "float", "decimal", "bool", "DateOnly", "TimeOnly", "DateTime", "DateTimeOffset", "Guid" };
6267

68+
/// <summary>
69+
/// ADR-0036 Wave 3 — the CANONICAL hostname matcher for <c>@stringFormat: hostname</c>,
70+
/// emitted into a <c>[RegularExpression(@"...")]</c> verbatim string literal. The matcher
71+
/// lives in codegen (NOT author <c>validator.regex</c>) so every port replicates the SAME
72+
/// canonical form. RFC-1123 labels: 1–63 chars each, alphanumeric + internal hyphens,
73+
/// dot-separated; total ≤253, anchored. Byte-identical to the TS Zod <c>.regex(...)</c> source.
74+
/// </summary>
75+
public const string HostnameRegex =
76+
@"^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$";
77+
6378
/// <summary>The base C# scalar type for a field subtype (no nullability), or null for object fields.</summary>
6479
public static string? ScalarFor(string fieldSubType) =>
6580
ScalarType.GetValueOrDefault(fieldSubType);
@@ -108,6 +123,12 @@ public static bool IsLocalTime(MetaField field) =>
108123
public static bool RequiresSystemTextJson(MetaObject obj) =>
109124
obj.Fields().Any(f => DbColumnTypeClrOverride(f) is not null);
110125

126+
/// <summary>ADR-0036 Wave 3 — true when any of <paramref name="obj"/>'s own fields is a
127+
/// <c>field.inet</c> (so the generated file needs <c>using System.Net;</c> for the
128+
/// <c>IPAddress</c> type). <c>field.uri</c> needs only <c>System</c> (always imported).</summary>
129+
public static bool RequiresSystemNet(MetaObject obj) =>
130+
obj.Fields().Any(f => !f.IsArray && f.SubType == FIELD_SUBTYPE_INET);
131+
111132
/// <summary>True when the C# type is a value type (gets <c>?</c> for nullable; needs no <c>= default!</c>).</summary>
112133
public static bool IsValueType(string csharpType) => ValueTypes.Contains(csharpType);
113134

‎server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,26 @@ public virtual IEnumerable<EmittedFile> Generate(GenContext ctx)
126126
: "timestamp with time zone";
127127
modelLines.Add($" modelBuilder.Entity<{owner}>().Property(x => x.{prop}).HasColumnType(\"{colType}\");");
128128
}
129+
// ADR-0036 Wave 3 — field.uri / field.inet native CLR bindings.
130+
// • field.uri → CLR System.Uri over a `text` column. EF has no built-in
131+
// Uri↔column mapping, so a HasConversion(Uri↔string) + HasColumnType("text")
132+
// stores the absolute URI string and the model agrees with the TS-owned DDL.
133+
// • field.inet → CLR System.Net.IPAddress over the Postgres-native `inet`
134+
// column. Npgsql maps IPAddress↔inet natively; the explicit HasColumnType
135+
// keeps the model and the TS-owned schema DDL in lockstep.
136+
foreach (var f in e.Fields().Where(f => !f.IsArray && f.SubType == FIELD_SUBTYPE_URI))
137+
{
138+
var prop = CSharpNaming.Pascal(f.Name);
139+
modelLines.Add(
140+
$" modelBuilder.Entity<{owner}>().Property(x => x.{prop}).HasColumnType(\"text\").HasConversion(v => v!.ToString(), v => new Uri(v));");
141+
}
142+
foreach (var f in e.Fields().Where(f => !f.IsArray && f.SubType == FIELD_SUBTYPE_INET))
143+
{
144+
var prop = CSharpNaming.Pascal(f.Name);
145+
modelLines.Add(
146+
$" modelBuilder.Entity<{owner}>().Property(x => x.{prop}).HasColumnType(\"inet\");");
147+
}
148+
129149
// R6 Plan 2b — @dbColumnType physical overrides. The logical field stays its
130150
// native CLR type (a @dbColumnType:uuid string is still C# string); EF must be
131151
// told the provider column type (and, for uuid, a string↔Guid value converter)

‎server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,9 @@ protected virtual EmittedFile EmitMappedClass(MetaObject entity, GenContext ctx)
122122
// A @dbColumnType:jsonb field surfaces as a System.Text.Json.JsonDocument (issue #98).
123123
if (CSharpNaming.RequiresSystemTextJson(entity))
124124
sb.AppendLine("using System.Text.Json;");
125+
// ADR-0036 Wave 3 — a field.inet surfaces as System.Net.IPAddress.
126+
if (CSharpNaming.RequiresSystemNet(entity))
127+
sb.AppendLine("using System.Net;");
125128
// A composite PK emits a class-level [PrimaryKey(...)] which lives in the
126129
// Microsoft.EntityFrameworkCore namespace (not a DataAnnotations attribute) —
127130
// import it so the emitted class compiles standalone, without relying on the
@@ -482,6 +485,9 @@ protected virtual EmittedFile EmitAbstractShapeClass(MetaObject entity, GenConte
482485
// A @dbColumnType:jsonb field surfaces as a System.Text.Json.JsonDocument (issue #98).
483486
if (CSharpNaming.RequiresSystemTextJson(entity))
484487
sb.AppendLine("using System.Text.Json;");
488+
// ADR-0036 Wave 3 — a field.inet surfaces as System.Net.IPAddress.
489+
if (CSharpNaming.RequiresSystemNet(entity))
490+
sb.AppendLine("using System.Net;");
485491
// FR-021 — usings for OTHER packages this entity references (object navs + TPH base).
486492
foreach (var ns in PackageBindingResolver.CrossPackageReferencedNamespaces(entity, ctx.Root, ctx.Config))
487493
sb.AppendLine($"using {ns};");
@@ -549,6 +555,9 @@ protected virtual EmittedFile EmitValueObjectPoco(MetaObject vo, GenContext ctx)
549555
// A @dbColumnType:jsonb field surfaces as a System.Text.Json.JsonDocument (issue #98).
550556
if (CSharpNaming.RequiresSystemTextJson(vo))
551557
sb.AppendLine("using System.Text.Json;");
558+
// ADR-0036 Wave 3 — a field.inet surfaces as System.Net.IPAddress.
559+
if (CSharpNaming.RequiresSystemNet(vo))
560+
sb.AppendLine("using System.Net;");
552561
// FR-021 — usings for OTHER packages this value-object references (object navs + super).
553562
foreach (var ns in PackageBindingResolver.CrossPackageReferencedNamespaces(vo, ctx.Root, ctx.Config))
554563
sb.AppendLine($"using {ns};");
@@ -809,6 +818,20 @@ protected virtual string ScalarProperty(
809818
// → [MaxLength] (preserving the existing @maxLength semantics).
810819
protected static void AppendStringValidatorAttributes(StringBuilder sb, MetaField field)
811820
{
821+
// ADR-0036 Wave 3 — @stringFormat narrows a plain string to a closed validated
822+
// format. The canonical matcher per format lives HERE (codegen), never author
823+
// validator.regex (cross-language regex engines diverge). The field stays a plain
824+
// string: email → [EmailAddress]; hostname → the canonical RFC-1123 [RegularExpression].
825+
switch (field.OwnAttr(FIELD_ATTR_STRING_FORMAT) as string)
826+
{
827+
case STRING_FORMAT_EMAIL:
828+
sb.AppendLine(" [EmailAddress]");
829+
break;
830+
case STRING_FORMAT_HOSTNAME:
831+
sb.AppendLine($" [RegularExpression(@\"{CSharpNaming.HostnameRegex}\")]");
832+
break;
833+
}
834+
812835
long? min = null;
813836
long? max = field.MaxLength;
814837
foreach (var v in field.Validators())

‎server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,8 +137,10 @@ protected virtual Dictionary<string, IReadOnlyList<string>> ComputeFilterableOps
137137
/// <summary>Operator set for <paramref name="subType"/>, or empty for unsupported subtypes.</summary>
138138
internal static IReadOnlyList<string> OpsForSubtype(string? subType) => subType switch
139139
{
140-
FIELD_SUBTYPE_STRING or FIELD_SUBTYPE_ENUM => OpsString,
141-
FIELD_SUBTYPE_UUID => OpsUuid,
140+
// ADR-0036 Wave 3 — field.uri is string-like (eq/ne/in/like/isNull); field.inet is
141+
// uuid-like (eq/ne/in/isNull — no like / ordering on an opaque address value).
142+
FIELD_SUBTYPE_STRING or FIELD_SUBTYPE_ENUM or FIELD_SUBTYPE_URI => OpsString,
143+
FIELD_SUBTYPE_UUID or FIELD_SUBTYPE_INET => OpsUuid,
142144
FIELD_SUBTYPE_INT or FIELD_SUBTYPE_LONG
143145
or FIELD_SUBTYPE_FLOAT or FIELD_SUBTYPE_DOUBLE or FIELD_SUBTYPE_DECIMAL
144146
or FIELD_SUBTYPE_CURRENCY

‎server/csharp/MetaObjects/Core/Field/FieldConstants.cs‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,24 @@ public static class FieldConstants
4242
/// </summary>
4343
public const string FIELD_SUBTYPE_UUID = "uuid";
4444

45+
/// <summary>
46+
/// ADR-0036 Wave 3 — <c>field.uri</c>: a URI/URL string. A concept with a native type +
47+
/// behavior, so a subtype (not a <c>@stringFormat</c>). String-backed on the wire (like
48+
/// <see cref="FIELD_SUBTYPE_STRING"/>); native binding is <c>System.Uri</c> in entity
49+
/// codegen and a Postgres <c>text</c> column (Postgres has no uri type). A bare scalar:
50+
/// no required attrs and no loader value-validation. Ships WITHOUT @kind in v1.
51+
/// </summary>
52+
public const string FIELD_SUBTYPE_URI = "uri";
53+
54+
/// <summary>
55+
/// ADR-0036 Wave 3 — <c>field.inet</c>: an IP-address string (IPv4 or IPv6). A concept
56+
/// with a native type + behavior, so a subtype (not a <c>@stringFormat</c>). String-backed
57+
/// on the wire (like <see cref="FIELD_SUBTYPE_STRING"/>); native binding is
58+
/// <c>System.Net.IPAddress</c> in entity codegen and a Postgres-native <c>inet</c> column.
59+
/// A bare scalar: no required attrs and no loader value-validation. Ships WITHOUT @kind in v1.
60+
/// </summary>
61+
public const string FIELD_SUBTYPE_INET = "inet";
62+
4563
public static readonly string[] FIELD_SUBTYPES =
4664
[
4765
BaseTypes.SUBTYPE_BASE,
@@ -60,6 +78,8 @@ public static class FieldConstants
6078
FIELD_SUBTYPE_CURRENCY,
6179
FIELD_SUBTYPE_ENUM,
6280
FIELD_SUBTYPE_UUID,
81+
FIELD_SUBTYPE_URI,
82+
FIELD_SUBTYPE_INET,
6383
];
6484

6585
// -----------------------------------------------------------------------
@@ -68,6 +88,25 @@ public static class FieldConstants
6888

6989
public const string FIELD_ATTR_REQUIRED = "required";
7090
public const string FIELD_ATTR_UNIQUE = "unique";
91+
92+
/// <summary>
93+
/// ADR-0036 Wave 3 — <c>@stringFormat</c> on <c>field.string</c>: a closed validation
94+
/// format (email | hostname) for a plain string field that has NO native type or
95+
/// behavior of its own. The field stays a plain string (native binding + DB column
96+
/// unchanged); codegen emits the matching validator. The canonical matcher per format
97+
/// lives in each port's codegen, NOT author validator.regex. Named @stringFormat (not
98+
/// @format) to avoid colliding with template.* @format.
99+
/// </summary>
100+
public const string FIELD_ATTR_STRING_FORMAT = "stringFormat";
101+
102+
/// <summary>@stringFormat "email" — an RFC-5322-ish email address.</summary>
103+
public const string STRING_FORMAT_EMAIL = "email";
104+
105+
/// <summary>@stringFormat "hostname" — a DNS hostname (RFC-1123 label rules).</summary>
106+
public const string STRING_FORMAT_HOSTNAME = "hostname";
107+
108+
/// <summary>The closed @stringFormat value set.</summary>
109+
public static readonly string[] STRING_FORMAT_VALUES = [STRING_FORMAT_EMAIL, STRING_FORMAT_HOSTNAME];
71110
/// <summary>
72111
/// FR-013: when true, the field is read-only — codegen emits no setter, the
73112
/// persistence layer skips the column on INSERT/UPDATE, and input schemas mark

‎server/csharp/MetaObjects/Core/Field/FieldSchema.cs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,23 @@ public static class FieldSchema
134134
"(string/int/long/double/float/decimal/boolean/date/time/timestamp/uuid). " +
135135
"Mutually exclusive with @objectRef; exactly one of the two must be set.");
136136

137+
/// <summary>
138+
/// ADR-0036 Wave 3 — the @stringFormat attr — only on field.string. Closed value set
139+
/// {email | hostname}. The field stays a plain string; codegen owns the canonical
140+
/// matcher per format. The allowed-values set is the Wave-1 gate mechanism (emitted to
141+
/// the registry manifest as allowedValues).
142+
/// </summary>
143+
public static readonly AttrSchema StringFormatAttr = new AttrSchema(
144+
Name: FieldConstants.FIELD_ATTR_STRING_FORMAT,
145+
ValueType: AttrConstants.ATTR_SUBTYPE_STRING,
146+
Required: false,
147+
AllowedValues: [.. FieldConstants.STRING_FORMAT_VALUES],
148+
Description:
149+
"ADR-0036/0037: a closed validation format for a plain string field that has NO " +
150+
"native type or behavior of its own — email | hostname. The field stays a plain " +
151+
"string (native binding + DB column unchanged); codegen emits the matching validator. " +
152+
"The canonical matcher per format lives in each port's codegen, NOT author validator.regex.");
153+
137154
/// <summary>The @currency attr — only on field.currency.</summary>
138155
public static readonly AttrSchema CurrencyFieldAttr = new AttrSchema(
139156
Name: FieldConstants.FIELD_ATTR_CURRENCY,

‎server/csharp/MetaObjects/CoreTypes.cs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,10 @@ private static TypeDefinition Def(
100100
// R6 Plan 2a — field.uuid is string-backed on the wire (lowercase-canonical
101101
// UUID string); the native System.Guid binding is a build-time codegen concern.
102102
[FIELD_SUBTYPE_UUID] = DataType.String,
103+
// ADR-0036 Wave 3 — field.uri / field.inet are string-backed on the wire; the
104+
// native System.Uri / System.Net.IPAddress bindings are build-time codegen concerns.
105+
[FIELD_SUBTYPE_URI] = DataType.String,
106+
[FIELD_SUBTYPE_INET] = DataType.String,
103107
[FIELD_SUBTYPE_DOUBLE] = DataType.Double,
104108
[FIELD_SUBTYPE_FLOAT] = DataType.Double,
105109
[FIELD_SUBTYPE_DECIMAL] = DataType.Double,
@@ -266,6 +270,10 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry)
266270
{
267271
List<AttrSchema> fieldAttrs = subType switch
268272
{
273+
// ADR-0036 Wave 3: @stringFormat (email|hostname) is scoped to field.string.
274+
// Strict attr scoping (from spec field.json's field.string allow-list) keeps it
275+
// here and prunes it everywhere else.
276+
FIELD_SUBTYPE_STRING => [.. FieldSchema.CommonFieldAttrs, FieldSchema.StringFormatAttr],
269277
FIELD_SUBTYPE_CURRENCY => [.. FieldSchema.CommonFieldAttrs, FieldSchema.CurrencyFieldAttr],
270278
// field.map — the open-keyed map. @objectRef is already in CommonFieldAttrs;
271279
// @valueType is map-specific. Strict attr scoping (from spec field.json's

‎server/csharp/MetaObjects/SpecMetamodel/field.json‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@
2424
"description": "Variable-length text. Binds to the native string type; DB column is VARCHAR/TEXT (use @maxLength for VARCHAR(n)).",
2525
"whenToUse": "Plain variable-length text. Set @maxLength to size the column. The default for textual data.",
2626
"children": [
27-
{ "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Maximum character length for string-typed fields (drives VARCHAR(n))." }
27+
{ "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Maximum character length for string-typed fields (drives VARCHAR(n))." },
28+
{ "type": "attr", "subType": "string", "name": "stringFormat", "min": 0, "max": 1, "allowedValues": ["email", "hostname"], "description": "ADR-0036/0037: a closed validation format for a plain string field that has NO native type or behavior of its own — email | hostname. The field stays a plain string (native binding + DB column unchanged); codegen emits the matching validator (Zod z.email() / a hostname check; PG CHECK where appropriate). The canonical matcher per format lives in each port's codegen, NOT author validator.regex (cross-language regex engines diverge). Named @stringFormat (not @format) to avoid colliding with template.* @format (output format). Concepts WITH a native type or behavior are subtypes instead (uuid → field.uuid, url/uri → field.uri, ip → field.inet)." }
2829
]
2930
},
3031
{
@@ -159,6 +160,22 @@
159160
"extendsBase": true,
160161
"description": "Logical UUID identity scalar. A bare scalar (no required attrs, no loader value-validation) — binds to TS string (no native UUID type); DB column is Postgres-native uuid.",
161162
"whenToUse": "A key or external identifier is a UUID. Use it for a typed UUID column instead of a plain string."
163+
},
164+
{
165+
"type": "field",
166+
"subType": "uri",
167+
"dataType": "string",
168+
"extendsBase": true,
169+
"description": "A URI/URL string (ADR-0036/0037 — a concept with a native type + behavior, so a subtype not a @stringFormat). Binds to TS string (TS has no native URI type, same as field.uuid); other ports bind to their native URI type (Java java.net.URI, C# System.Uri, Python urllib.parse, Kotlin java.net.URI) and parse scheme/authority/path. DB column is text (Postgres has no uri type). Codegen emits a URL/URI validator (TS Zod z.string().url()). v1 ships WITHOUT @kind — the native type subsumes url/urn; @kind is reserved for a later url|urn value-constraint.",
170+
"whenToUse": "A field holds a URL or URI. Use it for a typed URI column + URL validation instead of a plain string."
171+
},
172+
{
173+
"type": "field",
174+
"subType": "inet",
175+
"dataType": "string",
176+
"extendsBase": true,
177+
"description": "An IP-address string (IPv4 or IPv6) (ADR-0036/0037 — a concept with a native type + behavior, so a subtype not a @stringFormat). Binds to TS string (TS has no native IP type, same as field.uuid); other ports bind to their native IP type (Java java.net.InetAddress, C# System.Net.IPAddress, Python ipaddress, Kotlin java.net.InetAddress). DB column is the Postgres-native inet type. Codegen emits an IP validator accepting both v4 and v6 (TS Zod z.string().ip()). v1 ships WITHOUT @kind — the native type subsumes ipv4/ipv6; @kind is reserved for a later ipv4|ipv6 value-constraint.",
178+
"whenToUse": "A field holds an IPv4 or IPv6 address. Use it for a native Postgres inet column + IP validation instead of a plain string."
162179
}
163180
]
164181
}

0 commit comments

Comments
 (0)