diff --git a/docs/core-concepts/typesafe-schemas.mdx b/docs/core-concepts/typesafe-schemas.mdx index 9299a46b..3e8da1a9 100644 --- a/docs/core-concepts/typesafe-schemas.mdx +++ b/docs/core-concepts/typesafe-schemas.mdx @@ -138,6 +138,32 @@ Generation also rejects nullable roots, `Ack.any()` and `Ack.map()` roots, `Ack.anyOf()`, bare `Ack.instance()`, anonymous inline object fields, unresolved dynamic schema factories, and cross-library union branches. +Schema-first JSON keys keep their spelling on the wire. Fields, discriminator +getters, and inline JSON Schema model name segments use the same word boundaries. +The generator splits at punctuation, spaces, and other characters outside +ASCII letters and digits. It also starts a word at an uppercase letter after +a lowercase letter or digit, as in `ipv4Address` and `sha256Hash`, and before +a capitalized word following an acronym, as in `HTTPServer` and `URLIsValid`. +A plural acronym such as `URLs` stays together. + +Each word is lowercased, then capitalized where required by the target name. +Fields and discriminator getters leave the first word lowercase. Type name +segments capitalize it too. For example, `UserID`, `userID`, and `user_id` +all become `userId` as a field and `UserId` as a type name segment. `URLs` +becomes `urls` or `Urls`, and `address_2` becomes `address2` or `Address2`. +Generation rejects keys containing non-ASCII letters, such as `café` and +`já_ok`, as well as empty names, field names that start with a digit, Dart +reserved words, and keys that produce the same Dart member. Use a class-first +model with `@AckKey` to keep a key and choose its Dart field name. + +Field and discriminator names also cannot shadow identifiers used by the +generated class. This includes `bool`, `double`, `dynamic`, `int`, `num`, +`override`, `identical`, `deepEquals`, `deepHashCode`, +`deepUnmodifiableCopy`, and `deepUnmodifiableJsonMap`. Generation also checks +the schema declaration name, the Ack import prefix, and names and import +prefixes used in field types. Use a class-first model with `@AckKey` to keep +the wire key and choose a different Dart field name. + ### Schema-first unions Each branch must be a named `@Schemable()` object schema in the same library: @@ -546,8 +572,27 @@ static schema; use `Object?` for an open JSON value. Automatic `List` and `Set` inference also requires non-nullable element types because `Ack.list` has no nullable-item contract. +The generated parse and encode helpers, including `toJson()` and +`safeToJson()`, validate with a class's static `schema` when it declares one. +Nested class-first fields also use that schema. The declaration must be a +non-nullable `AckSchema` with the model as its runtime type and a boundary +type assignable to `Map`. +Use `ModelSchema.schema` as the raw generated schema when declaring +`Model.schema` with refinements. + ### Class-first unions +The sealed base and its branches may expose a static `schema` only as a +read-only alias of their generated facade's `schema`, such as +`static final schema = PetSchema.schema;`. Apply custom validation to the +union schema where you use it, or use a non-union model for a class-owned +schema with refinements. + +Every branch inherits the sealed base’s `caseStyle` by default, including +branches with `@Schemable(discriminatorValue: ...)`. Set a branch’s own +`caseStyle` to override the base. Use `AckCaseStyle.none` to preserve the +branch’s Dart field names. + Annotate a sealed base with a discriminator key. Concrete branches in the same library are included automatically, and inherited constructor fields may use super parameters: @@ -656,6 +701,19 @@ declare the same model name. Deferred imports are unsupported. Automatic recursive class-first schemas are not yet defined. For self or mutually recursive contracts, use schema-first named `Ack.lazy` schemas. +### Using Ack models inside json_serializable classes + +When a `@JsonSerializable()` class holds an Ack model, specify the converters +on that field. For an Ack class with an `AccountSchema` facade, use + +```dart +@JsonKey(fromJson: AccountSchema.fromJson, toJson: AccountSchema.encode) +final Account account; +``` + +Use `JsonKey` from `package:json_annotation/json_annotation.dart` on the +container field. + ## Which direction should you choose? Put `@Schemable()` on a top-level schema when you want to design the boundary diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index d4bfae20..9a47447d 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -6,6 +6,25 @@ This guide summarizes **what exists in Ack today**, **what changed in 1.7 and 2. --- +## Beta.3 to 2.0: generated models + +| Affected code | Changed in | Migration | +| --- | --- | --- | +| A custom static `schema` on a class-first sealed union base or branch | `2.0.0` | Expose the generated facade's `schema` directly. Apply custom validation at the union level or use a non-union model. | +| Schema-first keys that shadow a generated reference, such as `override` or `identical` | `2.0.0` | Use a class-first model with `@AckKey` to preserve the wire key and give the Dart field a different name. | +| Schema-first fields, discriminators, and inline JSON Schema model names | `2.0.0` | Regenerate and update Dart callers. Digits before uppercase letters and acronym boundaries affect names such as `ipv4Address` and `urlIsValid`. Inline model segments normalize acronyms, for example `UserID` → `UserId`. Use a class-first model with `@AckKey` for keys containing non-ASCII letters, keys mapping to a reserved word such as `default`, and collisions. | +| Implicit field style on an annotated branch of a styled sealed class | `2.0.0` | Regenerate to inherit the base’s style. Use `caseStyle: AckCaseStyle.none` on the branch to retain Dart names on the wire. | +| Code that reads `Schemable.caseStyle` as non-null | `2.0.0` | Handle a null style as unspecified. Use `annotation.caseStyle ?? AckCaseStyle.none` when you need the standalone default. | +| `caseStyle: AckCaseStyle.none` on a top-level schema or library annotation | `2.0.0` | Remove the class-only option from the annotation. | +| A super parameter whose inherited default references a declaration you cannot access | `2.0.0` | Import the declaration used in the default, or give the super parameter an explicit default. | +| JSON Schema properties that cannot become distinct Dart fields, such as `@id` and `id` | `2.0.0` | Automatic generation uses a validated value model. Read the original keys from `model.value`, or define a class-first model with `@AckKey` for typed fields. | +| A JSON Schema property whose wire spelling matches its model name, such as `Model` | `2.0.0` | Regenerate and use the typed field, such as `model.model`, when the derived Dart name is valid. | +| Class-owned schema refinements | `2.0.0` | Generated helpers and nested fields now enforce them. Compose `ModelSchema.schema` explicitly when you need the raw generated rules. | +| A nullable class-owned `schema` or one with a boundary wider than a JSON map | `2.0.0` | Declare a non-nullable `AckSchema, Model>`. A narrower boundary type is also valid. Use `ModelSchema.schema` as the base for class-owned refinements. | +| Schema-first fields using snake_case or another wire spelling | `2.0.0` | Regenerate and use the lowerCamelCase Dart names in field accesses, constructors and `copyWith`. JSON keys keep their original spelling. | +| The direct `ackModelBuilder` factory | `2.0.0` | Use the shared `ack_generator:ack_generator` builder with source_gen’s combining builder. | +| Generated `Set` fields that previously accepted duplicate JSON items | `2.0.0` | Remove duplicates or use `List` when duplicates must be accepted. Exported schemas now include `uniqueItems: true` for these fields. | + ## Migrating to `Is…`/`Has…` rule annotations Ack 2.0 uses top-level rule annotations. `Is…` names what a value is; `Has…` names a bound or property it @@ -122,6 +141,10 @@ Ack is organized into five coordinated packages that share one version number an | `@AckField(description: ...)` | `2.0.0` | `/// @description ...` doc tag | | `@JsonConverter()` on `@Schemable` classes/fields | `1.7.0` (rejected) | Declare `static final schema = ...` on the type or register one in `@Schemable(schemas: [...])` | +Schema-first union discriminator getters use the same lowerCamelCase naming as +other fields. A class-first union emits one discriminator wire key, even when +a branch field uses a different case style. + ### Validation Annotations The top-level 1.x validation and presence classes were removed in `2.0.0`. diff --git a/example/lib/additional_properties_example.g.dart b/example/lib/additional_properties_example.g.dart index c15758f0..b3f97fca 100644 --- a/example/lib/additional_properties_example.g.dart +++ b/example/lib/additional_properties_example.g.dart @@ -7,7 +7,6 @@ part of 'additional_properties_example.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file /// Immutable model generated from `userConfigSchema`. @@ -76,9 +75,9 @@ final class UserConfig { identical(this, other) || (other is UserConfig && runtimeType == other.runtimeType && - deepEquals(username, other.username) && - deepEquals(email, other.email) && - deepEquals(additionalProperties, other.additionalProperties)); + deepEquals(this.username, other.username) && + deepEquals(this.email, other.email) && + deepEquals(this.additionalProperties, other.additionalProperties)); @override int get hashCode => Object.hashAll([ @@ -93,23 +92,23 @@ final class UserConfig { 'UserConfig(username: ${username}, email: ${email}, additionalProperties: ${additionalProperties})'; static UserConfig _fromAckRuntime(Map value) { - const declared = {'username', 'email'}; + const _ackDeclaredKeys = {'username', 'email'}; return UserConfig( username: value['username'] as String, email: value['email'] as String, additionalProperties: Map.fromEntries( - value.entries.where((entry) => !declared.contains(entry.key)), + value.entries.where((entry) => !_ackDeclaredKeys.contains(entry.key)), ), ); } Map _toAckRuntime() { - const declared = {'username', 'email'}; + const _ackDeclaredKeys = {'username', 'email'}; return { for (final entry in additionalProperties.entries) - if (!declared.contains(entry.key)) entry.key: entry.value, - 'username': username, - 'email': email, + if (!_ackDeclaredKeys.contains(entry.key)) entry.key: entry.value, + 'username': this.username, + 'email': this.email, }; } } @@ -210,9 +209,9 @@ final class ApiRequest { identical(this, other) || (other is ApiRequest && runtimeType == other.runtimeType && - deepEquals(method, other.method) && - deepEquals(url, other.url) && - deepEquals(additionalProperties, other.additionalProperties)); + deepEquals(this.method, other.method) && + deepEquals(this.url, other.url) && + deepEquals(this.additionalProperties, other.additionalProperties)); @override int get hashCode => Object.hashAll([ @@ -227,23 +226,23 @@ final class ApiRequest { 'ApiRequest(method: ${method}, url: ${url}, additionalProperties: ${additionalProperties})'; static ApiRequest _fromAckRuntime(Map value) { - const declared = {'method', 'url'}; + const _ackDeclaredKeys = {'method', 'url'}; return ApiRequest( method: value['method'] as String, url: value['url'] as String, additionalProperties: Map.fromEntries( - value.entries.where((entry) => !declared.contains(entry.key)), + value.entries.where((entry) => !_ackDeclaredKeys.contains(entry.key)), ), ); } Map _toAckRuntime() { - const declared = {'method', 'url'}; + const _ackDeclaredKeys = {'method', 'url'}; return { for (final entry in additionalProperties.entries) - if (!declared.contains(entry.key)) entry.key: entry.value, - 'method': method, - 'url': url, + if (!_ackDeclaredKeys.contains(entry.key)) entry.key: entry.value, + 'method': this.method, + 'url': this.url, }; } } @@ -345,9 +344,9 @@ final class FeatureFlags { identical(this, other) || (other is FeatureFlags && runtimeType == other.runtimeType && - deepEquals(appVersion, other.appVersion) && - deepEquals(environment, other.environment) && - deepEquals(additionalProperties, other.additionalProperties)); + deepEquals(this.appVersion, other.appVersion) && + deepEquals(this.environment, other.environment) && + deepEquals(this.additionalProperties, other.additionalProperties)); @override int get hashCode => Object.hashAll([ @@ -362,23 +361,23 @@ final class FeatureFlags { 'FeatureFlags(appVersion: ${appVersion}, environment: ${environment}, additionalProperties: ${additionalProperties})'; static FeatureFlags _fromAckRuntime(Map value) { - const declared = {'appVersion', 'environment'}; + const _ackDeclaredKeys = {'appVersion', 'environment'}; return FeatureFlags( appVersion: value['appVersion'] as String, environment: value['environment'] as String, additionalProperties: Map.fromEntries( - value.entries.where((entry) => !declared.contains(entry.key)), + value.entries.where((entry) => !_ackDeclaredKeys.contains(entry.key)), ), ); } Map _toAckRuntime() { - const declared = {'appVersion', 'environment'}; + const _ackDeclaredKeys = {'appVersion', 'environment'}; return { for (final entry in additionalProperties.entries) - if (!declared.contains(entry.key)) entry.key: entry.value, - 'appVersion': appVersion, - 'environment': environment, + if (!_ackDeclaredKeys.contains(entry.key)) entry.key: entry.value, + 'appVersion': this.appVersion, + 'environment': this.environment, }; } } @@ -473,7 +472,7 @@ final class DynamicData { identical(this, other) || (other is DynamicData && runtimeType == other.runtimeType && - deepEquals(additionalProperties, other.additionalProperties)); + deepEquals(this.additionalProperties, other.additionalProperties)); @override int get hashCode => @@ -484,19 +483,19 @@ final class DynamicData { 'DynamicData(additionalProperties: ${additionalProperties})'; static DynamicData _fromAckRuntime(Map value) { - const declared = {}; + const _ackDeclaredKeys = {}; return DynamicData( additionalProperties: Map.fromEntries( - value.entries.where((entry) => !declared.contains(entry.key)), + value.entries.where((entry) => !_ackDeclaredKeys.contains(entry.key)), ), ); } Map _toAckRuntime() { - const declared = {}; + const _ackDeclaredKeys = {}; return { for (final entry in additionalProperties.entries) - if (!declared.contains(entry.key)) entry.key: entry.value, + if (!_ackDeclaredKeys.contains(entry.key)) entry.key: entry.value, }; } } diff --git a/example/lib/class_first_models.g.dart b/example/lib/class_first_models.g.dart index d235d521..977d3783 100644 --- a/example/lib/class_first_models.g.dart +++ b/example/lib/class_first_models.g.dart @@ -7,7 +7,6 @@ part of 'class_first_models.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file final _catObject = Ack.object({ @@ -67,8 +66,8 @@ abstract final class CatSchema { AckSchemaModelExtension(_catSchema).toSchemaModel(); } -Cat _$CatFromRuntime(Map value) => - Cat(id: value['id'] as String, lives: value['lives'] as int); +Cat _$CatFromRuntime(Map $ackValue) => + Cat(id: $ackValue['id'] as String, lives: $ackValue['lives'] as int); Map _$CatToRuntime(Cat model) => { 'id': model.id, @@ -102,9 +101,7 @@ mixin _$CatAck { @override bool operator ==(Object other) { if (identical(this, other)) return true; - if (other is! Cat || runtimeType != other.runtimeType) { - return false; - } + if (other is! Cat || runtimeType != other.runtimeType) return false; final self = this as Cat; return deepEquals(self.id, other.id) && deepEquals(self.lives, other.lives); } @@ -195,8 +192,8 @@ abstract final class DogSchema { AckSchemaModelExtension(_dogSchema).toSchemaModel(); } -Dog _$DogFromRuntime(Map value) => - Dog(id: value['id'] as String, breed: value['breed'] as String); +Dog _$DogFromRuntime(Map $ackValue) => + Dog(id: $ackValue['id'] as String, breed: $ackValue['breed'] as String); Map _$DogToRuntime(Dog model) => { 'id': model.id, @@ -230,9 +227,7 @@ mixin _$DogAck { @override bool operator ==(Object other) { if (identical(this, other)) return true; - if (other is! Dog || runtimeType != other.runtimeType) { - return false; - } + if (other is! Dog || runtimeType != other.runtimeType) return false; final self = this as Dog; return deepEquals(self.id, other.id) && deepEquals(self.breed, other.breed); } @@ -277,7 +272,10 @@ final _petSchema = _petObject decode: (value) => switch (value['type']) { 'cat' => _$CatFromRuntime(value), 'Dog' => _$DogFromRuntime(value), - final unknown => throw StateError('Unknown type: $unknown'), + final unknown => throw StateError( + 'Unknown type: ' + '$unknown', + ), }, encode: (model) => switch (model) { Cat() => _$CatToRuntime(model), @@ -371,11 +369,11 @@ abstract final class AccountSchema { /// /// Throws an `AckException` when validation fails. static Account parse(Object? value, {String? debugName}) => - _accountSchema.parse(value, debugName: debugName)!; + Account.schema.parse(value, debugName: debugName)!; /// Validates [value] and returns the model or the validation failure. static SchemaResult safeParse(Object? value, {String? debugName}) => - _accountSchema.safeParse(value, debugName: debugName); + Account.schema.safeParse(value, debugName: debugName); /// Validates decoded [json] and creates the model. /// @@ -386,14 +384,14 @@ abstract final class AccountSchema { /// /// Throws an `AckException` when validation fails. static Map encode(Account value, {String? debugName}) => - _accountSchema.encode(value, debugName: debugName)!; + Account.schema.encode(value, debugName: debugName)!; /// Validates [value] and encodes it as a JSON map, returning the validation /// failure instead of throwing. static SchemaResult> safeEncode( Account value, { String? debugName, - }) => _accountSchema.safeEncode(value, debugName: debugName); + }) => Account.schema.safeEncode(value, debugName: debugName); /// The JSON Schema that describes [Account]. static Map toJsonSchema() => _accountSchema.toJsonSchema(); @@ -403,10 +401,10 @@ abstract final class AccountSchema { AckSchemaModelExtension(_accountSchema).toSchemaModel(); } -Account _$AccountFromRuntime(Map value) => Account( - displayName: value['display_name'] as String, - website: value['website'] as Uri?, - role: value['role'] as String? ?? 'member', +Account _$AccountFromRuntime(Map $ackValue) => Account( + displayName: $ackValue['display_name'] as String, + website: $ackValue['website'] as Uri?, + role: $ackValue['role'] as String? ?? 'member', ); Map _$AccountToRuntime(Account model) => { @@ -457,9 +455,7 @@ mixin _$AccountAck { @override bool operator ==(Object other) { if (identical(this, other)) return true; - if (other is! Account || runtimeType != other.runtimeType) { - return false; - } + if (other is! Account || runtimeType != other.runtimeType) return false; final self = this as Account; return deepEquals(self.displayName, other.displayName) && deepEquals(self.website, other.website) && diff --git a/example/lib/pet.g.dart b/example/lib/pet.g.dart index 7105059f..236ef078 100644 --- a/example/lib/pet.g.dart +++ b/example/lib/pet.g.dart @@ -7,7 +7,6 @@ part of 'pet.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file /// Discriminated model base generated from `petSchema`. @@ -60,7 +59,10 @@ sealed class Pet { return switch (value['type']) { 'cat' => Cat._fromAckRuntime(value), 'dog' => Dog._fromAckRuntime(value), - final unknown => throw StateError('Unknown type: $unknown'), + final unknown => throw StateError( + 'Unknown type: ' + '$unknown', + ), }; } @@ -117,7 +119,7 @@ final class Cat extends Pet { identical(this, other) || (other is Cat && runtimeType == other.runtimeType && - deepEquals(lives, other.lives)); + deepEquals(this.lives, other.lives)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(lives)]); @@ -131,7 +133,7 @@ final class Cat extends Pet { @override Map _toAckRuntime() => { 'type': 'cat', - 'lives': lives, + 'lives': this.lives, }; } @@ -203,7 +205,7 @@ final class Dog extends Pet { identical(this, other) || (other is Dog && runtimeType == other.runtimeType && - deepEquals(breed, other.breed)); + deepEquals(this.breed, other.breed)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(breed)]); @@ -217,7 +219,7 @@ final class Dog extends Pet { @override Map _toAckRuntime() => { 'type': 'dog', - 'breed': breed, + 'breed': this.breed, }; } diff --git a/example/lib/schema_types_discriminated.g.dart b/example/lib/schema_types_discriminated.g.dart index 87e6aa94..385f3773 100644 --- a/example/lib/schema_types_discriminated.g.dart +++ b/example/lib/schema_types_discriminated.g.dart @@ -7,7 +7,6 @@ part of 'schema_types_discriminated.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file /// Discriminated model base generated from `petSchema`. @@ -60,7 +59,10 @@ sealed class Pet { return switch (value['kind']) { 'cat' => Cat._fromAckRuntime(value), 'dog' => Dog._fromAckRuntime(value), - final unknown => throw StateError('Unknown kind: $unknown'), + final unknown => throw StateError( + 'Unknown kind: ' + '$unknown', + ), }; } @@ -117,7 +119,7 @@ final class Cat extends Pet { identical(this, other) || (other is Cat && runtimeType == other.runtimeType && - deepEquals(lives, other.lives)); + deepEquals(this.lives, other.lives)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(lives)]); @@ -131,7 +133,7 @@ final class Cat extends Pet { @override Map _toAckRuntime() => { 'kind': 'cat', - 'lives': lives, + 'lives': this.lives, }; } @@ -209,8 +211,8 @@ final class Dog extends Pet { identical(this, other) || (other is Dog && runtimeType == other.runtimeType && - deepEquals(bark, other.bark) && - deepEquals(additionalProperties, other.additionalProperties)); + deepEquals(this.bark, other.bark) && + deepEquals(this.additionalProperties, other.additionalProperties)); @override int get hashCode => Object.hashAll([ @@ -224,23 +226,23 @@ final class Dog extends Pet { 'Dog(bark: ${bark}, additionalProperties: ${additionalProperties})'; static Dog _fromAckRuntime(Map value) { - const declared = {'kind', 'bark'}; + const _ackDeclaredKeys = {'kind', 'bark'}; return Dog( bark: value['bark'] as bool, additionalProperties: Map.fromEntries( - value.entries.where((entry) => !declared.contains(entry.key)), + value.entries.where((entry) => !_ackDeclaredKeys.contains(entry.key)), ), ); } @override Map _toAckRuntime() { - const declared = {'kind', 'bark'}; + const _ackDeclaredKeys = {'kind', 'bark'}; return { for (final entry in additionalProperties.entries) - if (!declared.contains(entry.key)) entry.key: entry.value, + if (!_ackDeclaredKeys.contains(entry.key)) entry.key: entry.value, 'kind': 'dog', - 'bark': bark, + 'bark': this.bark, }; } } diff --git a/example/lib/schema_types_edge_cases.g.dart b/example/lib/schema_types_edge_cases.g.dart index abff44fd..e82dc73b 100644 --- a/example/lib/schema_types_edge_cases.g.dart +++ b/example/lib/schema_types_edge_cases.g.dart @@ -7,7 +7,6 @@ part of 'schema_types_edge_cases.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file /// Immutable model generated from `productSchema`. @@ -80,10 +79,10 @@ final class Product { identical(this, other) || (other is Product && runtimeType == other.runtimeType && - deepEquals(name, other.name) && - deepEquals(tags, other.tags) && - deepEquals(scores, other.scores) && - deepEquals(flags, other.flags)); + deepEquals(this.name, other.name) && + deepEquals(this.tags, other.tags) && + deepEquals(this.scores, other.scores) && + deepEquals(this.flags, other.flags)); @override int get hashCode => Object.hashAll([ @@ -106,10 +105,10 @@ final class Product { ); Map _toAckRuntime() => { - 'name': name, - 'tags': tags.map((item) => item).toList(growable: false), - 'scores': scores.map((item) => item).toList(growable: false), - 'flags': flags.map((item) => item).toList(growable: false), + 'name': this.name, + 'tags': this.tags.map((item) => item).toList(growable: false), + 'scores': this.scores.map((item) => item).toList(growable: false), + 'flags': this.flags.map((item) => item).toList(growable: false), }; } @@ -207,8 +206,8 @@ final class Grid { identical(this, other) || (other is Grid && runtimeType == other.runtimeType && - deepEquals(name, other.name) && - deepEquals(matrix, other.matrix)); + deepEquals(this.name, other.name) && + deepEquals(this.matrix, other.matrix)); @override int get hashCode => @@ -225,8 +224,8 @@ final class Grid { ); Map _toAckRuntime() => { - 'name': name, - 'matrix': matrix + 'name': this.name, + 'matrix': this.matrix .map((item) => item.map((item) => item).toList(growable: false)) .toList(growable: false), }; @@ -319,10 +318,10 @@ final class Address { identical(this, other) || (other is Address && runtimeType == other.runtimeType && - deepEquals(street, other.street) && - deepEquals(city, other.city) && - deepEquals(zipCode, other.zipCode) && - deepEquals(country, other.country)); + deepEquals(this.street, other.street) && + deepEquals(this.city, other.city) && + deepEquals(this.zipCode, other.zipCode) && + deepEquals(this.country, other.country)); @override int get hashCode => Object.hashAll([ @@ -345,10 +344,10 @@ final class Address { ); Map _toAckRuntime() => { - 'street': street, - 'city': city, - 'zipCode': zipCode, - 'country': country, + 'street': this.street, + 'city': this.city, + 'zipCode': this.zipCode, + 'country': this.country, }; } @@ -452,10 +451,10 @@ final class Person { identical(this, other) || (other is Person && runtimeType == other.runtimeType && - deepEquals(name, other.name) && - deepEquals(email, other.email) && - deepEquals(address, other.address) && - deepEquals(age, other.age)); + deepEquals(this.name, other.name) && + deepEquals(this.email, other.email) && + deepEquals(this.address, other.address) && + deepEquals(this.age, other.age)); @override int get hashCode => Object.hashAll([ @@ -478,10 +477,10 @@ final class Person { ); Map _toAckRuntime() => { - 'name': name, - 'email': email, - 'address': Address.$ack.toRuntime(address), - 'age': age, + 'name': this.name, + 'email': this.email, + 'address': Address.$ack.toRuntime(this.address), + 'age': this.age, }; } @@ -577,10 +576,10 @@ final class Employee { identical(this, other) || (other is Employee && runtimeType == other.runtimeType && - deepEquals(name, other.name) && - deepEquals(employeeId, other.employeeId) && - deepEquals(homeAddress, other.homeAddress) && - deepEquals(workAddress, other.workAddress)); + deepEquals(this.name, other.name) && + deepEquals(this.employeeId, other.employeeId) && + deepEquals(this.homeAddress, other.homeAddress) && + deepEquals(this.workAddress, other.workAddress)); @override int get hashCode => Object.hashAll([ @@ -607,10 +606,10 @@ final class Employee { ); Map _toAckRuntime() => { - 'name': name, - 'employeeId': employeeId, - 'homeAddress': Address.$ack.toRuntime(homeAddress), - 'workAddress': Address.$ack.toRuntime(workAddress), + 'name': this.name, + 'employeeId': this.employeeId, + 'homeAddress': Address.$ack.toRuntime(this.homeAddress), + 'workAddress': Address.$ack.toRuntime(this.workAddress), }; } @@ -718,11 +717,11 @@ final class Modifier { identical(this, other) || (other is Modifier && runtimeType == other.runtimeType && - deepEquals(requiredField, other.requiredField) && - deepEquals(optionalField, other.optionalField) && - deepEquals(nullableField, other.nullableField) && - deepEquals(optionalNullable, other.optionalNullable) && - deepEquals(nullableOptional, other.nullableOptional)); + deepEquals(this.requiredField, other.requiredField) && + deepEquals(this.optionalField, other.optionalField) && + deepEquals(this.nullableField, other.nullableField) && + deepEquals(this.optionalNullable, other.optionalNullable) && + deepEquals(this.nullableOptional, other.nullableOptional)); @override int get hashCode => Object.hashAll([ @@ -747,11 +746,11 @@ final class Modifier { ); Map _toAckRuntime() => { - 'requiredField': requiredField, - 'optionalField': ?optionalField, - 'nullableField': nullableField, - 'optionalNullable': ?optionalNullable, - 'nullableOptional': ?nullableOptional, + 'requiredField': this.requiredField, + 'optionalField': ?this.optionalField, + 'nullableField': this.nullableField, + 'optionalNullable': ?this.optionalNullable, + 'nullableOptional': ?this.nullableOptional, }; } @@ -888,10 +887,10 @@ final class TaggedItem { identical(this, other) || (other is TaggedItem && runtimeType == other.runtimeType && - deepEquals(name, other.name) && - deepEquals(requiredTags, other.requiredTags) && - deepEquals(optionalTags, other.optionalTags) && - deepEquals(nullableTags, other.nullableTags)); + deepEquals(this.name, other.name) && + deepEquals(this.requiredTags, other.requiredTags) && + deepEquals(this.optionalTags, other.optionalTags) && + deepEquals(this.nullableTags, other.nullableTags)); @override int get hashCode => Object.hashAll([ @@ -920,10 +919,16 @@ final class TaggedItem { ); Map _toAckRuntime() => { - 'name': name, - 'requiredTags': requiredTags.map((item) => item).toList(growable: false), - 'optionalTags': ?optionalTags?.map((item) => item).toList(growable: false), - 'nullableTags': nullableTags?.map((item) => item).toList(growable: false), + 'name': this.name, + 'requiredTags': this.requiredTags + .map((item) => item) + .toList(growable: false), + 'optionalTags': ?this.optionalTags + ?.map((item) => item) + .toList(growable: false), + 'nullableTags': this.nullableTags + ?.map((item) => item) + .toList(growable: false), }; } @@ -1031,8 +1036,8 @@ final class ContactList { identical(this, other) || (other is ContactList && runtimeType == other.runtimeType && - deepEquals(name, other.name) && - deepEquals(addresses, other.addresses)); + deepEquals(this.name, other.name) && + deepEquals(this.addresses, other.addresses)); @override int get hashCode => Object.hashAll([ @@ -1052,8 +1057,8 @@ final class ContactList { ); Map _toAckRuntime() => { - 'name': name, - 'addresses': addresses + 'name': this.name, + 'addresses': this.addresses .map((item) => Address.$ack.toRuntime(item)) .toList(growable: false), }; @@ -1218,7 +1223,7 @@ final class Minimal { identical(this, other) || (other is Minimal && runtimeType == other.runtimeType && - deepEquals(id, other.id)); + deepEquals(this.id, other.id)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(id)]); @@ -1229,7 +1234,7 @@ final class Minimal { static Minimal _fromAckRuntime(Map value) => Minimal(id: value['id'] as String); - Map _toAckRuntime() => {'id': id}; + Map _toAckRuntime() => {'id': this.id}; } /// Creates copies of [Minimal] with selected fields replaced. @@ -1307,7 +1312,7 @@ final class NamedItem { identical(this, other) || (other is NamedItem && runtimeType == other.runtimeType && - deepEquals(name, other.name)); + deepEquals(this.name, other.name)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(name)]); @@ -1318,7 +1323,7 @@ final class NamedItem { static NamedItem _fromAckRuntime(Map value) => NamedItem(name: value['name'] as String); - Map _toAckRuntime() => {'name': name}; + Map _toAckRuntime() => {'name': this.name}; } /// Creates copies of [NamedItem] with selected fields replaced. @@ -1395,7 +1400,7 @@ final class Item { identical(this, other) || (other is Item && runtimeType == other.runtimeType && - deepEquals(id, other.id)); + deepEquals(this.id, other.id)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(id)]); @@ -1406,7 +1411,7 @@ final class Item { static Item _fromAckRuntime(Map value) => Item(id: value['id'] as String); - Map _toAckRuntime() => {'id': id}; + Map _toAckRuntime() => {'id': this.id}; } /// Creates copies of [Item] with selected fields replaced. @@ -1485,7 +1490,7 @@ final class MyCustomSchema123 { identical(this, other) || (other is MyCustomSchema123 && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -1496,7 +1501,9 @@ final class MyCustomSchema123 { static MyCustomSchema123 _fromAckRuntime(Map value) => MyCustomSchema123(value: value['value'] as String); - Map _toAckRuntime() => {'value': value}; + Map _toAckRuntime() => { + 'value': this.value, + }; } /// Creates copies of [MyCustomSchema123] with selected fields replaced. diff --git a/example/lib/schema_types_primitives.g.dart b/example/lib/schema_types_primitives.g.dart index 22214895..320dd17d 100644 --- a/example/lib/schema_types_primitives.g.dart +++ b/example/lib/schema_types_primitives.g.dart @@ -7,7 +7,6 @@ part of 'schema_types_primitives.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file /// Immutable value model generated from `passwordSchema`. @@ -68,7 +67,7 @@ final class Password { identical(this, other) || (other is Password && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -156,7 +155,7 @@ final class Age { identical(this, other) || (other is Age && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -244,7 +243,7 @@ final class Price { identical(this, other) || (other is Price && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -332,7 +331,7 @@ final class Active { identical(this, other) || (other is Active && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -421,7 +420,7 @@ final class Tags { identical(this, other) || (other is Tags && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -511,7 +510,7 @@ final class Scores { identical(this, other) || (other is Scores && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -602,7 +601,7 @@ final class StatusLiteral { identical(this, other) || (other is StatusLiteral && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -691,7 +690,7 @@ final class Role { identical(this, other) || (other is Role && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -781,7 +780,7 @@ final class UserRoleModel { identical(this, other) || (other is UserRoleModel && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -872,7 +871,7 @@ final class StatusEnum { identical(this, other) || (other is StatusEnum && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -962,7 +961,7 @@ final class OptionalStatus { identical(this, other) || (other is OptionalStatus && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -1054,7 +1053,7 @@ final class DefaultedEnum { identical(this, other) || (other is DefaultedEnum && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -1146,7 +1145,7 @@ final class ChainedEnumString { identical(this, other) || (other is ChainedEnumString && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -1238,7 +1237,7 @@ final class RefinedAge { identical(this, other) || (other is RefinedAge && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); diff --git a/example/lib/schema_types_simple.dart b/example/lib/schema_types_simple.dart index 7132d1dc..5b1b79be 100644 --- a/example/lib/schema_types_simple.dart +++ b/example/lib/schema_types_simple.dart @@ -8,4 +8,5 @@ final userSchema = Ack.object({ 'name': Ack.string(), 'age': Ack.integer(), 'active': Ack.boolean(), + 'account_id': Ack.string().optional(), }); diff --git a/example/lib/schema_types_simple.g.dart b/example/lib/schema_types_simple.g.dart index 6bc7074c..469c873e 100644 --- a/example/lib/schema_types_simple.g.dart +++ b/example/lib/schema_types_simple.g.dart @@ -7,7 +7,6 @@ part of 'schema_types_simple.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file /// Immutable model generated from `userSchema`. @@ -16,7 +15,12 @@ final class User { /// /// Use `parse` or `fromJson` for untrusted input. `toJson` validates /// the model while encoding it. - User({required this.name, required this.age, required this.active}); + User({ + required this.name, + required this.age, + required this.active, + this.accountId, + }); /// Validates [input] and creates the model. /// @@ -38,6 +42,8 @@ final class User { final bool active; + final String? accountId; + /// The Ack adapter that parses and encodes this model. static final $ack = AckModelAdapter( schema: () => userSchema, @@ -70,9 +76,10 @@ final class User { identical(this, other) || (other is User && runtimeType == other.runtimeType && - deepEquals(name, other.name) && - deepEquals(age, other.age) && - deepEquals(active, other.active)); + deepEquals(this.name, other.name) && + deepEquals(this.age, other.age) && + deepEquals(this.active, other.active) && + deepEquals(this.accountId, other.accountId)); @override int get hashCode => Object.hashAll([ @@ -80,42 +87,60 @@ final class User { deepHashCode(name), deepHashCode(age), deepHashCode(active), + deepHashCode(accountId), ]); @override - String toString() => 'User(name: ${name}, age: ${age}, active: ${active})'; + String toString() => + 'User(name: ${name}, age: ${age}, active: ${active}, accountId: ${accountId})'; static User _fromAckRuntime(Map value) => User( name: value['name'] as String, age: value['age'] as int, active: value['active'] as bool, + accountId: value['account_id'] as String?, ); Map _toAckRuntime() => { - 'name': name, - 'age': age, - 'active': active, + 'name': this.name, + 'age': this.age, + 'active': this.active, + 'account_id': ?this.accountId, }; } +final class _UserCopyWithUnset { + const _UserCopyWithUnset(); +} + /// Creates copies of [User] with selected fields replaced. abstract interface class $UserCopyWith<$Result> { /// Returns a copy with the given fields replaced. /// /// An omitted argument keeps the current value. An explicit `null` clears a /// nullable field. - $Result call({String? name, int? age, bool? active}); + $Result call({String? name, int? age, bool? active, String? accountId}); } final class _$UserCopyWith implements $UserCopyWith { const _$UserCopyWith(this._source); + static const _UserCopyWithUnset _ackCopyWithUnset = _UserCopyWithUnset(); + final User _source; @override - User call({String? name, int? age, bool? active}) => User( + User call({ + String? name, + int? age, + bool? active, + Object? accountId = _ackCopyWithUnset, + }) => User( name: name ?? _source.name, age: age ?? _source.age, active: active ?? _source.active, + accountId: identical(accountId, _ackCopyWithUnset) + ? _source.accountId + : accountId as String?, ); } diff --git a/example/lib/schema_types_transforms.g.dart b/example/lib/schema_types_transforms.g.dart index 8ebc55e1..cf183fff 100644 --- a/example/lib/schema_types_transforms.g.dart +++ b/example/lib/schema_types_transforms.g.dart @@ -7,7 +7,6 @@ part of 'schema_types_transforms.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file /// Immutable value model generated from `colorSchema`. @@ -68,7 +67,7 @@ final class ColorModel { identical(this, other) || (other is ColorModel && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -192,17 +191,17 @@ final class Profile { identical(this, other) || (other is Profile && runtimeType == other.runtimeType && - deepEquals(homepage, other.homepage) && - deepEquals(birthday, other.birthday) && - deepEquals(lastLogin, other.lastLogin) && - deepEquals(timeout, other.timeout) && - deepEquals(links, other.links) && - deepEquals(favoriteColor, other.favoriteColor) && - deepEquals(slug, other.slug) && - deepEquals(accent, other.accent) && - deepEquals(colors, other.colors) && - deepEquals(customColors, other.customColors) && - deepEquals(tagList, other.tagList)); + deepEquals(this.homepage, other.homepage) && + deepEquals(this.birthday, other.birthday) && + deepEquals(this.lastLogin, other.lastLogin) && + deepEquals(this.timeout, other.timeout) && + deepEquals(this.links, other.links) && + deepEquals(this.favoriteColor, other.favoriteColor) && + deepEquals(this.slug, other.slug) && + deepEquals(this.accent, other.accent) && + deepEquals(this.colors, other.colors) && + deepEquals(this.customColors, other.customColors) && + deepEquals(this.tagList, other.tagList)); @override int get hashCode => Object.hashAll([ @@ -241,19 +240,21 @@ final class Profile { ); Map _toAckRuntime() => { - 'homepage': homepage, - 'birthday': birthday, - 'lastLogin': lastLogin, - 'timeout': timeout, - 'links': links.map((item) => item).toList(growable: false), - 'favoriteColor': favoriteColor, - 'slug': slug, - 'accent': ColorModel.$ack.toRuntime(accent), - 'colors': colors + 'homepage': this.homepage, + 'birthday': this.birthday, + 'lastLogin': this.lastLogin, + 'timeout': this.timeout, + 'links': this.links.map((item) => item).toList(growable: false), + 'favoriteColor': this.favoriteColor, + 'slug': this.slug, + 'accent': ColorModel.$ack.toRuntime(this.accent), + 'colors': this.colors .map((item) => ColorModel.$ack.toRuntime(item)) .toList(growable: false), - 'customColors': customColors.map((item) => item).toList(growable: false), - 'tagList': tagList, + 'customColors': this.customColors + .map((item) => item) + .toList(growable: false), + 'tagList': this.tagList, }; } diff --git a/example/lib/user_with_color.g.dart b/example/lib/user_with_color.g.dart index 5a4c572a..61bf0105 100644 --- a/example/lib/user_with_color.g.dart +++ b/example/lib/user_with_color.g.dart @@ -7,7 +7,6 @@ part of 'user_with_color.dart'; // ************************************************************************** // ignore_for_file: type=lint -// ignore_for_file: invalid_use_of_internal_member // coverage:ignore-file /// Immutable value model generated from `colorSchema`. @@ -68,7 +67,7 @@ final class ColorModel { identical(this, other) || (other is ColorModel && runtimeType == other.runtimeType && - deepEquals(value, other.value)); + deepEquals(this.value, other.value)); @override int get hashCode => Object.hashAll([runtimeType, deepHashCode(value)]); @@ -158,8 +157,8 @@ final class Profile { identical(this, other) || (other is Profile && runtimeType == other.runtimeType && - deepEquals(bio, other.bio) && - deepEquals(website, other.website)); + deepEquals(this.bio, other.bio) && + deepEquals(this.website, other.website)); @override int get hashCode => @@ -172,8 +171,8 @@ final class Profile { Profile(bio: value['bio'] as String, website: value['website'] as Uri?); Map _toAckRuntime() => { - 'bio': bio, - 'website': ?website, + 'bio': this.bio, + 'website': ?this.website, }; } @@ -288,14 +287,14 @@ final class UserWithColor { identical(this, other) || (other is UserWithColor && runtimeType == other.runtimeType && - deepEquals(firstName, other.firstName) && - deepEquals(lastName, other.lastName) && - deepEquals(age, other.age) && - deepEquals(profile, other.profile) && - deepEquals(color, other.color) && - deepEquals(favoriteColor, other.favoriteColor) && - deepEquals(pet, other.pet) && - deepEquals(pets, other.pets)); + deepEquals(this.firstName, other.firstName) && + deepEquals(this.lastName, other.lastName) && + deepEquals(this.age, other.age) && + deepEquals(this.profile, other.profile) && + deepEquals(this.color, other.color) && + deepEquals(this.favoriteColor, other.favoriteColor) && + deepEquals(this.pet, other.pet) && + deepEquals(this.pets, other.pets)); @override int get hashCode => Object.hashAll([ @@ -334,17 +333,17 @@ final class UserWithColor { ); Map _toAckRuntime() => { - 'firstName': firstName, - 'lastName': lastName, - 'age': age, - 'profile': Profile.$ack.toRuntime(profile), - 'color': ColorModel.$ack.toRuntime(color), - 'favoriteColor': ?switch (favoriteColor) { + 'firstName': this.firstName, + 'lastName': this.lastName, + 'age': this.age, + 'profile': Profile.$ack.toRuntime(this.profile), + 'color': ColorModel.$ack.toRuntime(this.color), + 'favoriteColor': ?switch (this.favoriteColor) { null => null, final fieldValue => ColorModel.$ack.toRuntime(fieldValue), }, - 'pet': Pet.$ack.toRuntime(pet), - 'pets': pets + 'pet': Pet.$ack.toRuntime(this.pet), + 'pets': this.pets .map((item) => Pet.$ack.toRuntime(item)) .toList(growable: false), }; diff --git a/example/test/schema_variable_test.dart b/example/test/schema_variable_test.dart index 84b36192..a2c01b70 100644 --- a/example/test/schema_variable_test.dart +++ b/example/test/schema_variable_test.dart @@ -14,6 +14,18 @@ void main() { expect(user.active, true); }); + test('User exposes a lowerCamelCase field for a snake_case wire key', () { + final wire = { + 'name': 'Alice', + 'age': 30, + 'active': true, + 'account_id': 'acct-1', + }; + final user = User.parse(wire); + expect(user.accountId, 'acct-1'); + expect(user.toJson(), wire); + }); + test('User validates data through schema', () { final invalidData = { 'name': 'Alice', diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index 7883f48a..1619cf24 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -2,6 +2,12 @@ ### Breaking +* **Breaking:** `Schemable.caseStyle` is now an `AckCaseStyle?`. An omitted + style is null. Use `AckCaseStyle.none` for an explicit override. + +* **Breaking:** Annotated union branches inherit the base case style when + their own style is omitted. Use `AckCaseStyle.none` to keep Dart names. + * **Breaking:** `SchemaContext` is a `base` class and `createChild` is internal. Read the context from `SchemaError.context` when handling validation errors. @@ -91,6 +97,9 @@ ### Changed +* Support `AckSchema.forGeneratedField` as a generated-code entry point + returning `AckSchema`. + * Keep wrapper context path handling internal. Empty JSON member keys still appear as empty tokens in validation paths. diff --git a/packages/ack/lib/src/annotations/schemable.dart b/packages/ack/lib/src/annotations/schemable.dart index 5a4d2676..c0a16b67 100644 --- a/packages/ack/lib/src/annotations/schemable.dart +++ b/packages/ack/lib/src/annotations/schemable.dart @@ -38,7 +38,7 @@ final class Schemable { this.name, this.schemaName, this.description, - this.caseStyle = AckCaseStyle.none, + this.caseStyle, this.discriminatorKey, this.discriminatorValue, this.unknownProperties = AckUnknownPropertyPolicy.reject, @@ -59,7 +59,11 @@ final class Schemable { final String? description; /// JSON field-name style for a class declaration. - final AckCaseStyle caseStyle; + /// + /// A null style inherits the base style for a sealed union branch and uses + /// [AckCaseStyle.none] elsewhere. Set [AckCaseStyle.none] explicitly to keep + /// a branch's Dart field names as-is. + final AckCaseStyle? caseStyle; /// Discriminator key for a sealed class declaration. final String? discriminatorKey; diff --git a/packages/ack/lib/src/schemas/schema.dart b/packages/ack/lib/src/schemas/schema.dart index f58ff04e..f12eb825 100644 --- a/packages/ack/lib/src/schemas/schema.dart +++ b/packages/ack/lib/src/schemas/schema.dart @@ -124,11 +124,10 @@ sealed class AckSchema { /// /// The field declaration supplies optionality, nullability and defaults. /// Non-null values retain the custom schema's validation and encoder. - @internal - static CodecSchema forGeneratedField< - B extends Object, - R extends Object - >(AckSchema schema) => CodecSchema._( + /// This entry point is supported for generated model code. + static AckSchema forGeneratedField( + AckSchema schema, + ) => CodecSchema._( inputSchema: schema, outputSchema: schema, decoder: (value) => value as R, diff --git a/packages/ack/test/annotations/ack_model_test.dart b/packages/ack/test/annotations/ack_model_test.dart index c80121ee..4624805c 100644 --- a/packages/ack/test/annotations/ack_model_test.dart +++ b/packages/ack/test/annotations/ack_model_test.dart @@ -9,7 +9,12 @@ void main() { const defaults = Schemable(); expect(defaults.name, isNull); expect(defaults.schemaName, isNull); - expect(defaults.caseStyle, AckCaseStyle.none); + expect(defaults.caseStyle, isNull); + expect(const Schemable(caseStyle: null).caseStyle, isNull); + expect( + const Schemable(caseStyle: AckCaseStyle.none).caseStyle, + AckCaseStyle.none, + ); expect(defaults.discriminatorKey, isNull); expect(defaults.discriminatorValue, isNull); expect(defaults.unknownProperties, AckUnknownPropertyPolicy.reject); diff --git a/packages/ack/test/schemas/generated_field_schema_test.dart b/packages/ack/test/schemas/generated_field_schema_test.dart index 6d7b9c2a..622f9794 100644 --- a/packages/ack/test/schemas/generated_field_schema_test.dart +++ b/packages/ack/test/schemas/generated_field_schema_test.dart @@ -1,10 +1,18 @@ -// Generated parts use this helper across the package boundary. -// ignore_for_file: invalid_use_of_internal_member - import 'package:ack/ack.dart'; import 'package:test/test.dart'; +typedef _GeneratedFieldFactory = AckSchema Function( + AckSchema, +); + void main() { + test('the generated field factory exposes the abstract schema type', () { + expect( + AckSchema.forGeneratedField.runtimeType, + _GeneratedFieldFactory, + ); + }); + test('field policies replace custom presence while keeping the codec', () { final custom = Ack.string() .minLength(2) diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index a1ae6300..a7218e5f 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -2,6 +2,53 @@ ### Breaking +* **Breaking:** Explicit `caseStyle: AckCaseStyle.none` is rejected on + top-level schema and library annotations. Omit the class-only option there. + +* **Breaking:** A class-owned model `schema` must be a non-nullable + `AckSchema` with the model as its runtime type and a boundary assignable + to `Map`. The generator reports incompatible declarations + before emitting code. + +* **Breaking:** A JSON Schema property whose wire spelling matches its model + name can now generate a typed field when its Dart field name is distinct. + Regenerate and update callers that used the previous value model. + +* **Breaking:** Inherited constructor defaults from another library must use + declarations visible to the generated part. Import the referenced names or + give the super parameter an explicit default. + +* **Breaking:** Reject schema-first field and discriminator names that shadow + generated references such as `override` and `identical`. + +* **Breaking:** Class-first sealed union bases and branches may declare a + static `schema` only as a direct alias of their generated facade's schema. + Apply custom validation at the union level or use a non-union model. + +* **Breaking:** Use the configured shared part builder instead of the + generator's old direct `ackModelBuilder` export. + +* **Breaking:** Generated `Set` fields reject duplicate JSON values. + Their exported JSON Schemas include `uniqueItems: true`. +* **Breaking:** A stored discriminator uses its configured JSON key once. + Schema-first discriminator getters use lowerCamelCase. + +* **Breaking:** Generate lowerCamelCase Dart fields from schema-first JSON + keys. One naming rule handles field names, discriminator getters, and inline + JSON Schema type names. For example, `UserID` maps to `userId`, `URLs` maps + to `urls`, and `ipv4Address` retains its case boundary. Inline type segments + normalize acronyms too, such as `UserID` to `UserId`. Generation rejects keys + containing non-ASCII letters and invalid or colliding Dart names. Wire keys + keep their original spelling. + +* **Breaking:** Generated helpers and nested fields enforce class-owned + schema refinements (#263). + +* **Breaking:** Annotated union branches inherit the base case style when + their own style is omitted. Use `AckCaseStyle.none` to keep Dart names. + The generator reads this distinction from the public nullable + `Schemable.caseStyle` option. + * **Breaking:** Replace `@IsUrl()` with `@IsUri()` and regenerate model parts. * **Breaking:** Remove the deprecated beta validation annotation aliases and their generic `kind` and `value` getters. Use the Is/Has rule annotations. @@ -13,6 +60,33 @@ * Expand support to Analyzer 14.x and build 5.x. The generator can resolve with Freezed 4.0.3 and build_runner 2.17.1. +### Fixed + +* Keep generated class-first runtime locals from capturing identifiers used + by constructor defaults. + +* Suggest `@Schemable()` in the build error when a union branch cannot resolve + to a model. +* Document JSON converters for Ack model fields in json_serializable classes. + +* Report invalid rule arguments on the annotated field, including non-integer + arguments on integer fields, negative lengths, and invalid regular expressions. + +* Derive UpperCamelCase model names for inline objects under snake_case keys. + +* Qualify references to class statics in generated constructor defaults. +* Preserve short string interpolations when qualifying constructor defaults. +* Fall back to validated value models when JSON Schema property names collide + in Dart, shadow generated references, or contain non-ASCII letters. + Generated comments identify the properties that led to the fallback. +* Preserve constructor defaults inherited through super parameters, including + defaults that refer to statics on the declaring class. + +* Escape literal dollar signs and quotes in generated discriminator messages. + +* Generated models compare declared fields and encode passthrough JSON + correctly when field names overlap with generator parameters or locals. + ## 2.0.0-beta.3 ### Breaking diff --git a/packages/ack_generator/lib/builder.dart b/packages/ack_generator/lib/builder.dart index 8a9e071e..384328bb 100644 --- a/packages/ack_generator/lib/builder.dart +++ b/packages/ack_generator/lib/builder.dart @@ -1 +1 @@ -export 'src/builder.dart'; +export 'src/builder.dart' show ackGenerator, ackJsonSchemaBuilder; diff --git a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart index 8203f499..6cb80ade 100644 --- a/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/class_model_graph_builder.dart @@ -1,5 +1,6 @@ import 'package:ack/annotations.dart' as annotations; import 'package:analyzer/dart/ast/ast.dart'; +import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/constant/value.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; @@ -106,17 +107,24 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { if (options.discriminatorValue != null) { throw InvalidGenerationSource( '${element.name} sets discriminatorValue but is not a concrete ' - 'branch of an annotated sealed ${annotationName(element)} base.', + 'branch of an annotated sealed @Schemable base.', element: element, ); } if (element.isAbstract || !element.isConstructable) { throw InvalidGenerationSource( - '${annotationName(element)} requires a constructable class; ' + '@Schemable requires a constructable class; ' '${element.name} is abstract.', element: element, ); } + if (element.getGetter('schema') case final getter? when getter.isStatic) { + _validateStaticSchema( + element, + getter, + '${_facadeName(element, options)}.schema', + ); + } await _buildObject(element, options: options); } _rejectRecursiveClassFirstGraphs(); @@ -175,7 +183,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { final name = element.name ?? ''; if (name.startsWith('_')) { throw InvalidGenerationSource( - '${annotationName(element)} requires a public class; received ' + '@Schemable requires a public class; received ' '"$name".', element: element, todo: 'Annotate a public class.', @@ -191,23 +199,22 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { ); } _rejectRedirectingFactory(element); - _validateStaticSchema(element); _validateStaticFromJson(element); _requireFinalConcreteClass(element); if (_jsonSerializableChecker.hasAnnotationOfExact(element)) { throw InvalidGenerationSource( - '$name cannot use ${annotationName(element)} and @JsonSerializable ' + '$name cannot use @Schemable and @JsonSerializable ' 'together because both generate the same _\$$name JSON helpers.', element: element, todo: - 'Remove @JsonSerializable; ${annotationName(element)} owns JSON ' + 'Remove @JsonSerializable; @Schemable owns JSON ' 'generation.', ); } final options = _options(element)!; if (element.isSealed && options.discriminatorKey == null) { throw InvalidGenerationSource( - 'Sealed ${annotationName(element)} $name requires discriminatorKey.', + 'Sealed @Schemable $name requires discriminatorKey.', element: element, ); } @@ -219,7 +226,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { } if (element.isSealed && options.discriminatorValue != null) { throw InvalidGenerationSource( - 'Sealed ${annotationName(element)} $name cannot set ' + 'Sealed @Schemable $name cannot set ' 'discriminatorValue.', element: element, ); @@ -230,26 +237,82 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { /// /// The facade is generated in this build, so the type is checked only once /// it resolves. - void _validateStaticSchema(ClassElement element) { - final getter = element.getGetter('schema'); - if (getter == null || - !getter.isStatic || - containsInvalidType(getter.returnType)) { - return; + void _validateStaticSchema( + ClassElement element, + GetterElement getter, + String facadeSchema, + ) { + final type = getter.returnType; + if (containsInvalidType(type)) return; + if (type is DynamicType) { + final resolved = inputResolved!; + final declaration = propertyDeclaration(getter); + final node = declarationNode(resolved, declaration); + final inferred = switch (node) { + VariableDeclaration(parent: VariableDeclarationList(type: null)) || + MethodDeclaration(returnType: null) => true, + _ => false, + }; + if (inferred && + declarationExpression( + resolved, + declaration, + )?.unParenthesized.toSource() == + facadeSchema) { + return; + } } - final runtime = ackSchemaRuntimeType(getter.returnType); - if (runtime != null && - sameTypeIgnoringNullability(runtime, element.thisType)) { + + final arguments = ackSchemaTypeArguments(type); + final provider = element.library.typeProvider; + final jsonMap = provider.mapType( + provider.stringType, + provider.objectQuestionType, + ); + if (type.nullabilitySuffix == NullabilitySuffix.none && + arguments != null && + element.library.typeSystem.isSubtypeOf(arguments.boundary, jsonMap) && + arguments.runtime.nullabilitySuffix == NullabilitySuffix.none && + sameTypeIgnoringNullability(arguments.runtime, element.thisType)) { return; } throw InvalidGenerationSource( - '${element.name}.schema must be an AckSchema, ' - '${element.name}>; it produces ' - '${runtime?.getDisplayString() ?? 'an untyped value'}.', + '${element.name}.schema must be a non-nullable ' + 'AckSchema, ${element.name}>. ' + 'Its declared type is ${type.getDisplayString()}.', element: getter, ); } + void _validateUnionStaticSchema(ClassElement element, _ModelOptions options) { + final getter = element.getGetter('schema'); + final method = element.getMethod('schema'); + final member = switch ((getter, method)) { + (final getter?, _) when getter.isStatic => getter, + (_, final method?) when method.isStatic => method, + _ => null, + }; + if (member == null) return; + + final facadeSchema = '${_facadeName(element, options)}.schema'; + final expression = declarationExpression( + inputResolved!, + propertyDeclaration(member), + ); + if (member is GetterElement && + element.getSetter('schema')?.isStatic != true && + expression?.unParenthesized.toSource() == facadeSchema) { + _validateStaticSchema(element, member, facadeSchema); + return; + } + + throw InvalidGenerationSource( + '${element.name}.schema must directly expose $facadeSchema ' + 'in a sealed union. Validate at the union level or use a non-union model.', + element: propertyDeclaration(member), + ); + } + /// A model may expose `static final fromJson = XSchema.fromJson;` or a static /// `fromJson` method. Either must accept a JSON map and return the model. /// @@ -327,7 +390,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { final target = node.redirectedConstructor; if (target == null) return; throw InvalidGenerationSource( - '${annotationName(element)} ${element.name} redirects its unnamed ' + '@Schemable ${element.name} redirects its unnamed ' 'constructor to ${target.toSource()}. Redirecting factory models are ' 'not supported; declare a final class whose unnamed generative ' 'constructor initializes its fields.', @@ -339,12 +402,14 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { _requireMixin(base); _rejectGeneratedMemberCollisions(base, includeValueMembers: false); final baseOptions = _options(base)!; + _validateUnionStaticSchema(base, baseOptions); final discriminatorKey = baseOptions.discriminatorKey!; - _rejectInvalidMemberName( - discriminatorKey, - base, - memberKind: 'discriminator member', - ); + if (discriminatorKey.isEmpty) { + throw InvalidGenerationSource( + '${base.name} discriminator key must not be empty.', + element: base, + ); + } if (_reservedMembers.contains(discriminatorKey)) { throw InvalidGenerationSource( '${base.name}.$discriminatorKey conflicts with a generated member.', @@ -373,7 +438,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { } if (candidates.isEmpty) { throw InvalidGenerationSource( - 'Sealed ${annotationName(base)} ${base.name} has no concrete ' + 'Sealed @Schemable ${base.name} has no concrete ' 'same-library branches.', element: base, ); @@ -388,7 +453,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { final valueOwners = {}; for (final branch in candidates) { final branchOptions = - _options(branch) ?? + _options(branch, inheritedCaseStyle: baseOptions.caseStyle) ?? ( schemaName: null, description: null, @@ -404,6 +469,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { element: branch, ); } + _validateUnionStaticSchema(branch, branchOptions); final value = branchOptions.discriminatorValue ?? branch.name!; final prior = valueOwners[value]; if (prior != null) { @@ -473,7 +539,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { final constructor = element.unnamedConstructor; if (constructor == null || !constructor.isGenerative) { throw InvalidGenerationSource( - '${annotationName(element)} ${element.name} requires an unnamed ' + '@Schemable ${element.name} requires an unnamed ' 'generative constructor.', element: element, ); @@ -487,7 +553,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { if (field.isFinal) continue; throw InvalidGenerationSource( '${element.name}.${field.name} must be final because ' - '${annotationName(element)} generates immutable value semantics.', + '@Schemable generates immutable value semantics.', element: field, todo: 'Declare the stored field as final.', ); @@ -527,6 +593,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { } final parameters = {}; + final defaultExpressions = {}; final constructorParameters = []; for (final parameter in constructor.formalParameters) { _rejectJsonKey(element, parameter); @@ -540,6 +607,8 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { ); } parameters[fieldName] = parameter; + final defaultExpression = await _defaultExpression(parameter); + defaultExpressions[fieldName] = defaultExpression; constructorParameters.add( AckConstructorParameter( name: parameter.name!, @@ -550,7 +619,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { typeRef: futureTypes[fieldName]?.runtimeRef ?? _typeRef(parameter.type, field!), - defaultExpression: parameter.defaultValueCode, + defaultExpression: defaultExpression, ), ); } @@ -586,14 +655,24 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { if (parameters.containsKey(name)) { throw InvalidGenerationSource( '${element.name}.$name is private and cannot participate in ' - '${annotationName(element)} generation.', + '@Schemable generation.', element: field, ); } continue; } final parameter = parameters[name]; - final isDiscriminator = discriminatorKey == name; + final explicitKey = _jsonKey(field, parameter); + final inferredKey = _rename(name, options.caseStyle); + final isDiscriminator = + discriminatorKey != null && + (explicitKey == discriminatorKey || + explicitKey == null && + (name == discriminatorKey || + inferredKey == discriminatorKey)); + if (isDiscriminator && name != discriminatorKey) { + _validateBranchDiscriminator(element, name, discriminatorValue!); + } if (parameter == null && !isDiscriminator) { throw InvalidGenerationSource( '${element.name}.$name must be initialized by a matching unnamed ' @@ -625,8 +704,9 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { ); } _recordClassFirstDependencies(element, field.type, field); - final jsonKey = - _jsonKey(field, parameter) ?? _rename(name, options.caseStyle); + final jsonKey = isDiscriminator + ? discriminatorKey + : explicitKey ?? inferredKey; final prior = ownerByJsonKey[jsonKey]; if (prior != null) { throw InvalidGenerationSource( @@ -671,7 +751,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { schema, presence: presence, acceptsNull: acceptsNull, - defaultCode: parameter?.defaultValueCode, + defaultCode: defaultExpressions[name], defaultIsNull: parameter?.computeConstantValue()?.isNull ?? false, ); if (rejectNull) { @@ -686,7 +766,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { acceptsNull: acceptsNull, runtimeRef: futureType?.runtimeRef ?? _typeRef(field.type, field), schemaExpression: schema, - defaultExpression: parameter?.defaultValueCode, + defaultExpression: defaultExpressions[name], ), ); } @@ -820,7 +900,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { _ => runtimeRef, }; final rendered = _schemaRuntimeRef(setType).render(corePrefix: ackPrefix); - return '$listSchema.codec<$rendered>(' + return '$listSchema.unique().codec<$rendered>(' 'decode: (list) => list.toSet(), ' 'encode: (set) => set.toList(growable: false),' ')'; @@ -955,6 +1035,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { final resolved = inputResolved; if (resolved == null) return null; for (final element in [field, ?parameter]) { + if (element.library != library.element) continue; final node = declarationNode(resolved, element); if (node is FormalParameter) { final comment = node.documentationComment; @@ -1090,7 +1171,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { if (element.isAbstract || element.isSealed || element.isFinal) return; throw InvalidGenerationSource( '${element.name} must be declared as a final class because ' - '${annotationName(element)} generates immutable value semantics.', + '@Schemable generates immutable value semantics.', element: element, todo: 'Add the final class modifier.', ); @@ -1289,7 +1370,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { if (!RegExp(r'^[A-Z][A-Za-z0-9_$]*$').hasMatch(facadeName) || isDartKeyword(facadeName)) { throw InvalidGenerationSource( - 'Invalid ${annotationName(element)} schema facade name "$facadeName" on ' + 'Invalid @Schemable schema facade name "$facadeName" on ' '${element.name}; schemaName must be a public UpperCamel identifier.', element: element, ); @@ -1310,6 +1391,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { AckClassModelMetadata( facadeName: facadeName, backingName: backingName, + hasStaticSchema: element.getGetter('schema')?.isStatic ?? false, copyWithSupertypes: { for (final supertype in element.allSupertypes) if (supertype.element case final ClassElement parent) @@ -1323,17 +1405,96 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { ); } - _ModelOptions? _options(ClassElement element) { + Future _defaultExpression(FormalParameterElement parameter) async { + final original = parameter.defaultValueCode; + if (original == null) return null; + + for ( + FormalParameterElement? source = parameter; + source != null; + source = source is SuperFormalParameterElement + ? source.superConstructorParameter + : null + ) { + final owner = source.enclosingElement?.enclosingElement; + if (owner is! ClassElement) return original; + final external = owner.library != library.element; + final resolved = await resolvedLibraryFor(owner.library); + final declaration = resolved.getFragmentDeclaration(source.firstFragment); + final content = declaration?.resolvedUnit?.content; + final node = declaration?.node; + if (content == null || node is! FormalParameter) { + if (external) throw _inaccessibleDefault(parameter, owner.name!); + return original; + } + final value = node.defaultClause?.value; + if (value == null) continue; + + final visitor = _ConstructorDefaultReferences(owner, external: external); + value.accept(visitor); + if (visitor.references.isEmpty) return original; + var qualified = content.substring(value.offset, value.end); + for (final reference in visitor.references.reversed) { + final name = external + ? _visibleDefaultName(parameter, reference.target) + : reference.target.name!; + final qualifiedName = reference.member == null + ? name + : '$name.${reference.member}'; + qualified = qualified.replaceRange( + reference.offset - value.offset, + reference.end - value.offset, + reference.shortInterpolation && qualifiedName.contains('.') + ? '{$qualifiedName}' + : qualifiedName, + ); + } + return qualified; + } + return original; + } + + String _visibleDefaultName(FormalParameterElement parameter, Element target) { + final name = target.name!; + final String? prefix; + try { + prefix = visiblePrefixFor(target, path: name, context: parameter); + } on InvalidGenerationSource { + throw _inaccessibleDefault(parameter, name); + } + if (prefix == null && + library.element.firstFragment.scope.lookup(name).getter?.baseElement != + target.baseElement) { + throw _inaccessibleDefault(parameter, name); + } + return qualifySymbol(prefix, name); + } + + InvalidGenerationSource _inaccessibleDefault( + FormalParameterElement parameter, + String reference, + ) => InvalidGenerationSource( + '${parameter.enclosingElement?.enclosingElement?.name}.${parameter.name} ' + 'inherits a default that references "$reference", which cannot be ' + 'resolved in this library. Declare an explicit default for this parameter.', + element: parameter, + ); + + _ModelOptions? _options( + ClassElement element, { + annotations.AckCaseStyle inheritedCaseStyle = annotations.AckCaseStyle.none, + }) { final annotation = ModelGraphBuilderBase.schemableChecker .firstAnnotationOfExact(element); if (annotation == null) return null; final reader = ConstantReader(annotation); - final caseStyle = reader.read('caseStyle').objectValue; - final caseIndex = caseStyle.getField('index')!.toIntValue()!; + final caseIndex = reader.peek('caseStyle')?.read('index').intValue; return ( schemaName: _nullableString(reader, 'schemaName'), description: _nullableString(reader, 'description'), - caseStyle: annotations.AckCaseStyle.values[caseIndex], + caseStyle: caseIndex == null + ? inheritedCaseStyle + : annotations.AckCaseStyle.values[caseIndex], discriminatorKey: _nullableString(reader, 'discriminatorKey'), discriminatorValue: _nullableString(reader, 'discriminatorValue'), unknownProperties: @@ -1351,7 +1512,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { final explicit = options.description; if (explicit != null && explicit.trim().isEmpty) { throw InvalidGenerationSource( - '${element.name} ${annotationName(element)}.description must not be ' + '${element.name} @Schemable.description must not be ' 'blank.', element: element, ); @@ -1406,7 +1567,7 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { if (!_jsonKeyChecker.hasAnnotationOfExact(element)) return; throw InvalidGenerationSource( '${owner.name}.${element.name} uses @JsonKey, which is not supported on ' - '${annotationName(owner)} classes in Ack 2.0. Use @AckKey(...) ' + '@Schemable classes in Ack 2.0. Use @AckKey(...) ' 'instead.', element: element, ); @@ -1490,3 +1651,80 @@ final class ClassModelGraphBuilder extends ModelGraphBuilderBase { declarationName: element.name!, ); } + +typedef _DefaultReference = ({ + Element target, + String? member, + int offset, + int end, + bool shortInterpolation, +}); + +/// Finds references whose spelling can depend on the declaring scope. +final class _ConstructorDefaultReferences extends RecursiveAstVisitor { + _ConstructorDefaultReferences(this.owner, {required this.external}); + + final ClassElement owner; + final bool external; + final references = <_DefaultReference>[]; + + void _add(AstNode node, Element target, {String? member, int? end}) { + final parent = node.parent; + references.add(( + target: target, + member: member, + offset: node.offset, + end: end ?? node.end, + shortInterpolation: + parent is InterpolationExpression && parent.rightBracket == null, + )); + } + + @override + void visitNamedType(NamedType node) { + final target = node.element; + if (external && target?.enclosingElement is LibraryElement) { + _add(node, target!, end: node.name.end); + } + super.visitNamedType(node); + } + + @override + void visitPrefixedIdentifier(PrefixedIdentifier node) { + final target = node.identifier.element; + if (external && node.prefix.element is PrefixElement && target != null) { + _add(node, target); + return; + } + super.visitPrefixedIdentifier(node); + } + + @override + void visitSimpleIdentifier(SimpleIdentifier node) { + final element = node.element; + if (element == null) return; + final parent = node.parent; + final isMember = + parent is PrefixedIdentifier && identical(parent.identifier, node) || + parent is PropertyAccess && identical(parent.propertyName, node) || + parent is MethodInvocation && + parent.target != null && + identical(parent.methodName, node) || + parent is ConstructorName && identical(parent.name, node); + if (isMember) { + if (external && node.name.startsWith('_')) _add(node, element); + return; + } + if (element is ExecutableElement && + element.isStatic && + element.enclosingElement == owner) { + if (external && node.name.startsWith('_')) { + _add(node, element); + } else { + _add(node, owner, member: node.name); + } + } else if (external && element.enclosingElement is LibraryElement) { + _add(node, element); + } + } +} diff --git a/packages/ack_generator/lib/src/analyzer/custom_schema_resolver.dart b/packages/ack_generator/lib/src/analyzer/custom_schema_resolver.dart index 52e1b608..526ef779 100644 --- a/packages/ack_generator/lib/src/analyzer/custom_schema_resolver.dart +++ b/packages/ack_generator/lib/src/analyzer/custom_schema_resolver.dart @@ -531,8 +531,13 @@ final class CustomSchemaResolver { path: path, context: field, ); - if (target.library != _library.element && - !_isClassFirstFacadeVisible(target, facadeName, prefix: prefix)) { + if (target.getGetter('schema')?.isStatic == true || + target.library != _library.element && + !_isClassFirstFacadeVisible( + target, + facadeName, + prefix: prefix, + )) { final typeOwned = await typeOwnedSchema( interfaceType, field, diff --git a/packages/ack_generator/lib/src/analyzer/model_graph_builder_base.dart b/packages/ack_generator/lib/src/analyzer/model_graph_builder_base.dart index 1f947cc1..5b211dec 100644 --- a/packages/ack_generator/lib/src/analyzer/model_graph_builder_base.dart +++ b/packages/ack_generator/lib/src/analyzer/model_graph_builder_base.dart @@ -167,9 +167,6 @@ abstract base class ModelGraphBuilderBase { bool hasSchemable(Element element) => schemableChecker.hasAnnotationOfExact(propertyDeclaration(element)); - /// The annotation spelling that marks [element] or its sealed base. - String annotationName(Element element) => '@Schemable'; - /// Reads the custom `name` override from `@Schemable(name: ...)` on [element]. String? schemableCustomName(Element element) { final declaration = propertyDeclaration(element); diff --git a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart index a7c05001..17cd2aee 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_first_names.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_first_names.dart @@ -1,10 +1,8 @@ import '../utils/string_literal.dart'; -/// Names that conflict with generated APIs or their unqualified type references. +/// Names that conflict with generated APIs. const ackSchemaFirstReservedMembers = { r'$ack', - // Generated JSON signatures use the unqualified dynamic type. - 'dynamic', 'parse', 'safeParse', 'fromJson', @@ -19,6 +17,19 @@ const ackSchemaFirstReservedMembers = { 'runtimeType', }; +const _generatedReferences = { + 'bool', + 'double', + 'int', + 'num', + 'override', + 'identical', + 'deepEquals', + 'deepHashCode', + 'deepUnmodifiableCopy', + 'deepUnmodifiableJsonMap', +}; + /// Why [key] cannot be a schema-first field name, or `null` when it can. /// /// [capturesExtras] is whether the model stores unknown properties in its @@ -26,17 +37,23 @@ const ackSchemaFirstReservedMembers = { String? ackSchemaFirstFieldNameProblem( String key, { required bool capturesExtras, + Set generatedReferences = const {}, }) { if (key.startsWith('_')) { return "cannot start with '_' (private Dart member)."; } - if (!RegExp(r'^[A-Za-z$][A-Za-z0-9_$]*$').hasMatch(key) || - isDartReservedWord(key)) { + if (!RegExp(r'^[A-Za-z$][A-Za-z0-9_$]*$').hasMatch(key)) { return 'cannot be represented as a Dart field name.'; } + if (isDartReservedWord(key)) { + return 'maps to the reserved Dart word "$key".'; + } if (key == 'dynamic') { return 'shadows the dynamic type used by generated JSON methods.'; } + if (_generatedReferences.contains(key) || generatedReferences.contains(key)) { + return 'shadows the generated reference "$key".'; + } if (ackSchemaFirstReservedMembers.contains(key)) { return 'conflicts with generated/Object member "$key".'; } @@ -45,3 +62,53 @@ String? ackSchemaFirstFieldNameProblem( } return null; } + +final _nonAsciiLetter = RegExp(r'(?![A-Za-z])\p{L}', unicode: true); + +/// Why a wire key cannot be converted to a schema-first Dart name. +String? ackSchemaFirstWireKeyProblem(String key) => + _nonAsciiLetter.hasMatch(key) + ? 'contains non-ASCII letters. Use a class-first model with @AckKey to ' + 'keep the wire key and choose its Dart name.' + : null; + +/// Records a wire key and reports when another key already maps to its name. +String? ackSchemaFirstFieldCollision( + Map wireKeysByFieldName, + String dartName, + String wireKey, +) { + final previous = wireKeysByFieldName.putIfAbsent(dartName, () => wireKey); + if (previous == wireKey) return null; + return 'JSON keys "$previous" and "$wireKey" that both map to ' + 'the Dart field "$dartName".'; +} + +final _wordBoundary = RegExp( + r'[^A-Za-z0-9]+|(?<=[a-z0-9])(?=[A-Z])|' + // Split HTTPServer and URLIsValid while keeping the plural s in URLs. + r'(?<=[A-Z])(?=[A-Z][a-z])(?![A-HJ-Z]s(?![a-z]))', +); + +Iterable _words(String key) => key + .split(_wordBoundary) + .where((word) => word.isNotEmpty) + .map((word) => word.toLowerCase()); + +String _upperInitial(String word) => + '${word[0].toUpperCase()}${word.substring(1)}'; + +/// UpperCamelCase segment for a generated model name derived from a key. +String ackSchemaFirstTypeNameSegment(String key) => + _words(key).map(_upperInitial).join(); + +/// Dart field name for a schema-first wire key. +String ackSchemaFirstDartFieldName(String key) { + final words = _words(key); + if (words.isEmpty) return ''; + return words.first + words.skip(1).map(_upperInitial).join(); +} + +/// Dart getter name corresponding to a schema-first union's wire discriminator. +String ackSchemaFirstDiscriminatorName(String key) => + ackSchemaFirstDartFieldName(key); diff --git a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart index 8888864b..95beae7d 100644 --- a/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart +++ b/packages/ack_generator/lib/src/analyzer/schema_model_graph_builder.dart @@ -7,7 +7,6 @@ import 'package:source_gen/source_gen.dart'; import '../json/helper_names.dart'; import '../models/schema_model_graph.dart'; -import '../utils/string_literal.dart'; import 'model_graph_builder_base.dart'; import 'schema_first_names.dart'; @@ -66,9 +65,7 @@ final class _SchemaMetadata { /// Builds the single normalized graph consumed by Ack model emission. final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { - SchemaModelGraphBuilder(super.library); - - static const _reservedMembers = ackSchemaFirstReservedMembers; + SchemaModelGraphBuilder(super.library, {super.ackPrefix}); static const _anyOfSchemaChecker = TypeChecker.typeNamed( AnyOfSchema, @@ -137,12 +134,11 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { .firstAnnotationOfExact(propertyDeclaration(element)); if (annotation == null) return; final reader = ConstantReader(annotation); - int index(String option) => - reader.read(option).objectValue.getField('index')!.toIntValue()!; + int? index(String option) => reader.peek(option)?.read('index').intValue; final configured = [ if (!reader.read('schemaName').isNull) 'schemaName', if (!reader.read('description').isNull) 'description', - if (index('caseStyle') != 0) 'caseStyle', + if (!reader.read('caseStyle').isNull) 'caseStyle', if (!reader.read('discriminatorKey').isNull) 'discriminatorKey', if (!reader.read('discriminatorValue').isNull) 'discriminatorValue', if (index('unknownProperties') != 0) 'unknownProperties', @@ -227,7 +223,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { _isCrossLibrarySchemable(chain.reference!)) { throw InvalidGenerationSource( '$path aliases a cross-library ' - '${annotationName(referencedElement(chain.reference!)!)} schema. ' + '@Schemable schema. ' 'Use the original model directly.', element: declaration.element, ); @@ -358,6 +354,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { ); final fields = []; final declaredKeys = {}; + final wireKeysByFieldName = {}; for (final entry in literal.elements) { if (entry is! MapLiteralEntry || entry.key is! SimpleStringLiteral) { throw InvalidGenerationSource( @@ -366,13 +363,27 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { ); } final jsonKey = (entry.key as SimpleStringLiteral).value; + final fieldPath = '$path.$jsonKey'; + if (ackSchemaFirstWireKeyProblem(jsonKey) case final problem?) { + throw InvalidGenerationSource( + '$fieldPath $problem', + element: declaration.element, + ); + } if (!declaredKeys.add(jsonKey)) { throw InvalidGenerationSource( '$path.$jsonKey is a duplicate object field. Declare each key once.', element: declaration.element, ); } - final fieldPath = '$path.$jsonKey'; + final dartName = ackSchemaFirstDartFieldName(jsonKey); + if (ackSchemaFirstFieldCollision(wireKeysByFieldName, dartName, jsonKey) + case final collision?) { + throw InvalidGenerationSource( + '$path has $collision', + element: declaration.element, + ); + } final fieldChain = parseSchemaChain(entry.value); final fieldMetadata = await _schemaMetadata( entry.value, @@ -395,7 +406,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { ); fields.add( AckFieldNode( - dartName: jsonKey, + dartName: dartName, jsonKey: jsonKey, presence: fieldMetadata.presence, nullable: fieldMetadata.nullable, @@ -446,12 +457,21 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { element: declaration.element, ); } - _rejectInvalidMemberName(discriminatorKey, path, declaration.element); - if (_reservedMembers.contains(discriminatorKey) || - discriminatorKey == 'additionalProperties') { + if (ackSchemaFirstWireKeyProblem(discriminatorKey) case final problem?) { throw InvalidGenerationSource( - '$path.$discriminatorKey conflicts with a generated member or Dart ' - 'keyword.', + '$path.$discriminatorKey $problem', + element: declaration.element, + ); + } + final discriminatorName = ackSchemaFirstDiscriminatorName(discriminatorKey); + final discriminatorProblem = ackSchemaFirstFieldNameProblem( + discriminatorName, + capturesExtras: true, + generatedReferences: {?ackPrefix, declaration.id.declarationName}, + ); + if (discriminatorProblem != null) { + throw InvalidGenerationSource( + '$path.$discriminatorKey $discriminatorProblem', element: declaration.element, ); } @@ -468,7 +488,8 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { final target = _localDeclaration(element.value); if (target == null) { throw InvalidGenerationSource( - '$path.$value is a cross-library or unresolvable discriminated branch.', + '$path.$value is a cross-library or unresolvable discriminated branch. ' + 'Reference a same-library object schema annotated with @Schemable().', element: declaration.element, ); } @@ -478,10 +499,20 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { if (branch is! AckObjectModelNode) { throw InvalidGenerationSource( '$path.$value must reference an ' - '${annotationName(declaration.element)} object schema.', + '@Schemable object schema.', element: declaration.element, ); } + for (final field in branch.fields) { + if (field.dartName == discriminatorName && + field.jsonKey != discriminatorKey) { + throw InvalidGenerationSource( + '$path.$value JSON key "${field.jsonKey}" conflicts with the ' + 'Dart discriminator getter "$discriminatorName".', + element: declaration.element, + ); + } + } final owner = _unionOwnerByBranch[target.id]; if (owner != null && owner != declaration.id) { throw InvalidGenerationSource( @@ -1102,7 +1133,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { ); if (model == null) { throw InvalidGenerationSource( - '$path Ack.lazy must resolve to a named ${annotationName(context)} ' + '$path Ack.lazy must resolve to a named @Schemable ' 'schema.', element: context, ); @@ -1261,7 +1292,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { if (customName.trim() != customName || !RegExp(r'^[A-Z][A-Za-z0-9]*$').hasMatch(customName)) { throw InvalidGenerationSource( - 'Invalid ${annotationName(element)} name "$customName". Names must ' + 'Invalid @Schemable name "$customName". Names must ' 'be unchanged UpperCamelCase identifiers.', element: element, ); @@ -1288,7 +1319,7 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { final name = declaration.className; if (!generated.add(name)) { throw InvalidGenerationSource( - 'Multiple ${annotationName(declaration.element)} declarations ' + 'Multiple @Schemable declarations ' 'generate "$name".', element: declaration.element, ); @@ -1315,7 +1346,29 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { final declaration = _declarationsById[node.id]; if (declaration == null) continue; - void checkMember(String name) { + final references = { + ?ackPrefix, + (_unionOwnerByBranch[node.id] ?? node.id).declarationName, + if (node is AckObjectModelNode) + for (final field in node.fields) ..._typeReferences(field.runtimeRef), + }; + + void checkMember( + String key, + String name, { + required bool capturesExtras, + }) { + final problem = ackSchemaFirstFieldNameProblem( + name, + capturesExtras: capturesExtras, + generatedReferences: references, + ); + if (problem != null) { + throw InvalidGenerationSource( + '${node.id.declarationName}.$key $problem', + element: declaration.element, + ); + } if (name != node.className) return; throw InvalidGenerationSource( '${node.id.declarationName}.$name conflicts with the generated ' @@ -1325,25 +1378,27 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { } if (node is AckUnionModelNode) { - checkMember(node.discriminatorKey); + checkMember( + node.discriminatorKey, + ackSchemaFirstDiscriminatorName(node.discriminatorKey), + capturesExtras: true, + ); continue; } if (node is AckObjectModelNode) { for (final field in node.fields) { - final problem = ackSchemaFirstFieldNameProblem( + checkMember( + field.jsonKey, field.dartName, capturesExtras: node.additionalProperties, ); - if (problem != null) { - throw InvalidGenerationSource( - '${node.id.declarationName}.${field.dartName} $problem', - element: declaration.element, - ); - } - checkMember(field.dartName); } if (node.discriminatorKey case final discriminator?) { - checkMember(discriminator); + checkMember( + discriminator, + ackSchemaFirstDiscriminatorName(discriminator), + capturesExtras: true, + ); } } validateCopyWithHelperNames( @@ -1361,6 +1416,37 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { } } + Iterable _typeReferences(AckInferRef type) sync* { + switch (type) { + case AckExternalTypeRef( + :final name, + :final importPrefix, + :final typeArguments, + ): + yield importPrefix ?? name; + for (final argument in typeArguments) { + yield* _typeReferences(argument); + } + case AckModelTypeRef( + :final className, + :final importPrefix, + :final runtimeRef, + ): + yield importPrefix ?? className; + yield* _typeReferences(runtimeRef); + case AckListTypeRef(:final elementType) || + AckSetTypeRef(:final elementType): + yield* _typeReferences(elementType); + case AckMapTypeRef(:final valueType) || + AckJsonMaybeTypeRef(:final valueType): + yield* _typeReferences(valueType); + case AckNullableTypeRef(:final inner): + yield* _typeReferences(inner); + case AckScalarTypeRef(): + break; + } + } + void _validateUnionBranchDiscriminator( _Declaration branch, String discriminatorKey, @@ -1405,22 +1491,6 @@ final class SchemaModelGraphBuilder extends ModelGraphBuilderBase { }; } - void _rejectInvalidMemberName(String jsonKey, String path, Element element) { - if (jsonKey.startsWith('_')) { - throw InvalidGenerationSource( - "$path.$jsonKey cannot start with '_' (private Dart member).", - element: element, - ); - } - if (!RegExp(r'^[A-Za-z$][A-Za-z0-9_$]*$').hasMatch(jsonKey) || - isDartReservedWord(jsonKey)) { - throw InvalidGenerationSource( - '$path.$jsonKey cannot be represented as a Dart field name.', - element: element, - ); - } - } - void _rejectUnsupportedSchemaType( Expression expression, String path, diff --git a/packages/ack_generator/lib/src/builders/class_model_emitter.dart b/packages/ack_generator/lib/src/builders/class_model_emitter.dart index 8641d85f..5478387c 100644 --- a/packages/ack_generator/lib/src/builders/class_model_emitter.dart +++ b/packages/ack_generator/lib/src/builders/class_model_emitter.dart @@ -139,7 +139,7 @@ final ${metadata.backingName} = $rawName.codec<${node.className}>( decode: (value) => switch (value[${dartStringLiteral(node.discriminatorKey)}]) { ${decodeCases.join(',\n ')}, final unknown => throw StateError( - 'Unknown ${node.discriminatorKey}: \$unknown', + ${dartStringLiteral('Unknown ${node.discriminatorKey}: ')} '\$unknown', ), }, encode: (model) => switch (model) { @@ -183,8 +183,11 @@ final $backingName = $input.codec<${node.className}>( String className, AckClassModelMetadata metadata, { required String wireName, - }) => - ''' + }) { + final validationSchema = metadata.hasStaticSchema + ? '$className.schema' + : metadata.backingName; + return ''' /// Parses, validates, and encodes [$className] values. abstract final class ${metadata.facadeName} { /// The typed schema, for composing [$className] into other schemas. @@ -199,13 +202,13 @@ abstract final class ${metadata.facadeName} { /// /// Throws an `AckException` when validation fails. static $className parse(Object? value, {String? debugName}) => - ${metadata.backingName}.parse(value, debugName: debugName)!; + $validationSchema.parse(value, debugName: debugName)!; /// Validates [value] and returns the model or the validation failure. static ${_ack('SchemaResult')}<$className> safeParse( Object? value, { String? debugName, - }) => ${metadata.backingName}.safeParse(value, debugName: debugName); + }) => $validationSchema.safeParse(value, debugName: debugName); /// Validates decoded [json] and creates the model. /// @@ -218,14 +221,14 @@ abstract final class ${metadata.facadeName} { static Map encode( $className value, { String? debugName, - }) => ${metadata.backingName}.encode(value, debugName: debugName)!; + }) => $validationSchema.encode(value, debugName: debugName)!; /// Validates [value] and encodes it as a JSON map, returning the validation /// failure instead of throwing. static ${_ack('SchemaResult')}> safeEncode( $className value, { String? debugName, - }) => ${metadata.backingName}.safeEncode(value, debugName: debugName); + }) => $validationSchema.safeEncode(value, debugName: debugName); /// The JSON Schema that describes [$className]. static Map toJsonSchema() => @@ -235,6 +238,7 @@ abstract final class ${metadata.facadeName} { static ${_ack('AckSchemaModel')} toSchemaModel() => ${_ack('AckSchemaModelExtension')}(${metadata.backingName}).toSchemaModel(); }'''; + } String _objectSchema(AckObjectModelNode node) { final entries = [ @@ -257,13 +261,26 @@ abstract final class ${metadata.facadeName} { final fieldsByName = { for (final field in node.fields) field.dartName: field, }; + // Defaults can reference Dart identifiers from the user's library, + // including ones containing a dollar sign. + final defaults = node.constructorParameters + .map((parameter) => parameter.defaultExpression) + .nonNulls; + var prefix = r'$ack'; + while (defaults.any((expression) => expression.contains(prefix))) { + prefix += r'$'; + } + final value = '${prefix}Value'; + final declared = '${prefix}Declared'; + final entry = '${prefix}Entry'; + final fieldValue = '${prefix}FieldValue'; final arguments = []; for (final parameter in node.constructorParameters) { final String expression; if (parameter.fieldName == node.captureFieldName) { expression = '${_ack('deepUnmodifiableJsonMap')}(Map.fromEntries(\n' - ' value.entries.where((entry) => !declared.contains(entry.key)),\n' + ' $value.entries.where(($entry) => !$declared.contains($entry.key)),\n' ' ))'; } else { final field = fieldsByName[parameter.fieldName]; @@ -272,7 +289,7 @@ abstract final class ${metadata.facadeName} { 'Missing field ${parameter.fieldName} on ${node.className}.', ); } - expression = _decodeParameter(parameter, field); + expression = _decodeParameter(parameter, field, value, fieldValue); } arguments.add( parameter.kind == AckConstructorParameterKind.named @@ -283,13 +300,13 @@ abstract final class ${metadata.facadeName} { if (node.captureFieldName == null) { return ''' -${node.className} $function(Map value) => +${node.className} $function(Map $value) => ${node.className}(${arguments.join(', ')});'''; } - final declared = _declaredKeys(node); + final keys = _declaredKeys(node); return ''' -${node.className} $function(Map value) { - const declared = ${_dataClasses.declaredKeysLiteral(declared)}; +${node.className} $function(Map $value) { + const $declared = ${_dataClasses.declaredKeysLiteral(keys)}; return ${node.className}( ${arguments.join(',\n ')}, ); @@ -299,10 +316,12 @@ ${node.className} $function(Map value) { String _decodeParameter( AckConstructorParameter parameter, AckFieldNode field, + String value, + String fieldValue, ) { if (parameter.typeRef case AckJsonMaybeTypeRef(:final valueType)) { final keyLiteral = dartStringLiteral(field.jsonKey); - final raw = 'value[$keyLiteral]'; + final raw = '$value[$keyLiteral]'; final innerType = _type(valueType); final baseValueType = _dataClasses.nonNullable(valueType); final absentExpr = @@ -323,13 +342,13 @@ ${node.className} $function(Map value) { presentExpr = 'switch ($raw) {' ' null => const ${_ack('JsonMaybe')}<$innerType>.value(null),' - ' final fieldValue => ${_ack('JsonMaybe')}<$innerType>.value(' - '${_fromRuntime(baseValueType, 'fieldValue')}),' + ' final $fieldValue => ${_ack('JsonMaybe')}<$innerType>.value(' + '${_fromRuntime(baseValueType, fieldValue)}),' ' }'; } - return '!value.containsKey($keyLiteral) ? $absentExpr : $presentExpr'; + return '!$value.containsKey($keyLiteral) ? $absentExpr : $presentExpr'; } - final raw = 'value[${dartStringLiteral(field.jsonKey)}]'; + final raw = '$value[${dartStringLiteral(field.jsonKey)}]'; final defaultExpr = parameter.defaultExpression != null && parameter.defaultExpression != 'null' @@ -350,7 +369,7 @@ ${node.className} $function(Map value) { final nullBranch = defaultExpr ?? 'null'; return 'switch ($raw) {' ' null => $nullBranch,' - ' final fieldValue => ${_fromRuntime(baseType, 'fieldValue')},' + ' final $fieldValue => ${_fromRuntime(baseType, fieldValue)},' ' }'; } @@ -373,13 +392,13 @@ Map $function(${node.className} model) => {${fieldEntries.join(', ')}};'''; } final entries = [ - 'for (final entry in model.$capture.entries)\n' - ' if (!declared.contains(entry.key)) entry.key: entry.value', + 'for (final \$ackEntry in model.$capture.entries)\n' + ' if (!\$ackDeclared.contains(\$ackEntry.key)) \$ackEntry.key: \$ackEntry.value', ...fieldEntries, ]; return ''' Map $function(${node.className} model) { - const declared = ${_dataClasses.declaredKeysLiteral(_declaredKeys(node))}; + const \$ackDeclared = ${_dataClasses.declaredKeysLiteral(_declaredKeys(node))}; return { ${entries.join(',\n ')}, }; diff --git a/packages/ack_generator/lib/src/builders/data_class_emitter.dart b/packages/ack_generator/lib/src/builders/data_class_emitter.dart index d097b1b7..538c7643 100644 --- a/packages/ack_generator/lib/src/builders/data_class_emitter.dart +++ b/packages/ack_generator/lib/src/builders/data_class_emitter.dart @@ -75,13 +75,13 @@ final class AckDataClassEmitter { ]; final members = [ if (includeValueMembers) ...[ - copyWithGetter( + for (final method in valueMethods( className: className, + fields: stored, hasParameters: copyWithParameters.isNotEmpty, castSelf: true, - ), - equalityMembers(className: className, fields: stored, castSelf: true), - toStringMethod(className: className, fields: stored, castSelf: true), + )) + '${method.accept(DartEmitter())}${method.lambda == true ? ';' : ''}', ], jsonMembers(className: className, facadeName: facadeName), ]; @@ -93,58 +93,97 @@ ${includeValueMembers ? '${copyWithContract(className: className, parameters: co } /// Emits `copyWith`, `operator ==`, `hashCode`, and `toString` for a - /// schema-first model class. + /// generated model class or mixin. List valueMethods({ required String className, required List fields, required bool hasParameters, - }) => [ - Method( - (m) => m - ..name = 'copyWith' - ..type = MethodType.getter - ..returns = refer('${ackCopyWithInterfaceName(className)}<$className>') - ..docs.add( - '/// Creates a copy of this model with selected fields replaced.', - ) - ..lambda = true - ..body = Code( - _copyWithCreation(className, hasParameters: hasParameters), + bool castSelf = false, + }) { + final castFields = castSelf && fields.isNotEmpty; + final comparisons = [ + for (final field in fields) + _equals( + '${castFields ? 'self' : 'this'}.${field.dartName}', + 'other.${field.dartName}', ), - ), - Method( - (m) => m - ..name = 'operator ==' - ..annotations.add(refer('override')) - ..returns = refer('bool') - ..requiredParameters.add( - Parameter( - (p) => p - ..name = 'other' - ..type = refer('Object'), + ]; + final equalsBody = castFields + ? ''' +if (identical(this, other)) return true; +if (other is! $className || runtimeType != other.runtimeType) return false; +final self = this as $className; +return ${comparisons.join(' && ')}; +''' + : _directEqualsExpression(className, comparisons); + final hash = _hashExpression(fields, receiver: castFields ? 'self' : null); + final preview = _toStringPreview( + className, + fields, + receiver: castFields ? 'self' : null, + ); + return [ + Method( + (m) => m + ..name = 'copyWith' + ..type = MethodType.getter + ..returns = refer( + '${ackCopyWithInterfaceName(className)}<$className>', + ) + ..docs.add( + '/// Creates a copy of this model with selected fields replaced.', + ) + ..lambda = true + ..body = Code( + _copyWithCreation( + className, + hasParameters: hasParameters, + castSelf: castSelf, + ), + ), + ), + Method( + (m) => m + ..name = 'operator ==' + ..annotations.add(refer('override')) + ..returns = refer('bool') + ..requiredParameters.add( + Parameter( + (p) => p + ..name = 'other' + ..type = refer('Object'), + ), + ) + ..lambda = !castFields + ..body = Code(equalsBody), + ), + Method( + (m) => m + ..name = 'hashCode' + ..annotations.add(refer('override')) + ..type = MethodType.getter + ..returns = refer('int') + ..lambda = !castFields + ..body = Code( + castFields + ? 'final self = this as $className; return $hash;' + : hash, + ), + ), + Method( + (m) => m + ..name = 'toString' + ..annotations.add(refer('override')) + ..returns = refer('String') + ..lambda = !castFields + ..body = Code( + castFields + ? "final self = this as $className; return '$preview';" + : "'$preview'", ), - ) - ..lambda = true - ..body = Code(_directEqualsExpression(className, fields)), - ), - Method( - (m) => m - ..name = 'hashCode' - ..annotations.add(refer('override')) - ..type = MethodType.getter - ..returns = refer('int') - ..lambda = true - ..body = Code(_hashExpression(fields)), - ), - Method( - (m) => m - ..name = 'toString' - ..annotations.add(refer('override')) - ..returns = refer('String') - ..lambda = true - ..body = Code("'${_toStringPreview(className, fields)}'"), - ), - ]; + ), + ]; + } /// The typed `copyWith` interface and its implementation, plus the private /// sentinel type when a nullable field needs one. @@ -211,78 +250,6 @@ $sentinelField$sourceField @override }'''; } - /// The `copyWith` getter that exposes [copyWithContract]'s interface. - String copyWithGetter({ - required String className, - required bool hasParameters, - bool castSelf = false, - }) { - final creation = _copyWithCreation( - className, - hasParameters: hasParameters, - castSelf: castSelf, - ); - return ''' -/// Creates a copy of this model with selected fields replaced. -${ackCopyWithInterfaceName(className)}<$className> get copyWith => $creation;'''; - } - - String equalityMembers({ - required String className, - required List fields, - bool castSelf = false, - }) { - if (castSelf && fields.isNotEmpty) { - final fieldEquals = [ - for (final field in fields) - _equals('self.${field.dartName}', 'other.${field.dartName}'), - ]; - final equality = fieldEquals.isEmpty ? 'true' : fieldEquals.join(' && '); - final hashes = _hashExpression(fields, receiver: 'self'); - return ''' -@override -bool operator ==(Object other) { - if (identical(this, other)) return true; - if (other is! $className || runtimeType != other.runtimeType) { - return false; - } - final self = this as $className; - return $equality; -} - -@override -int get hashCode { - final self = this as $className; - return $hashes; -}'''; - } - return ''' -@override -bool operator ==(Object other) => - ${_directEqualsExpression(className, fields)}; - -@override -int get hashCode => ${_hashExpression(fields)};'''; - } - - String toStringMethod({ - required String className, - required List fields, - bool castSelf = false, - }) { - if (castSelf && fields.isNotEmpty) { - return ''' -@override -String toString() { - final self = this as $className; - return '${_toStringPreview(className, fields, receiver: 'self')}'; -}'''; - } - return ''' -@override -String toString() => '${_toStringPreview(className, fields)}';'''; - } - String jsonMembers({required String className, required String facadeName}) { return ''' /// Validates this model and encodes it for JSON. @@ -308,12 +275,14 @@ ${_ack('SchemaResult')}> safeToJson() => : 'const $implementationName()'; } - String _directEqualsExpression(String className, List fields) { + String _directEqualsExpression( + String className, + List fieldComparisons, + ) { final comparisons = [ 'other is $className', 'runtimeType == other.runtimeType', - for (final field in fields) - _equals(field.dartName, 'other.${field.dartName}'), + ...fieldComparisons, ]; return 'identical(this, other) || (${comparisons.join(' && ')})'; } diff --git a/packages/ack_generator/lib/src/builders/model_emitter.dart b/packages/ack_generator/lib/src/builders/model_emitter.dart index 2f7389cb..5b43067d 100644 --- a/packages/ack_generator/lib/src/builders/model_emitter.dart +++ b/packages/ack_generator/lib/src/builders/model_emitter.dart @@ -1,5 +1,6 @@ import 'package:code_builder/code_builder.dart'; +import '../analyzer/schema_first_names.dart'; import '../models/schema_model_graph.dart'; import '../utils/string_literal.dart'; import 'data_class_emitter.dart'; @@ -176,7 +177,9 @@ final class AckModelEmitter { _adapter(node, node.id.declarationName), if (_exposesSchemaShorthand( declarationName: node.id.declarationName, - discriminatorKey: node.discriminatorKey, + discriminatorKey: ackSchemaFirstDiscriminatorName( + node.discriminatorKey, + ), )) _schemaShorthand(node), ]) @@ -194,7 +197,7 @@ final class AckModelEmitter { Method( (m) => m ..type = MethodType.getter - ..name = node.discriminatorKey + ..name = ackSchemaFirstDiscriminatorName(node.discriminatorKey) ..docs.add( '/// The discriminator value that selects this branch.', ) @@ -218,7 +221,7 @@ final class AckModelEmitter { return switch (value[${dartStringLiteral(node.discriminatorKey)}]) { ${cases.join(',\n ')}, final unknown => throw StateError( - 'Unknown ${node.discriminatorKey}: \$unknown', + ${dartStringLiteral('Unknown ${node.discriminatorKey}: ')} '\$unknown', ), };'''), ), @@ -251,7 +254,7 @@ return switch (value[${dartStringLiteral(node.discriminatorKey)}]) { if (_exposesSchemaShorthand( declarationName: union.id.declarationName, fields: fields, - discriminatorKey: discriminator, + discriminatorKey: ackSchemaFirstDiscriminatorName(discriminator), )) _schemaShorthand(node), ]) @@ -269,7 +272,7 @@ return switch (value[${dartStringLiteral(node.discriminatorKey)}]) { (m) => m ..annotations.add(refer('override')) ..type = MethodType.getter - ..name = discriminator + ..name = ackSchemaFirstDiscriminatorName(discriminator) ..returns = refer('String') ..lambda = true ..body = Code(dartStringLiteral(value)), @@ -646,7 +649,7 @@ ${_ack('AckModelAdapter')}( final allArguments = [ ...arguments, 'additionalProperties: Map.fromEntries(\n' - ' value.entries.where((entry) => !declared.contains(entry.key)),\n' + ' value.entries.where((entry) => !_ackDeclaredKeys.contains(entry.key)),\n' ' )', ]; return Method( @@ -662,7 +665,7 @@ ${_ack('AckModelAdapter')}( ), ) ..body = Code(''' -const declared = ${_dataClasses.declaredKeysLiteral(keys)}; +const _ackDeclaredKeys = ${_dataClasses.declaredKeysLiteral(keys)}; return ${node.className}( ${allArguments.join(',\n ')}, );'''), @@ -701,11 +704,11 @@ return ${node.className}( ); final allEntries = [ 'for (final entry in additionalProperties.entries)\n' - ' if (!declared.contains(entry.key)) entry.key: entry.value', + ' if (!_ackDeclaredKeys.contains(entry.key)) entry.key: entry.value', ...entries, ]; m.body = Code(''' -const declared = $declaredLiteral; +const _ackDeclaredKeys = $declaredLiteral; return $_runtimeMapLiteral{ ${allEntries.join(',\n ')}, };'''); @@ -731,7 +734,7 @@ return $_runtimeMapLiteral{ String _encodeField(AckFieldNode field) => _dataClasses.encodeField( field.runtimeRef, - field.dartName, + 'this.${field.dartName}', nullable: !field.isRequired || field.nullable, ); diff --git a/packages/ack_generator/lib/src/inference/schema_inference.dart b/packages/ack_generator/lib/src/inference/schema_inference.dart index 6039672c..4e1a3f3e 100644 --- a/packages/ack_generator/lib/src/inference/schema_inference.dart +++ b/packages/ack_generator/lib/src/inference/schema_inference.dart @@ -73,7 +73,7 @@ final class AckSchemaInference { typeArguments: type.typeArguments, nullabilitySuffix: NullabilitySuffix.none, ); - return '${_ack('Ack')}.list($itemSchema).codec<${renderType(runtimeType)}>(decode: (list) => list.toSet(), encode: (set) => set.toList(growable: false),)'; + return '${_ack('Ack')}.list($itemSchema).unique().codec<${renderType(runtimeType)}>(decode: (list) => list.toSet(), encode: (set) => set.toList(growable: false),)'; } if (type.isDartCoreMap) { validateMapKey(type); @@ -106,10 +106,10 @@ final class AckSchemaInference { (_core(scalarType, 'int') || _core(scalarType, 'double') || _core(scalarType, 'num')); + final isInteger = scalarType is InterfaceType && _core(scalarType, 'int'); final isString = scalarType is InterfaceType && _core(scalarType, 'String'); final itemConstraints = []; final setConstraints = []; - var hasUniqueConstraint = false; void addScalarConstraint(String constraint) { if (isCollection) { @@ -119,9 +119,8 @@ final class AckSchemaInference { } } - void addCollectionConstraint(String constraint, {bool isUnique = false}) { + void addCollectionConstraint(String constraint) { if (isSet) { - if (isUnique) hasUniqueConstraint = true; setConstraints.add(constraint); } else { output = '$output$constraint'; @@ -141,17 +140,17 @@ final class AckSchemaInference { case 'HasMin': _require(declaration, type, annotation, isNumeric, '@HasMinLength'); addScalarConstraint( - '.min(${_number(declaration, annotation, value, 'min')})', + '.min(${_number(declaration, annotation, value, 'min', requireInteger: isInteger)})', ); case 'HasMax': _require(declaration, type, annotation, isNumeric, '@HasMaxLength'); addScalarConstraint( - '.max(${_number(declaration, annotation, value, 'max')})', + '.max(${_number(declaration, annotation, value, 'max', requireInteger: isInteger)})', ); case 'IsMultipleOf': _require(declaration, type, annotation, isNumeric, 'numeric field'); addScalarConstraint( - '.multipleOf(${_number(declaration, annotation, value, 'divisor')})', + '.multipleOf(${_number(declaration, annotation, value, 'divisor', requireInteger: isInteger)})', ); case 'IsPositive': _require(declaration, type, annotation, isNumeric, 'numeric field'); @@ -161,15 +160,27 @@ final class AckSchemaInference { addScalarConstraint('.negative()'); case 'HasMinLength': _require(declaration, type, annotation, isString, '@HasMin'); - addScalarConstraint('.minLength(${_int(value, 'length')})'); + addScalarConstraint( + '.minLength(${_nonNegativeInt(declaration, annotation, value, 'length')})', + ); case 'HasMaxLength': _require(declaration, type, annotation, isString, '@HasMax'); - addScalarConstraint('.maxLength(${_int(value, 'length')})'); - case 'HasMatch': - _require(declaration, type, annotation, isString, 'String field'); addScalarConstraint( - '.matches(${dartStringLiteral(value.getField('pattern')!.toStringValue()!)})', + '.maxLength(${_nonNegativeInt(declaration, annotation, value, 'length')})', ); + case 'HasMatch': + _require(declaration, type, annotation, isString, 'String field'); + final pattern = value.getField('pattern')!.toStringValue()!; + try { + RegExp(pattern); + } on FormatException catch (error) { + throw InvalidGenerationSource( + '${_qualifiedName(declaration)} has an invalid @HasMatch ' + 'regular expression: ${error.message}', + element: declaration, + ); + } + addScalarConstraint('.matches(${dartStringLiteral(pattern)})'); case 'IsNotEmpty': _require( declaration, @@ -221,7 +232,9 @@ final class AckSchemaInference { isCollection, 'List or Set field', ); - addCollectionConstraint('.minItems(${_int(value, 'count')})'); + addCollectionConstraint( + '.minItems(${_nonNegativeInt(declaration, annotation, value, 'count')})', + ); case 'HasMaxItems': _require( declaration, @@ -230,7 +243,9 @@ final class AckSchemaInference { isCollection, 'List or Set field', ); - addCollectionConstraint('.maxItems(${_int(value, 'count')})'); + addCollectionConstraint( + '.maxItems(${_nonNegativeInt(declaration, annotation, value, 'count')})', + ); case 'HasUniqueItems': _require( declaration, @@ -239,7 +254,7 @@ final class AckSchemaInference { isCollection, 'List or Set field', ); - addCollectionConstraint('.unique()', isUnique: true); + if (!isSet) addCollectionConstraint('.unique()'); default: throw InvalidGenerationSource( '${_qualifiedName(declaration)} has unsupported rule $annotation.', @@ -251,11 +266,6 @@ final class AckSchemaInference { output = _appendListItemConstraints(output, itemConstraints.join()); } if (setConstraints.isNotEmpty) { - if (isSet && !hasUniqueConstraint) { - // A Set cannot retain duplicate values after decoding. Validate the - // boundary with the same cardinality before the codec runs. - setConstraints.add('.unique()'); - } output = _beforeOuterCodec(output, setConstraints.join()); } return output; @@ -351,15 +361,30 @@ final class AckSchemaInference { String _ack(String symbol) => qualifySymbol(ackPrefix, symbol); - int _int(DartObject value, String name) => - value.getField(name)!.toIntValue()!; - - String _number( + int _nonNegativeInt( Element declaration, String annotation, DartObject value, String name, ) { + final argument = value.getField(name)!.toIntValue()!; + if (argument < 0) { + throw InvalidGenerationSource( + '${_qualifiedName(declaration)} has $annotation($argument). ' + 'The $name must be nonnegative.', + element: declaration, + ); + } + return argument; + } + + String _number( + Element declaration, + String annotation, + DartObject value, + String name, { + required bool requireInteger, + }) { final field = value.getField(name)!; final number = (field.toIntValue() ?? field.toDoubleValue())!; if (!number.isFinite) { @@ -369,6 +394,13 @@ final class AckSchemaInference { element: declaration, ); } + if (requireInteger && number is! int) { + throw InvalidGenerationSource( + '${_qualifiedName(declaration)} has $annotation($number). ' + 'Use an integer argument on an int field.', + element: declaration, + ); + } return number.toString(); } diff --git a/packages/ack_generator/lib/src/json_schema/json_schema_emitter.dart b/packages/ack_generator/lib/src/json_schema/json_schema_emitter.dart index 7927d8d6..73c48a0c 100644 --- a/packages/ack_generator/lib/src/json_schema/json_schema_emitter.dart +++ b/packages/ack_generator/lib/src/json_schema/json_schema_emitter.dart @@ -28,7 +28,7 @@ String _emit( ..writeln(); if (includeParts) { buffer - ..writeln("part '$partStem.g.dart';") + ..writeln("part ${dartStringLiteral('$partStem.g.dart')};") ..writeln(); } for (final declaration in translator.declarations) { @@ -46,6 +46,7 @@ String _emitFallback( required Map documents, required bool assertFormats, required List widened, + required List propertyNameDiagnostics, }) { final defs = document[r'$defs'] as Map? ?? const {}; const rootAnnotations = { @@ -103,6 +104,9 @@ String _emitFallback( ..writeln( '// Complex shapes use Object? values, not inferred typed fields.', ); + for (final diagnostic in propertyNameDiagnostics) { + buffer.writeln('// Property name fallback: ${_commentText('$diagnostic')}'); + } if (widened.isNotEmpty) { buffer.writeln('// unknown_properties: preserve widened these objects:'); for (final pointer in widened) { diff --git a/packages/ack_generator/lib/src/json_schema/json_schema_library.dart b/packages/ack_generator/lib/src/json_schema/json_schema_library.dart index 75529c50..49d15e37 100644 --- a/packages/ack_generator/lib/src/json_schema/json_schema_library.dart +++ b/packages/ack_generator/lib/src/json_schema/json_schema_library.dart @@ -152,6 +152,7 @@ AckJsonSchemaLibrary generateAckSchemaLibrary({ bool includeParts = true, Version? languageVersion, }) { + var propertyNameDiagnostics = const []; if (options.modelMode == AckJsonSchemaModelMode.auto) { final translator = _Translator(documentUri, options, documents); final effective = translator.prepare(document); @@ -172,6 +173,7 @@ AckJsonSchemaLibrary generateAckSchemaLibrary({ widenedPointers: List.unmodifiable(translator.widened), ); } + propertyNameDiagnostics = translator.propertyNameDiagnostics; } // The typed translator is intentionally conservative. A valid document it @@ -197,6 +199,7 @@ AckJsonSchemaLibrary generateAckSchemaLibrary({ documents: fallbackDocuments, assertFormats: options.assertFormats, widened: fallback.widened, + propertyNameDiagnostics: propertyNameDiagnostics, ), ), effectiveDocument: fallbackDocument, diff --git a/packages/ack_generator/lib/src/json_schema/json_schema_translator.dart b/packages/ack_generator/lib/src/json_schema/json_schema_translator.dart index fd4734f4..262ca423 100644 --- a/packages/ack_generator/lib/src/json_schema/json_schema_translator.dart +++ b/packages/ack_generator/lib/src/json_schema/json_schema_translator.dart @@ -98,6 +98,7 @@ final class _Translator { final AckJsonSchemaLibraryOptions options; final Map documents; final diagnostics = []; + final propertyNameDiagnostics = []; final declarations = <_Declaration>[]; final widened = []; @@ -106,8 +107,15 @@ final class _Translator { final _edgePointers = <(String, String), String>{}; late Map _defs; - void _fail(String pointer, String message) => - diagnostics.add(AckJsonSchemaDiagnostic(pointer, message)); + void _fail( + String pointer, + String message, { + bool explainPropertyNameFallback = false, + }) { + final diagnostic = AckJsonSchemaDiagnostic(pointer, message); + diagnostics.add(diagnostic); + if (explainPropertyNameFallback) propertyNameDiagnostics.add(diagnostic); + } /// Validates the document shape and names, applies widenings, and gates the /// result through `Ack.fromJsonSchema`. Returns `null` on failure. @@ -859,29 +867,40 @@ final class _Translator { final entries = []; if (properties is Map) { + final wireKeysByFieldName = {}; + final generatedReferences = {'ack', _variable(hoistName)}; for (final MapEntry(key: key, value: value) in properties.entries) { final fieldPointer = '$pointer/properties/${_token(key)}'; - if (key == hoistName) { + final dartName = ackSchemaFirstDartFieldName(key); + final problem = + ackSchemaFirstWireKeyProblem(key) ?? + ackSchemaFirstFieldNameProblem( + dartName, + capturesExtras: open, + generatedReferences: generatedReferences, + ); + if (problem != null) { _fail( fieldPointer, - 'Property "$key" would have the same name as its generated ' - 'model class.', + 'Property "$key" $problem', + explainPropertyNameFallback: true, ); continue; } - final problem = ackSchemaFirstFieldNameProblem( - key, - capturesExtras: open, - ); - if (problem != null) { - _fail(fieldPointer, 'Property "$key" $problem'); + if (ackSchemaFirstFieldCollision(wireKeysByFieldName, dartName, key) + case final collision?) { + _fail( + fieldPointer, + 'Object has $collision', + explainPropertyNameFallback: true, + ); continue; } final field = _expr( value, fieldPointer, owner: owner, - hoistName: '$hoistName${key[0].toUpperCase()}${key.substring(1)}', + hoistName: '$hoistName${ackSchemaFirstTypeNameSegment(key)}', ); if (field == null) continue; entries.add( diff --git a/packages/ack_generator/lib/src/model_generator.dart b/packages/ack_generator/lib/src/model_generator.dart index 011424db..915877ce 100644 --- a/packages/ack_generator/lib/src/model_generator.dart +++ b/packages/ack_generator/lib/src/model_generator.dart @@ -89,10 +89,13 @@ final class AckModelGenerator extends Generator { ({AckModelGraph graph, String? ackPrefix})? schemaFirst; if (annotated.isNotEmpty) { - final graph = await SchemaModelGraphBuilder(library).build(annotated); + final ackPrefix = _ackRuntimeQualifier(library, annotated.first); schemaFirst = ( - graph: graph, - ackPrefix: _ackRuntimeQualifier(library, annotated.first), + graph: await SchemaModelGraphBuilder( + library, + ackPrefix: ackPrefix, + ).build(annotated), + ackPrefix: ackPrefix, ); } ({AckModelGraph graph, String? ackPrefix})? classFirst; @@ -143,7 +146,6 @@ final class AckModelGenerator extends Generator { final body = output.where((chunk) => chunk.trim().isNotEmpty).join('\n\n'); if (body.isEmpty) return ''; return '// ignore_for_file: type=lint\n' - '// ignore_for_file: invalid_use_of_internal_member\n' '// coverage:ignore-file\n\n' '$body'; } @@ -204,13 +206,12 @@ final class AckModelGenerator extends Generator { final annotation = _schemableChecker.firstAnnotationOfExact(libraryElement); if (annotation == null) return; final reader = ConstantReader(annotation); - int index(String option) => - reader.read(option).objectValue.getField('index')!.toIntValue()!; + int? index(String option) => reader.peek(option)?.read('index').intValue; final configured = [ if (!reader.read('name').isNull) 'name', if (!reader.read('schemaName').isNull) 'schemaName', if (!reader.read('description').isNull) 'description', - if (index('caseStyle') != 0) 'caseStyle', + if (!reader.read('caseStyle').isNull) 'caseStyle', if (!reader.read('discriminatorKey').isNull) 'discriminatorKey', if (!reader.read('discriminatorValue').isNull) 'discriminatorValue', if (index('unknownProperties') != 0) 'unknownProperties', diff --git a/packages/ack_generator/lib/src/models/schema_model_graph.dart b/packages/ack_generator/lib/src/models/schema_model_graph.dart index 303ee88b..dc9145c8 100644 --- a/packages/ack_generator/lib/src/models/schema_model_graph.dart +++ b/packages/ack_generator/lib/src/models/schema_model_graph.dart @@ -204,11 +204,13 @@ final class AckClassModelMetadata { const AckClassModelMetadata({ required this.facadeName, required this.backingName, + this.hasStaticSchema = false, this.copyWithSupertypes = const [], }); final String facadeName; final String backingName; + final bool hasStaticSchema; final List copyWithSupertypes; } diff --git a/packages/ack_generator/test/integration/ack_infer_contract_test.dart b/packages/ack_generator/test/integration/ack_infer_contract_test.dart index 0dae8eec..f4a86da9 100644 --- a/packages/ack_generator/test/integration/ack_infer_contract_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_contract_test.dart @@ -86,8 +86,8 @@ final userSchema = Ack.object({ contains("value['nickname'] as String?"), contains("value['middleName'] as String?"), contains("value['role'] as String"), - contains("'nickname': ?nickname"), - contains("'middleName': middleName"), + contains("'nickname': ?this.nickname"), + contains("'middleName': this.middleName"), isNot(contains(r'_$UserFromJson')), isNot(contains(r'_$UserToJson')), isNot(contains('_ackFromRuntimeName')), diff --git a/packages/ack_generator/test/integration/ack_infer_data_class_test.dart b/packages/ack_generator/test/integration/ack_infer_data_class_test.dart index c5743b29..25293ef5 100644 --- a/packages/ack_generator/test/integration/ack_infer_data_class_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_data_class_test.dart @@ -244,7 +244,7 @@ final userSchema = Ack.object({ '/// Creates a copy of this model with selected fields replaced.', ), contains('User call({'), - contains('deepEquals(name, other.name)'), + contains('deepEquals(this.name, other.name)'), contains('deepHashCode(tags)'), contains(r"toString() => 'User(name: ${name}, tags: ${tags})'"), isNot(contains('class UserType')), diff --git a/packages/ack_generator/test/integration/ack_infer_graph_test.dart b/packages/ack_generator/test/integration/ack_infer_graph_test.dart index 6c98d595..0a02c259 100644 --- a/packages/ack_generator/test/integration/ack_infer_graph_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_graph_test.dart @@ -397,7 +397,7 @@ class Money { ''' $_head @Schemable( - caseStyle: AckCaseStyle.snake, + caseStyle: AckCaseStyle.none, description: 'A user.', schemaName: 'UserWire', ) @@ -412,6 +412,29 @@ final userSchema = Ack.object({'firstName': Ack.string()}); ); }); + test('rejects non-ASCII letters in schema-first wire names', () async { + for (final (key, declaration) in [ + ('café', "final modelSchema = Ack.object({'café': Ack.string()});"), + ( + 'já_ok', + "final modelSchema = Ack.discriminated(discriminatorKey: 'já_ok', " + "schemas: {'choice': choiceSchema});", + ), + ]) { + await _expectFailure( + ''' +$_head +@Schemable() +final choiceSchema = Ack.object({'name': Ack.string()}); + +@Schemable() +$declaration +''', + [key, 'non-ASCII letters', 'class-first model with @AckKey'], + ); + } + }); + test('rejects dynamic additionalProperties expressions', () async { await _expectFailure( ''' @@ -1010,33 +1033,28 @@ final userSchema = Ack.object({ ); }); - test('rejects a leading-underscore JSON key', () async { + test('reports collisions between normalized JSON keys', () async { await _expectFailure( ''' $_head @Schemable() final userSchema = Ack.object({ - '_id': Ack.string(), + 'first_name': Ack.string(), + 'firstName': Ack.string(), }); ''', - ['userSchema._id', "cannot start with '_'"], + ['first_name', 'firstName', 'both map to the Dart field'], ); }); - test('rejects a leading-underscore discriminator key', () async { + test('reports reserved names after field-name conversion', () async { await _expectFailure( ''' $_head @Schemable() -final catSchema = Ack.object({'lives': Ack.integer()}); - -@Schemable() -final petSchema = Ack.discriminated( - discriminatorKey: '_kind', - schemas: {'cat': catSchema}, -); +final userSchema = Ack.object({'_class': Ack.string()}); ''', - ['petSchema._kind', "cannot start with '_'"], + ['userSchema._class', 'reserved Dart word'], ); }); diff --git a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart index 76dcc49a..d94bc380 100644 --- a/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/ack_infer_runtime_build_test.dart @@ -245,6 +245,164 @@ final keywordFieldsSchema = Ack.object({ 'yield': Ack.string(), }); +@Schemable() +final class RefinedWindow with _$RefinedWindowAck { + const RefinedWindow({required this.start, required this.end}); + final int start; + final int end; + static final schema = RefinedWindowSchema.schema.refine( + (window) => window.start <= window.end, + message: 'start must be before end', + ); +} + +@Schemable() +final class RefinedBooking with _$RefinedBookingAck { + const RefinedBooking({required this.window}); + final RefinedWindow window; +} + +@Schemable(discriminatorKey: 'kind', caseStyle: AckCaseStyle.snake) +sealed class StyleAnimal with _$StyleAnimalAck { + const StyleAnimal(); +} + +@Schemable(discriminatorValue: 'cat') +final class StyleCat extends StyleAnimal with _$StyleCatAck { + const StyleCat({required this.livesLeft}); + final int livesLeft; +} + +final class StyleDog extends StyleAnimal with _$StyleDogAck { + const StyleDog({required this.furColor}); + final String furColor; +} + +@Schemable(discriminatorValue: 'bird', caseStyle: AckCaseStyle.none) +final class StyleBird extends StyleAnimal with _$StyleBirdAck { + const StyleBird({required this.wingCount}); + final int wingCount; +} + +@Schemable(discriminatorValue: 'fish', caseStyle: AckCaseStyle.pascal) +final class StyleFish extends StyleAnimal with _$StyleFishAck { + const StyleFish({required this.finCount}); + final int finCount; +} + +@Schemable() +final class StaticDefaults with _$StaticDefaultsAck { + const StaticDefaults({ + this.count = defaultCount, + @IsOptional() this.retries = defaultCount + 1, + this.limit = StaticDefaults.defaultCount, + }); + + static const defaultCount = 20; + final int count; + final int retries; + final int limit; +} + +const value = 20; +const declared = 21; +const $ackValue = 22; + +@Schemable(unknownProperties: AckUnknownPropertyPolicy.capture) +final class UnshadowedDefaults with _$UnshadowedDefaultsAck { + const UnshadowedDefaults({ + this.count = value, + this.retries = declared, + this.limit = $ackValue, + this.additionalProperties = const {}, + }); + + final int count; + final int retries; + final int limit; + final Map additionalProperties; +} + +@Schemable(discriminatorKey: r'$type') +sealed class SpecialPet with _$SpecialPetAck { + const SpecialPet(); +} + +@Schemable(discriminatorValue: 'cat') +final class SpecialCat extends SpecialPet with _$SpecialCatAck { + const SpecialCat({required this.name}); + final String name; +} + +@Schemable() +final specialWireBranchSchema = Ack.object({ + r'$type': Ack.literal('a'), + 'id': Ack.string(), +}); + +@Schemable() +final specialWireChoiceSchema = Ack.discriminated( + discriminatorKey: r'$type', + schemas: {'a': specialWireBranchSchema}, +); + +@Schemable(discriminatorKey: 'type', caseStyle: AckCaseStyle.pascal) +sealed class StoredAnimal with _$StoredAnimalAck { + const StoredAnimal(); +} + +@Schemable(discriminatorValue: 'cat') +final class StoredCat extends StoredAnimal with _$StoredCatAck { + const StoredCat(); + final String type = 'cat'; +} + +@Schemable(discriminatorKey: '@type') +sealed class AliasAnimal with _$AliasAnimalAck { + const AliasAnimal(); +} + +@Schemable(discriminatorValue: 'cat') +final class AliasCat extends AliasAnimal with _$AliasCatAck { + const AliasCat(); + @AckKey('@type') + final String kind = 'cat'; +} + +@Schemable() +final typenameBranchSchema = Ack.object({'id': Ack.string()}); +@Schemable() +final typenameChoiceSchema = Ack.discriminated( + discriminatorKey: '__typename', + schemas: {'Branch': typenameBranchSchema}, +); + +@Schemable() +final class UniqueTags with _$UniqueTagsAck { + const UniqueTags({required this.tags}); + final Set tags; +} + +@Schemable() +final wireNamesSchema = Ack.object({ + 'first_name': Ack.string(), + 'user-id': Ack.integer(), + '_nickname': Ack.string(), +}).passthrough(); + +@Schemable() +final scopedNamesSchema = Ack.object({ + 'other': Ack.string(), + 'declared': Ack.string(), + 'value': Ack.string(), + 'entry': Ack.string(), + 'model': Ack.string(), + 'self': Ack.string(), + 'item': Ack.string(), + 'fieldValue': Ack.string(), + 'key': Ack.string(), +}).passthrough(); + @Schemable() final dollarNamesSchema = Ack.object({ r'$id': Ack.string(), @@ -488,9 +646,114 @@ void main() { expect(KeywordFields.parse({...json}..remove('required')).required, isFalse); }); - test('toString keeps dollar signs in field names literal', () { - final names = DollarNames.parse({r'$id': 'a', r'cost$usd': 2}); - expect(names.toString(), r'DollarNames($id: a, cost$usd: 2)'); + test('class-owned refinements apply at every generated boundary', () { + const window = RefinedWindow(start: 2, end: 1); + const json = {'start': 2, 'end': 1}; + expect(RefinedWindowSchema.schema.safeEncode(window).isOk, isTrue); + expect(RefinedWindow.schema.safeEncode(window).isFail, isTrue); + expect(window.toJson, throwsA(isA())); + expect(window.safeToJson().isFail, isTrue); + expect(RefinedWindowSchema.safeEncode(window).isFail, isTrue); + expect(RefinedWindowSchema.safeParse(json).isFail, isTrue); + expect(RefinedBookingSchema.safeParse({'window': json}).isFail, isTrue); + }); + + test('union branches inherit the base style and honor explicit overrides', () { + expect(const StyleCat(livesLeft: 9).toJson(), {'kind': 'cat', 'lives_left': 9}); + expect( + const StyleDog(furColor: 'black').toJson(), + {'kind': 'StyleDog', 'fur_color': 'black'}, + ); + expect(const StyleBird(wingCount: 2).toJson(), {'kind': 'bird', 'wingCount': 2}); + expect(const StyleFish(finCount: 2).toJson(), {'kind': 'fish', 'FinCount': 2}); + }); + + test('constructor defaults can use unqualified class statics', () { + final model = StaticDefaultsSchema.parse({}); + expect(model.count, 20); + expect(model.retries, 21); + expect(model.limit, 20); + expect(model.toJson(), {'count': 20, 'retries': 21, 'limit': 20}); + }); + + test('generated runtime locals do not capture constructor defaults', () { + final model = UnshadowedDefaultsSchema.parse({'extra': true}); + expect(model.additionalProperties, {'extra': true}); + expect(model.toJson(), { + 'extra': true, + 'count': 20, + 'retries': 21, + 'limit': 22, + }); + }); + + test('discriminator keys can contain literal dollar signs', () { + const pet = {r'$type': 'cat', 'name': 'Milo'}; + expect(SpecialPetSchema.parse(pet).toJson(), pet); + const wire = {r'$type': 'a', 'id': 'a1'}; + expect(SpecialWireChoice.parse(wire).toJson(), wire); + }); + + test('stored and nonidentifier discriminators use their wire key', () { + expect(const StoredCat().toJson(), {'type': 'cat'}); + expect(const AliasCat().toJson(), {'@type': 'cat'}); + const json = {'__typename': 'Branch', 'id': 'x'}; + final model = TypenameChoice.parse(json); + expect(model.typename, 'Branch'); + expect(model.toJson(), json); + }); + + test('an unconstrained Set rejects duplicate wire values', () { + expect(UniqueTagsSchema.safeParse({'tags': ['x', 'x']}).isFail, isTrue); + expect(UniqueTagsSchema.safeParse({'tags': ['x', 'y']}).isOk, isTrue); + final properties = + UniqueTagsSchema.toJsonSchema()['properties'] as Map; + expect(properties['tags'], containsPair('uniqueItems', true)); + }); + + test('passthrough excludes declared wire keys from additional properties', () { + const json = { + 'first_name': 'Ada', + 'user-id': 7, + '_nickname': 'A', + 'firstName': 'an extra key', + }; + final model = WireNames.parse(json); + expect(model.firstName, 'Ada'); + expect(model.userId, 7); + expect(model.nickname, 'A'); + expect(model.additionalProperties, {'firstName': 'an extra key'}); + expect(model.toJson(), json); + }); + + test('generated local and parameter names can also be model fields', () { + const fields = ['other', 'declared', 'value', 'entry', 'model', 'self', + 'item', 'fieldValue', 'key']; + final json = { + for (final field in fields) field: field, + 'extra': 'captured', + }; + final first = ScopedNames.parse(json); + final second = ScopedNames.parse(json); + expect(first, second); + expect(first.hashCode, second.hashCode); + expect(first.toJson(), json); + expect(first.copyWith().toJson(), json); + expect(first.copyWith(declared: 'updated').toJson(), { + ...json, 'declared': 'updated', + }); + for (final field in fields) { + expect(first.toString(), contains('$field: $field')); + } + }); + + test('dollar signs separate Dart words and round-trip on the wire', () { + const json = {r'$id': 'a', r'cost$usd': 2}; + final names = DollarNames.parse(json); + expect(names.id, 'a'); + expect(names.costUsd, 2); + expect(names.toString(), 'DollarNames(id: a, costUsd: 2)'); + expect(names.toJson(), json); }); test('constructor snapshots Object-valued option maps without validating them', () { @@ -1127,6 +1390,26 @@ Extras misuse(Extras extras) => extras.copyWith(nickname: const Object()); p.relative(file.path, from: temporary.path): file.readAsStringSync(), }; expect(rebuilt, generated); + + File(p.join(temporary.path, 'lib', 'missing_annotation.dart')) + .writeAsStringSync(''' +import 'package:ack/ack.dart'; + +part 'missing_annotation.g.dart'; + +final branchSchema = Ack.object({'name': Ack.string()}); + +@Schemable() +final unionSchema = Ack.discriminated( + discriminatorKey: 'kind', + schemas: {'branch': branchSchema}, +); +'''); + final rejected = await _run(temporary, ['run', 'build_runner', 'build']); + final diagnostics = '${rejected.stdout}\n${rejected.stderr}'; + expect(rejected.exitCode, isNot(0), reason: diagnostics); + expect(diagnostics, contains('unionSchema.branch')); + expect(diagnostics, contains('annotated with @Schemable()')); } finally { temporary.deleteSync(recursive: true); } diff --git a/packages/ack_generator/test/integration/class_first_getter_model_refs_test.dart b/packages/ack_generator/test/integration/class_first_getter_model_refs_test.dart index 8af019f6..0651cbcc 100644 --- a/packages/ack_generator/test/integration/class_first_getter_model_refs_test.dart +++ b/packages/ack_generator/test/integration/class_first_getter_model_refs_test.dart @@ -34,7 +34,7 @@ final class Holder with _$HolderAck { 'test_pkg|lib/models.g.dart': decodedMatches( allOf([ contains('final class Label'), - contains(r"Label.$ack.fromRuntime(value['label'] as String)"), + contains(r"Label.$ack.fromRuntime($ackValue['label'] as String)"), contains(r'Label.$ack.fromRuntime(item as String)'), ]), ), diff --git a/packages/ack_generator/test/integration/class_first_json_test.dart b/packages/ack_generator/test/integration/class_first_json_test.dart index 2a2d13d2..04f41e92 100644 --- a/packages/ack_generator/test/integration/class_first_json_test.dart +++ b/packages/ack_generator/test/integration/class_first_json_test.dart @@ -38,9 +38,9 @@ final class User with _\$UserAck { } ''', allOf([ - contains(r'User _$UserFromRuntime(Map value)'), - contains("firstName: value['first_name'] as String"), - contains("nickname: value['nickname'] as String?"), + contains(r'User _$UserFromRuntime(Map $ackValue)'), + contains("firstName: \$ackValue['first_name'] as String"), + contains("nickname: \$ackValue['nickname'] as String?"), contains(r'Map _$UserToRuntime(User model)'), contains("'first_name': model.firstName"), contains("'nickname': ?model.nickname"), @@ -69,8 +69,8 @@ final class Cat extends Pet with _\$CatAck { ''', allOf([ contains(r'Cat _$CatFromRuntime'), - contains("id: value['id'] as String"), - contains("lives: value['lives'] as int"), + contains("id: \$ackValue['id'] as String"), + contains("lives: \$ackValue['lives'] as int"), contains("'id': model.id"), contains("'lives': model.lives"), isNot(contains(r'Pet _$PetFromRuntime')), @@ -95,7 +95,7 @@ final class Cat extends Pet with _\$CatAck { } ''', allOf([ - contains("livesLeft: value['lives_left'] as int"), + contains("livesLeft: \$ackValue['lives_left'] as int"), contains("'lives_left': model.livesLeft"), ]), ); @@ -121,7 +121,7 @@ final class User with _\$UserAck { } ''', allOf([ - contains("firstName: value['$key'] as String"), + contains("firstName: \$ackValue['$key'] as String"), contains("'$key': model.firstName"), ]), ); diff --git a/packages/ack_generator/test/integration/class_first_runtime_build_test.dart b/packages/ack_generator/test/integration/class_first_runtime_build_test.dart index ead43537..8b00a902 100644 --- a/packages/ack_generator/test/integration/class_first_runtime_build_test.dart +++ b/packages/ack_generator/test/integration/class_first_runtime_build_test.dart @@ -473,6 +473,19 @@ final class DollarNames with _$DollarNamesAck { final int cost$usd; } +@Schemable() +final class ScopedFields with _$ScopedFieldsAck { + const ScopedFields({ + required this.other, + required this.value, + required this.model, + }); + + final String other; + final int value; + final bool model; +} + @Schemable() final class OptionalCollections with _$OptionalCollectionsAck { const OptionalCollections({this.headers, this.aliases, this.tags}); @@ -485,12 +498,14 @@ final class OptionalCollections with _$OptionalCollectionsAck { @Schemable(discriminatorKey: 'type') sealed class Pet with _$PetAck { const Pet({required this.id}); + static final schema = PetSchema.schema; final String id; } -@Schemable(discriminatorValue: 'cat') +@Schemable(discriminatorValue: 'cat', schemaName: 'PetCatSchema') final class Cat extends Pet with _$CatAck { const Cat({required super.id, required this.lives}); + static get schema => PetCatSchema.schema; final int lives; } @@ -516,6 +531,26 @@ final class BabyRabbit extends Rabbit with _$BabyRabbitAck { final String? note; } +@Schemable(discriminatorKey: 'kind') +sealed class NamedAnimal with _$NamedAnimalAck { + const NamedAnimal({this.name = defaultName}); + static const defaultName = 'animal'; + final String name; +} + +final class NamedDog extends NamedAnimal with _$NamedDogAck { + const NamedDog({super.name}); +} + +final class NamedPuppy extends NamedDog with _$NamedPuppyAck { + const NamedPuppy({super.name}); +} + +final class NamedCat extends NamedAnimal with _$NamedCatAck { + const NamedCat({super.name = defaultName}); + static const defaultName = 'cat'; +} + @Schemable() final class Parent with _$ParentAck { const Parent({required this.id}); @@ -1158,6 +1193,15 @@ void main() { expect(names.toString(), r'DollarNames($id: a, cost$usd: 2)'); }); + test('class-first fields named other, value, and model round-trip', () { + const json = {'other': 'text', 'value': 4, 'model': true}; + final fields = ScopedFieldsSchema.parse(json); + expect(fields, const ScopedFields(other: 'text', value: 4, model: true)); + expect(fields.toJson(), json); + expect(fields.copyWith(value: 7).toJson(), {...json, 'value': 7}); + expect(fields.toString(), 'ScopedFields(other: text, value: 4, model: true)'); + }); + test('optional collections round-trip through null-aware bridges', () { final empty = OptionalCollectionsSchema.parse({}); expect(empty.headers, isNull); @@ -1185,11 +1229,21 @@ void main() { expect(dog, isA()); expect(dog.toJson(), {'type': 'Dog', 'id': 'd1', 'breed': 'lab'}); expect((cat as Cat).copyWith(lives: 8).id, 'c1'); - final direct = CatSchema.parse({'id': 'c2', 'lives': 7}); + final direct = PetCatSchema.parse({'id': 'c2', 'lives': 7}); expect(direct.toJson(), {'type': 'cat', 'id': 'c2', 'lives': 7}); expect(PetSchema.safeParse({'id': 'c2', 'lives': 7}).isFail, isTrue); }); + test('super parameters use the default from their declaring constructor', () { + expect(NamedDogSchema.parse({}).name, 'animal'); + expect(NamedPuppySchema.parse({}).name, 'animal'); + expect(NamedCatSchema.parse({}).name, 'cat'); + expect(NamedAnimalSchema.parse({'kind': 'NamedPuppy'}).toJson(), { + 'kind': 'NamedPuppy', + 'name': 'animal', + }); + }); + test('explicit descriptions and tags describe class-first object schemas', () { const task = 'A task the person can complete.'; expect(TaskSchema.toJsonSchema()['description'], task); diff --git a/packages/ack_generator/test/integration/class_first_value_runtime_refs_test.dart b/packages/ack_generator/test/integration/class_first_value_runtime_refs_test.dart index a01a108b..4345468d 100644 --- a/packages/ack_generator/test/integration/class_first_value_runtime_refs_test.dart +++ b/packages/ack_generator/test/integration/class_first_value_runtime_refs_test.dart @@ -49,11 +49,11 @@ final class Holder with _$HolderAck { } ''', allOf([ - contains(r"Scalar.$ack.fromRuntime(value['scalar'] as int)"), + contains(r"Scalar.$ack.fromRuntime($ackValue['scalar'] as int)"), contains( - r"Strings.$ack.fromRuntime(value['strings'] as List)", + r"Strings.$ack.fromRuntime($ackValue['strings'] as List)", ), - contains(r"Encoded.$ack.fromRuntime(value['encoded'] as Token)"), + contains(r"Encoded.$ack.fromRuntime($ackValue['encoded'] as Token)"), ]), ); }, diff --git a/packages/ack_generator/test/integration/class_model_emitter_test.dart b/packages/ack_generator/test/integration/class_model_emitter_test.dart index 55dcb98b..d02d260b 100644 --- a/packages/ack_generator/test/integration/class_model_emitter_test.dart +++ b/packages/ack_generator/test/integration/class_model_emitter_test.dart @@ -41,6 +41,76 @@ import 'package:ack/annotations.dart'; '''; void main() { + test('qualifies inherited defaults through the consumer imports', () async { + await _build( + { + 'base.dart': r''' +import 'values.dart' as source; + +const kRole = 'original'; +class Base { + const Base({this.role = kRole, this.title = source.kTitle, this.ids = const []}); + final String role; + final String title; + final List ids; +} +''', + 'values.dart': "const kTitle = 'title';", + 'model.dart': r''' +import 'package:ack/ack.dart'; +import 'base.dart' as origin show Base, kRole; +import 'values.dart' as values; +part 'model.g.dart'; + +const kRole = 'wrong'; + +@Schemable() +final class Model extends origin.Base with _$ModelAck { + const Model({super.role, super.title, super.ids}); +} +''', + }, + outputs: { + 'test_pkg|lib/model.g.dart': decodedMatches( + allOf([ + _containsCode('.withDefault(origin.kRole)'), + _containsCode('.withDefault(values.kTitle)'), + _containsCode('.withDefault(const [])'), + ]), + ), + }, + ); + }); + + test( + 'braces qualified class statics in constructor default interpolation', + () async { + await _build( + { + 'tag.dart': r''' +import 'package:ack/ack.dart'; +part 'tag.g.dart'; + +@Schemable() +final class Tag with _$TagAck { + static const prefix = 'p'; + const Tag({this.label = '$prefix-x'}); + final String label; +} +''', + }, + outputs: { + 'test_pkg|lib/tag.g.dart': decodedMatches( + allOf([ + _containsCode(r""".withDefault('${Tag.prefix}-x')"""), + _containsCode(r"""?? '${Tag.prefix}-x'"""), + ]), + ), + }, + ); + }, + ); + test( 'prefixed constraint annotations sit beside same-named app types', () async { @@ -104,7 +174,7 @@ final class Grid with _\$GridAck { 'test_pkg|lib/grid.g.dart': decodedMatches( allOf( _containsCode( - 'Ack.list(Ack.list(Ack.integer()).codec>(' + 'Ack.list(Ack.list(Ack.integer()).unique().codec>(' 'decode: (list) => list.toSet(), ' 'encode: (set) => set.toList(growable: false),' ')).minItems(2).unique().codec>>(', @@ -437,7 +507,7 @@ final class Envelope with _\$EnvelopeAck { contains("'kind': Ack.any()"), contains("'payload': Ack.any().optional().nullable()"), contains("'items': Ack.list(Ack.any())"), - contains("'tags': Ack.list(Ack.any()).codec>"), + contains("'tags': Ack.list(Ack.any()).unique().codec>"), contains("'values': Ack.map(Ack.any())"), contains("'metadata': Ack.map(Ack.any().nullable())"), contains("'labels': Ack.map(Ack.string().nullable())"), @@ -696,7 +766,7 @@ const Type otherAddressType = b.Address; 'test_pkg|lib/order.g.dart': decodedMatches( allOf([ contains("'shipping': a.AddressSchema.schema"), - contains("shipping: value['shipping'] as a.Address"), + contains("shipping: \$ackValue['shipping'] as a.Address"), isNot(contains('b.AddressSchema')), ]), ), @@ -993,9 +1063,9 @@ final class UserPatch with _$UserPatchAck { _containsCode( "'tags': Ack.list(Ack.string()).optional().nullable()", ), - _containsCode("value.containsKey('nickname')"), + _containsCode("\$ackValue.containsKey('nickname')"), _containsCode( - "JsonMaybe.value(value['nickname'] as String?)", + "JsonMaybe.value(\$ackValue['nickname'] as String?)", ), _containsCode('const JsonMaybe.absent()'), _containsCode('const JsonMaybe.absent()'), diff --git a/packages/ack_generator/test/integration/class_model_graph_test.dart b/packages/ack_generator/test/integration/class_model_graph_test.dart index 54cfe8ea..dfe05696 100644 --- a/packages/ack_generator/test/integration/class_model_graph_test.dart +++ b/packages/ack_generator/test/integration/class_model_graph_test.dart @@ -51,6 +51,112 @@ part 'model.g.dart'; '''; void main() { + test('rejects explicit caseStyle none on a library annotation', () async { + await _expectFailure( + r''' +AckSchema textSchema() => Ack.string(); + +@Schemable() +final class Model with _$ModelAck { + const Model({required this.id}); + final int id; +} +''', + ['@Schemable on a library directive only supports schemas', 'caseStyle'], + head: ''' +@Schemable(caseStyle: AckCaseStyle.none, schemas: [textSchema]) +library; + +import 'package:ack/ack.dart'; +part 'model.g.dart'; +''', + ); + }); + + test('reports a hidden constant used by a super-parameter default', () async { + await _expectFailure( + r''' +const kRole = 'wrong'; + +@Schemable() +final class Model extends Base with _$ModelAck { + const Model({super.role}); +} +''', + ['Model.role', 'kRole', 'explicit default'], + head: ''' +import 'package:ack/ack.dart'; +import 'base.dart' show Base; +part 'model.g.dart'; +''', + extraSources: { + 'base.dart': ''' +const kRole = 'right'; + +class Base { + const Base({this.role = kRole}); + final String role; +} +''', + }, + ); + }); + + test('rejects class-owned schemas with an incompatible shape', () async { + for (final declaration in [ + 'static final AckSchema schema = BoxSchema.schema;', + 'static AckSchema, Box>? get schema => BoxSchema.schema;', + ]) { + await _expectFailure( + ''' +@Schemable() +final class Box with _\$BoxAck { + const Box({required this.id}); + final int id; + $declaration +} +''', + ['Box.schema', 'non-nullable', 'AckSchema, Box>'], + ); + } + }); + + for (final (owner, baseSchema, branchSchema) in [ + ( + 'Shape', + 'static final schema = ShapeSchema.schema.refine((_) => false);', + '', + ), + ( + 'Range', + '', + 'static final schema = RangeSchema.schema.refine((r) => r.lo <= r.hi);', + ), + ]) { + test('rejects a custom schema on union member $owner', () async { + await _expectFailure( + ''' +@Schemable(discriminatorKey: 'kind') +sealed class Shape with _\$ShapeAck { + const Shape(); + $baseSchema +} + +final class Range extends Shape with _\$RangeAck { + const Range({required this.lo, required this.hi}); + final int lo; + final int hi; + $branchSchema +} +''', + [ + '$owner.schema must directly expose ${owner}Schema.schema', + 'Validate at the union level or use a non-union model.', + ], + ); + }); + } + test('rejects a JsonConverter on a field or class', () async { const converter = ''' final class UriText implements JsonConverter { @@ -1240,6 +1346,26 @@ final class Address with _\$AddressAck { ); }); + test('reports invalid rule arguments on the annotated field', () async { + for (final (type, annotation, diagnostic) in [ + ('int', '@HasMin(0.5)', 'Use an integer argument on an int field.'), + ('String', '@HasMinLength(-1)', 'The length must be nonnegative.'), + ('List', '@HasMaxItems(-1)', 'The count must be nonnegative.'), + ('String', "@HasMatch('(')", 'invalid @HasMatch regular expression'), + ]) { + await _expectFailure( + ''' +@Schemable() +final class User with _\$UserAck { + const User({$annotation required this.value}); + final $type value; +} +''', + ['User.value', diagnostic], + ); + } + }); + test( 'rejects invalid rule annotations on mismatched field types or values', () async { diff --git a/packages/ack_generator/test/integration/generated_names_contract_test.dart b/packages/ack_generator/test/integration/generated_names_contract_test.dart index aa80fa4e..c5090a59 100644 --- a/packages/ack_generator/test/integration/generated_names_contract_test.dart +++ b/packages/ack_generator/test/integration/generated_names_contract_test.dart @@ -23,12 +23,75 @@ Future _expectFailure(String source, List messages) async { } } +Future _expectOutput(String source, List snippets) async { + await testBuilder( + ackModelBuilder(BuilderOptions.empty), + {'test_pkg|lib/models.dart': source}, + readerWriter: await createTestReaderWriter(), + outputs: { + 'test_pkg|lib/models.g.dart': decodedMatches( + allOf(snippets.map(contains).toList()), + ), + }, + ); +} + const _head = ''' import 'package:ack/ack.dart'; part 'models.g.dart'; '''; void main() { + for (final name in [ + 'override', + 'identical', + 'bool', + 'int', + 'double', + 'num', + 'deepEquals', + 'deepHashCode', + 'deepUnmodifiableCopy', + 'deepUnmodifiableJsonMap', + ]) { + test('rejects keys that shadow the generated reference $name', () async { + await _expectFailure( + ''' +$_head +@Schemable() +final userSchema = Ack.object({'$name': Ack.integer()}); +''', + ['userSchema.$name', 'shadows', '"$name"'], + ); + }); + } + + test('rejects a field that shadows the adapter schema', () async { + await _expectFailure( + ''' +$_head +@Schemable() +final userSchema = Ack.object({'userSchema': Ack.string()}); +''', + ['userSchema.userSchema', 'shadows', '"userSchema"'], + ); + }); + + test('rejects a discriminator that shadows a generated reference', () async { + await _expectFailure( + ''' +$_head +@Schemable() +final catSchema = Ack.object({}); +@Schemable() +final petSchema = Ack.discriminated( + discriminatorKey: 'identical', schemas: {'cat': catSchema}, +); +''', + ['petSchema.identical', 'shadows', '"identical"'], + ); + }); + for (final name in [r'$TitleCopyWith', r'_$TitleCopyWith']) { test('rejects value-model helper collision $name', () async { await _expectFailure( @@ -44,20 +107,23 @@ final class $name {} } for (final model in ['User', 'Renamed']) { - test('rejects field matching generated class $model', () async { - await _expectFailure( + test('normalizes wire keys spelled like generated class $model', () async { + await _expectOutput( ''' $_head @Schemable(name: '$model') final userSchema = Ack.object({'$model': Ack.string()}); ''', - ['userSchema.$model', 'class name'], + [ + 'final String ${model.toLowerCase()};', + "'$model': this.${model.toLowerCase()}", + ], ); }); } - test('checks inherited fields against an alias model name', () async { - await _expectFailure( + test('keeps a normalized field when its schema is aliased', () async { + await _expectOutput( ''' $_head @Schemable() @@ -65,7 +131,7 @@ final originalSchema = Ack.object({'Alias': Ack.string()}); @Schemable() final aliasSchema = originalSchema; ''', - ['aliasSchema.Alias', 'class name'], + ['final class Alias', 'final String alias;', "'Alias': this.alias"], ); }); @@ -124,9 +190,11 @@ final aliasSchema = baseSchema$overrides; } for (final discriminator in ['Pet', 'Cat']) { - test('rejects discriminator matching class $discriminator', () async { - await _expectFailure( - ''' + test( + 'normalizes wire discriminator spelled like class $discriminator', + () async { + await _expectOutput( + ''' $_head @Schemable() final catSchema = Ack.object({}); @@ -135,9 +203,13 @@ final petSchema = Ack.discriminated( discriminatorKey: '$discriminator', schemas: {'cat': catSchema}, ); ''', - [discriminator, 'class name'], - ); - }); + [ + 'String get ${discriminator.toLowerCase()}', + "value['$discriminator']", + ], + ); + }, + ); } test( diff --git a/packages/ack_generator/test/integration/inference_library_test.dart b/packages/ack_generator/test/integration/inference_library_test.dart index ff27b8bb..bf7db073 100644 --- a/packages/ack_generator/test/integration/inference_library_test.dart +++ b/packages/ack_generator/test/integration/inference_library_test.dart @@ -112,7 +112,7 @@ void widget({@HasMinItems(2) required Set tags}) {} readerWriter: readerWriter, outputs: { 'test_pkg|lib/widget.probe': decodedMatches( - 'Ack.list(Ack.string()).minItems(2).unique().codec>(' + 'Ack.list(Ack.string()).unique().minItems(2).codec>(' 'decode: (list) => list.toSet(), ' 'encode: (set) => set.toList(growable: false),)', ), @@ -135,10 +135,10 @@ void widget({@HasMaxItems(3) required Set> cells}) {} readerWriter: readerWriter, outputs: { 'test_pkg|lib/widget.probe': decodedMatches( - 'Ack.list(Ack.list(Ack.string()).codec>(' + 'Ack.list(Ack.list(Ack.string()).unique().codec>(' 'decode: (list) => list.toSet(), ' 'encode: (set) => set.toList(growable: false),))' - '.maxItems(3).unique().codec>>(' + '.unique().maxItems(3).codec>>(' 'decode: (list) => list.toSet(), ' 'encode: (set) => set.toList(growable: false),)', ), diff --git a/packages/ack_generator/test/integration/library_schema_test.dart b/packages/ack_generator/test/integration/library_schema_test.dart index a253b0d0..65ca1fbf 100644 --- a/packages/ack_generator/test/integration/library_schema_test.dart +++ b/packages/ack_generator/test/integration/library_schema_test.dart @@ -49,7 +49,9 @@ final class Theme with _$ThemeAck { allOf([ containsCode('colorSchema'), containsCode("'palette': Ack.list(colorSchema),"), - containsCode("'swatches': Ack.list(colorSchema).codec>("), + containsCode( + "'swatches': Ack.list(colorSchema).unique().codec>(", + ), containsCode("'namedColors': Ack.map(colorSchema),"), containsCode('Box.schema(colorSchema)'), containsCode('centsSchema'), diff --git a/packages/ack_generator/test/integration/type_owned_schema_build_test.dart b/packages/ack_generator/test/integration/type_owned_schema_build_test.dart index c3ddf98d..917941c9 100644 --- a/packages/ack_generator/test/integration/type_owned_schema_build_test.dart +++ b/packages/ack_generator/test/integration/type_owned_schema_build_test.dart @@ -398,7 +398,7 @@ void main() { .readAsStringSync(); expect(generated, contains('Command.schema()')); expect(generated, contains('Trigger.schema()')); - expect(generated, contains('Box.schema(HabitSchema.schema)')); + expect(generated, contains('Box.schema(Habit.schema)')); expect(generated, contains('Ack.map(Slot.schema)')); _expectSuccess( await _run(temporary, ['analyze', '--fatal-infos']), diff --git a/packages/ack_generator/test/integration/type_owned_schema_test.dart b/packages/ack_generator/test/integration/type_owned_schema_test.dart index 2abd419d..4fb87880 100644 --- a/packages/ack_generator/test/integration/type_owned_schema_test.dart +++ b/packages/ack_generator/test/integration/type_owned_schema_test.dart @@ -48,7 +48,7 @@ final class Section with _$SectionAck { allOf( containsCode("'children': Ack.list(Slot.schema),"), containsCode( - "'unique': Ack.list(WidgetId.schema).codec>(", + "'unique': Ack.list(WidgetId.schema).unique().codec>(", ), containsCode("'byName': Ack.map(Slot.schema),"), ), @@ -340,8 +340,7 @@ final class Color { }); test('a Schemable class may expose its backing schema or facade as a static schema', () async { - await expectOutput( - r''' + await expectOutput(r''' @Schemable() final class Habit with _$HabitAck { const Habit({required this.name}); @@ -357,12 +356,7 @@ final class Routine with _$RoutineAck { final List habits; } -''', - allOf( - containsCode("Ack.object({'habits': Ack.list(HabitSchema.schema)})"), - isNot(contains('Habit.schema')), - ), - ); +''', containsCode("Ack.object({'habits': Ack.list(Habit.schema)})")); }); test('a Schemable class rejects a static schema of another type', () async { @@ -381,8 +375,9 @@ final class Habit with _$HabitAck { errors, contains( contains( - 'Habit.schema must be an AckSchema, Habit>; ' - 'it produces String.', + 'Habit.schema must be a non-nullable ' + 'AckSchema, Habit>. ' + 'Its declared type is StringSchema.', ), ), ); diff --git a/packages/ack_generator/test/json_schema/json_schema_library_test.dart b/packages/ack_generator/test/json_schema/json_schema_library_test.dart index 26dc358e..c1fd3e57 100644 --- a/packages/ack_generator/test/json_schema/json_schema_library_test.dart +++ b/packages/ack_generator/test/json_schema/json_schema_library_test.dart @@ -59,6 +59,42 @@ Matcher _diagnostic(String pointer, String message) => .having((d) => d.message, 'message', contains(message)); void main() { + test( + 'uses validated value models when Dart property names collide or shadow', + () { + for (final (keys, diagnostic) in [ + (['@id', 'id'], 'both map to the Dart field "id"'), + (['user_id', 'userId'], 'both map to the Dart field "userId"'), + (['ack'], 'shadows the generated reference "ack"'), + (['modelSchema'], 'shadows the generated reference "modelSchema"'), + (['café'], 'non-ASCII letters'), + ]) { + final result = _generate( + _model({ + for (final key in keys) key: {'type': 'string'}, + }), + ); + expect(result.source, contains('Ack.fromJsonSchema'), reason: '$keys'); + expect(result.source, contains(diagnostic), reason: '$keys'); + expect( + result.source, + isNot(contains('@ack.Schemable')), + reason: '$keys', + ); + } + }, + ); + + test('allows a property whose wire spelling matches its model name', () { + final result = _generate( + _model({ + 'Model': {'type': 'string'}, + }), + ); + expect(result.source, contains("@ack.Schemable(name: 'Model')")); + expect(result.source, contains("'Model': ack.Ack.string().optional()")); + }); + group('maps', () { final rows = { 'a string': ({'type': 'string'}, "'f':ack.Ack.string().optional()"), @@ -212,6 +248,27 @@ void main() { ); }); + test('snake_case inline object keys produce UpperCamelCase models', () { + final source = _squash( + _generate( + _model({ + 'shipping_address': { + 'type': 'object', + 'properties': { + 'city': {'type': 'string'}, + }, + 'additionalProperties': false, + }, + }), + ).source, + ); + expect(source, contains("@ack.Schemable(name:'ModelShippingAddress')")); + expect( + source, + contains("'shipping_address':modelShippingAddressSchema.optional()"), + ); + }); + test(r'a $ref as the referenced model', () { final source = _squash( _generate({ diff --git a/packages/ack_generator/test/src/schema_first_names_test.dart b/packages/ack_generator/test/src/schema_first_names_test.dart index 86e5d56e..6a8ec165 100644 --- a/packages/ack_generator/test/src/schema_first_names_test.dart +++ b/packages/ack_generator/test/src/schema_first_names_test.dart @@ -4,6 +4,71 @@ import 'package:analyzer/dart/ast/token.dart'; import 'package:test/test.dart'; void main() { + const names = [ + ('ID', 'id', 'Id'), + ('UserID', 'userId', 'UserId'), + ('userID', 'userId', 'UserId'), + ('user_id', 'userId', 'UserId'), + ('HTTPServer', 'httpServer', 'HttpServer'), + ('URLIsValid', 'urlIsValid', 'UrlIsValid'), + ('URLs', 'urls', 'Urls'), + ('URLsParser', 'urlsParser', 'UrlsParser'), + ('api_URL', 'apiUrl', 'ApiUrl'), + ('ipv4Address', 'ipv4Address', 'Ipv4Address'), + ('sha256Hash', 'sha256Hash', 'Sha256Hash'), + ('OAuth2Token', 'oAuth2Token', 'OAuth2Token'), + ('address_2', 'address2', 'Address2'), + ('user.id', 'userId', 'UserId'), + ('x_1_2', 'x12', 'X12'), + ('x_12', 'x12', 'X12'), + ('Name', 'name', 'Name'), + ('name', 'name', 'Name'), + ('_id', 'id', 'Id'), + ('id', 'id', 'Id'), + (r'$id', 'id', 'Id'), + (r'cost$usd', 'costUsd', 'CostUsd'), + ('@type', 'type', 'Type'), + ('@HTTPStatus', 'httpStatus', 'HttpStatus'), + ('1st_place', '1stPlace', '1stPlace'), + ('123', '123', '123'), + ('Default', 'default', 'Default'), + ('_class', 'class', 'Class'), + ]; + for (final (key, field, type) in names) { + test('uses one naming rule for wire key "$key"', () { + expect(ackSchemaFirstDartFieldName(key), field); + expect(ackSchemaFirstDiscriminatorName(key), field); + expect(ackSchemaFirstTypeNameSegment(key), type); + }); + } + + test('rejects non-ASCII letters before splitting words', () { + for (final key in ['café', 'já_ok', 'naïve_name', '東京']) { + expect( + ackSchemaFirstWireKeyProblem(key), + allOf(contains('non-ASCII letters'), contains('@AckKey')), + reason: key, + ); + } + expect(ackSchemaFirstWireKeyProblem('😀_hello'), isNull); + }); + + test( + 'rejects empty, digit-led, and reserved field names after conversion', + () { + for (final key in ['123', '1st_place', 'Default', '_class']) { + expect( + ackSchemaFirstFieldNameProblem( + ackSchemaFirstDartFieldName(key), + capturesExtras: false, + ), + isNotNull, + reason: key, + ); + } + }, + ); + test('member checks distinguish keywords from generated type collisions', () { for (final entry in Keyword.keywords.entries) { if (entry.value.isReservedWord) continue; @@ -34,7 +99,7 @@ void main() { if (!entry.value.isReservedWord) continue; expect( ackSchemaFirstFieldNameProblem(entry.key, capturesExtras: false), - 'cannot be represented as a Dart field name.', + startsWith('maps to the reserved Dart word'), reason: entry.key, ); } diff --git a/plugins/ack/skills/build-data-classes-with-ack/SKILL.md b/plugins/ack/skills/build-data-classes-with-ack/SKILL.md index f4fb04d4..14dae26a 100644 --- a/plugins/ack/skills/build-data-classes-with-ack/SKILL.md +++ b/plugins/ack/skills/build-data-classes-with-ack/SKILL.md @@ -58,6 +58,7 @@ The rules that make it build: - **Unknown keys** are rejected by default. Use `@Schemable(unknownProperties: AckUnknownPropertyPolicy.capture)` with a `Map additionalProperties` field when you need to round-trip them. - **Inferred field types:** `String`, `bool`, `int`, `double`, `num`, `DateTime` (UTC ISO string), `Uri`, `Duration` (ms), enums, `List`, `Set`, `Map`, `Object`/`Object?` (any JSON), nested `@Schemable` classes, `JsonMaybe`. Any other type needs a schema: read [references/custom-types.md](references/custom-types.md). - **Unions:** `@Schemable(discriminatorKey: 'type') sealed class` with `final class` branches in the same library (`@Schemable(discriminatorValue: 'x')` fixes a wire value; otherwise the class name is used). +- **Union schemas:** A static `schema` on the base or a branch must directly expose its generated facade's `schema`. Apply refinements to the union schema where you use it, or use a non-union model. ## 3. Generate @@ -65,9 +66,8 @@ Run `dart run build_runner build`. For a class-first model the build writes `.value(null)` (explicit `null` on the wire). - `copyWith(notes: null)` clears a nullable field; leaving the argument out keeps it. - Compose: `Ack.list(Invoice.schema)`, or a field typed `Invoice` inside another `@Schemable` class. @@ -81,6 +81,6 @@ Run `dart run build_runner build`. For a class-first model the build writes `