diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cab2ccb1..a2fc9a74 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,6 +65,7 @@ jobs: # JSON Schema suites run separately below. test/json_schema_*) continue ;; # These suites read local files or run a Dart subprocess. + test/naming_conventions_test.dart|\ test/runtime_dependencies_test.dart|\ test/schemas/local_date_timezone_test.dart|\ test/schemas/object_presence_characterization_test.dart|\ diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index af678481..6c837429 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -43,7 +43,7 @@ explicit null triggers the default. Generated field wrappers continue to use the field declaration's presence policy. Refines: [field presence and unknown keys](#field-presence-and-unknown-keys). -Contract: [default values](docs/core-concepts/configuration.mdx#default-values). +Contract: [default values](docs/core-concepts/schemas.mdx#defaults). ## Stable rule annotations @@ -73,7 +73,7 @@ namespace remains as deprecated redirecting constructors in 2.0.0-beta.3 and is removed before Ack 2.0.0. Replaces: [unified annotations](#unified-annotations-superseded). -Migration: [validation annotation table](docs/getting-started/migration-guide.mdx#validation-annotations). +Migration: [validation annotation table](docs/getting-started/migration-guide.mdx#removed-1x-and-beta-annotations). ## Single-part generation @@ -123,6 +123,21 @@ objects become schema failures, so `safeParse` is not a blanket exception barrie Contracts: [codecs](docs/core-concepts/codecs.mdx) and [error handling](docs/core-concepts/error-handling.mdx). +## Naming of identifiers and fields + +Date: 2026-12-02. Status: current. History: [#272](https://github.com/btwld/ack/pull/272). + +Identifier values use lowercase snake_case: built-in constraint keys such as +`list_min_items` and diagnostic codes such as `unsupported_keyword`. Users log, +search, and compare these values across languages, as with other libraries' +error codes. Field names follow their host: Dart members and generated fields +use lowerCamelCase, and serialized error maps use camelCase fields such as +`constraintKey`, like the JSON Schema keywords Ack exports. Ack never renames +wire keys; generated models map them to Dart names. A new snake_case key costs +nothing, but renaming a key breaks users who match on it. + +Contract: [naming test](packages/ack/test/naming_conventions_test.dart). + ## Detached validating wire views Date: 2026-10-27. Status: current. History: [#246](https://github.com/btwld/ack/pull/246). diff --git a/README.md b/README.md index 531a38aa..7cb345e7 100644 --- a/README.md +++ b/README.md @@ -9,22 +9,6 @@ Ack validates data in Dart and Flutter. This branch documents **2.0.0-beta.3**; see the [migration guide](docs/getting-started/migration-guide.mdx) for 1.x changes. -## Core concepts - -- Schemas define accepted boundary data and the Dart values it becomes. -- Parsing validates input; `safeParse` returns a result. Codecs also encode - runtime values back to the boundary. -- Presence and null differ: `optional` permits omission, `nullable` permits - null, and `JsonMaybe` preserves both states. -- Generation is optional: `@Schemable` turns schemas into models or - hand-written classes into schemas, using one `.g.dart` part. -- Generated model constructors are unchecked; use parsing for untrusted input - and JSON encoding for validated output. -- Native schemas export Draft-7; imported 2020-12 resources retain their - dialect unless explicitly lowered. -- Adapters reuse schemas for Firebase AI, MCP inputs, and - `json_schema_builder`; Ack still validates the data. - ## Start here Install the version documented on this branch: @@ -33,19 +17,25 @@ Install the version documented on this branch: dart pub add ack:^2.0.0-beta.3 ``` -```dart +```dart compile=body import 'package:ack/ack.dart'; final userSchema = Ack.object({ - 'name': Ack.string().minLength(2), - 'nickname': Ack.string().optional().nullable(), + 'name': Ack.string().minLength(2).maxLength(50), + 'age': Ack.integer().min(0).max(120), + 'email': Ack.string().email().nullable(), +}); + +final result = userSchema.safeParse({ + 'name': 'Ada', + 'age': 36, + 'email': 'ada@example.com', }); -final result = userSchema.safeParse({'name': 'Ada'}); if (result.isOk) { - print(result.getOrThrow()); + print('Welcome, ${result.getOrThrow()!['name']}'); } else { - print(result.getError()); + print(result.getError()); // one path: message line per failure } ``` diff --git a/docs.json b/docs.json index a99e12da..85457a08 100644 --- a/docs.json +++ b/docs.json @@ -80,10 +80,6 @@ { "group": "Adapter Authors", "pages": [ - { - "title": "Adapter Package Quickstart", - "href": "/guides/schema-converter-quickstart" - }, { "title": "Creating Adapter Packages", "href": "/guides/creating-schema-converter-packages" diff --git a/docs/api-reference/index.mdx b/docs/api-reference/index.mdx index eea44bfc..02a09a5e 100644 --- a/docs/api-reference/index.mdx +++ b/docs/api-reference/index.mdx @@ -2,578 +2,212 @@ title: API Reference --- -This page is a curated quick reference for the core Ack classes, methods, and -annotations. Use the [generated API documentation](https://pub.dev/documentation/ack/latest/ack/) -for every public declaration and exact signatures; use the linked guides here -for explanations and examples. - -## Core `Ack` Class - -Entry point for creating schemas. See [Schema Types](../core-concepts/schemas.mdx). - -- `Ack.string()`: Creates a `StringSchema` for validating `String` values. -- `Ack.integer()`: Creates an `IntegerSchema` for finite numeric values with no - fractional part. Losslessly normalizes inputs such as `42.0` to `int`. -- `Ack.double()`: Creates a `DoubleSchema` for finite numeric values. Losslessly - normalizes inputs such as `42` to `double`. -- `Ack.number()`: Creates a `NumberSchema` for finite `num` values while - preserving their `int` or `double` representation. -- `Ack.boolean()`: Creates a `BooleanSchema` for validating `bool` values. -- `Ack.list(AckSchema itemSchema)`: Creates a `ListSchema` for validating arrays. Nullable item schemas are not supported; make the list itself nullable instead. -- `Ack.object(Map properties)`: Creates an `ObjectSchema` for validating objects. -- `Ack.enumValues(List values)`: Creates an `EnumSchema` for Dart enum - types. Parses enum `.name` strings into typed enum values. Pass typed enum - values to `encode` or `safeEncode` for the reverse direction. **Preferred - over `enumString` when a Dart enum exists.** -- `Ack.enumString(List values)`: Creates a `StringSchema` constrained - to the given values. For ad-hoc string lists without a backing Dart enum. -- `Ack.anyOf(List schemas)`: Creates an `AnyOfSchema` for union types. -- `Ack.any()`: Creates an `AnySchema` that accepts any non-null JSON-safe - value. Chain `.nullable()` to allow `null`. -- `Ack.fromJsonSchema(Object document, {Uri? baseUri, Map - documents = const {}, bool assertFormats = false, String Function(String)? - unicodeNormalizer})`: Strictly imports a - decoded draft 2020-12 or Draft-7 JSON Schema. Referenced documents must be - supplied explicitly; Ack never fetches files or URLs. `format` is treated as - an annotation by default unless `assertFormats: true` (or the schema's - `$vocabulary` requires `format-assertion`). `unicodeNormalizer` supplies - NFKC normalization for international hostname and email checks; see - [format import](../guides/json-schema-integration.mdx#importing-format). -- `Ack.map(AckSchema valueSchema)`: Creates a `MapSchema` for a JSON object - with arbitrary string keys whose values all match `valueSchema`. Use - `Ack.map(Ack.any().nullable())` for a `JsonMap`. -- `Ack.instance()`: Creates a schema that checks a value is a - Dart instance of `T` (runtime type check; handy as a codec `output` schema). -- `Ack.codec(...)` / `Ack.date()` / `Ack.datetime()` / `Ack.uri()` / - `Ack.duration()`: Create codecs. See - [Codecs](../core-concepts/codecs.mdx). -- `Ack.lazy(String name, AckSchema Function() builder, {int maxDepth = 100})`: - Creates a memoized deferred schema reference for recursive schema graphs. - `maxDepth` must be at least `1` and limits parsing, runtime validation, and - encoding. JSON Schema export renders Draft-7 `definitions` / `$ref` entries - using `name` but warns that the runtime-only depth limit was omitted. -- `Ack.discriminated(...)`: Creates a discriminated union - schema. Branches may be plain `ObjectSchema` or transformed schemas whose - base is an `ObjectSchema`. The union owns the discriminator: branches normally - omit it, boundary payloads must include it, compatible branch discriminator - fields are allowed, and conflicts are rejected. Exported/generated branches - expose the exact branch literal. - -## JSON Schema Import - -See [JSON Schema Integration](../guides/json-schema-integration.mdx) for the -supported draft 2020-12 subset, reference-bundle behavior, diagnostics, and -examples. - -- `JsonSchemaImportDiagnostic`: Describes one import issue through `code`, - `documentUri`, `pointer`, `keyword`, and `message`. -- `JsonSchemaImportException`: Thrown when an import encounters an unsupported - assertion or cannot be completed safely. Its - `diagnostics` list identifies every reported issue. -- `JsonSchemaValidationError`: A `SchemaValidationError` returned when a value - fails an imported schema. `keyword` names the failing keyword, and - `documentUri` and `pointer` locate it after `$ref` resolution. - `keywordLocation` is the evaluation path that reached it, including `$ref`. - -## `AckSchema` (Base Class) - -Base class for all schema types. - -### Primary Validation Methods - -- `SchemaResult safeParse(Object? data, {String? debugName})`: Validates - `data` and returns a `SchemaResult`. Invalid input and recoverable `Exception` - values thrown by constraint, refinement, or `CodecSchema` `decode`/`encode` - callbacks become validation failures (`SchemaValidationError` / - `SchemaTransformError` / `SchemaEncodeError`), while programmer `Error` values - are rethrown with their original stack trace. -- `Runtime? parse(Object? data, {String? debugName})`: Validates `data` and returns the value; throws `AckException` on failure. -- `SchemaResult safeParseAs(Object? data, TOut? Function(Runtime?) map, {String? debugName})`: Parses and maps the validated value. A mapper that returns `null` produces a successful result with that value. Mapper `Exception`s become `SchemaTransformError` failures. Mapper `Error` values are rethrown with their original stack trace. -- `TOut parseAs(Object? data, TOut Function(Runtime?) map, {String? debugName})`: Throwing variant of `safeParseAs`. -- `SchemaResult safeEncode(Runtime? value, {String? debugName})`: Encodes a runtime value to the boundary representation, validating nested collection contents. -- `Boundary? encode(Runtime? value, {String? debugName})`: Throwing variant of `safeEncode`. - -### Schema Modification Methods - -- `AckSchema nullable({bool value = true})`: Returns a new schema that also accepts `null`. -- `AckSchema optional({bool value = true})`: Returns a new schema marked as optional (for object fields). -- `AckSchema describe(String description)`: Attaches a description for documentation and JSON Schema generation. -- `DefaultSchema withDefault(Runtime value)`: Wraps the schema in a `DefaultSchema` that supplies `value` when the parse input is `null`. - -String and boolean schemas require their exact Dart runtime type. Numeric -schemas require a `num` and follow JSON Schema value semantics instead of the -platform-specific `int`/`double` representation: `IntegerSchema` normalizes -lossless zero-fraction values to `int`, `DoubleSchema` normalizes exactly -representable values to `double`, and `NumberSchema` preserves the input -representation. Integer and double branches therefore overlap for integral -values in `Ack.anyOf`; the first matching branch determines the runtime value. -For non-`num` boundary types (e.g. numeric strings), use -[`transform`](../core-concepts/schemas.mdx#transformations) or -[`codec`](#codecschemaboundary-runtime) to convert before validation. - -### Custom Validation Methods - -- `AckSchema constrain(Constraint constraint, {String? message})` - adds a custom constraint and optionally overrides its error message. The - constraint must mix in `Validator`, or `constrain` throws an - `ArgumentError`. Chain `constrain` calls to attach multiple constraints. -- `AckSchema refine(bool Function(Runtime) validate, {String message = 'The value did not pass the custom validation.'})`: Adds a custom validation predicate with an optional error message. -- `CodecSchema transform(R Function(Runtime) transformer)`: Transforms validated runtime values to `R` (parse-only; encode fails). - -### Utility Methods - -- `Map toJsonSchema()`: Returns a JSON Schema map via the - canonical `AckSchemaModel` boundary, preserving imported Draft 2020-12 - resources by default and emitting Draft-7 for native Ack schemas. -- `Map toJsonSchemaDraft7()`: Lowers imported schemas into the - legacy Draft-7 `definitions` / `$ref` representation when possible. -- `AckSchemaModel toSchemaModel()`: Returns the canonical, target-independent - boundary model for schema adapters (preserving imported Draft 2020-12 - resources by default), including export warnings. -- `AckSchemaModel toSchemaModelDraft7()`: Returns the canonical boundary model - with imported schemas lowered to Draft-7 `definitions` / `$ref` when possible. - -See also [Schema Types](../core-concepts/schemas.mdx) for detailed usage examples. - -## `StringSchema` - -Schema for validating strings. See [String Validation](../core-concepts/validation.mdx#string-constraints). - -### Length Constraints - -- `minLength(int min)`: Minimum string length -- `maxLength(int max)`: Maximum string length -- `length(int exact)`: Exact string length -- `notEmpty()`: String must not be empty (equivalent to `minLength(1)`) - -### Pattern Matching - -- `matches(String pattern, {String? example, String? message})`: Must match a regex pattern. Patterns are not automatically anchored — use `^...$` for full-string matching. See [String validation](../core-concepts/validation.mdx#string-constraints) for details. -- `contains(String substring, {String? example, String? message})`: Must contain the literal substring. -- `startsWith(String value)`: Must start with `value`. -- `endsWith(String value)`: Must end with `value`. - -### Format Validation - -- `email()`: Must be valid email format -- `uri()`: Must be a valid absolute URI with a scheme and host -- `uuid()`: Must be valid UUID format -- `ip({int? version})`: Must be valid IP address (version 4 or 6) -- `ipv4()`: Must be valid IPv4 address -- `ipv6()`: Must be valid IPv6 address - -### Date and Time - -- `date()`: Must be valid ISO 8601 date (YYYY-MM-DD) -- `datetime()`: Must be a valid ISO 8601 datetime; announced RFC leap seconds - are accepted and preserved as strings -- `time()`: Must be valid time format (HH:MM:SS) - -### Transformations - -- `trim()`: Removes leading and trailing whitespace -- `toLowerCase()`: Converts to lowercase -- `toUpperCase()`: Converts to uppercase - -## `IntegerSchema` / `DoubleSchema` / `NumberSchema` (Number Schemas) - -Schemas for validating numeric values. `IntegerSchema` accepts finite `num` -values with no fractional part when conversion to `int` is lossless. -`DoubleSchema` accepts finite `num` values when conversion to `double` is -lossless. `NumberSchema` accepts finite `num` values without changing their -runtime representation. See -[Number Validation](../core-concepts/validation.mdx#number-constraints). - -Each method's parameter type matches the schema's runtime type: `int` for `IntegerSchema`, `double` for `DoubleSchema`, and `num` for `NumberSchema`. - -- `min(N limit)`: Minimum value (inclusive) -- `max(N limit)`: Maximum value (inclusive) -- `greaterThan(N limit)`: Must be greater than limit (exclusive) -- `lessThan(N limit)`: Must be less than limit (exclusive) -- `positive()`: Must be greater than 0 -- `negative()`: Must be less than 0 -- `multipleOf(N factor)`: Must be a multiple of the factor -- `finite()`: Must be finite (`DoubleSchema` and `NumberSchema`; already the default) -- `safe()`: Must be within safe integer range (`IntegerSchema` only) +This page lists the public Ack API by type, with a one-line summary for each +symbol. Exact signatures are in the +[generated API documentation](https://pub.dev/documentation/ack/latest/ack/) on +pub.dev. Explanations and examples are in the linked guides. + +## `Ack` factories + +Entry points for creating schemas. See [Schema Types](../core-concepts/schemas.mdx). + +- `Ack.string()`: Creates a `StringSchema` for `String` values. +- `Ack.literal(String value)`: Creates a `StringSchema` that accepts only `value`. +- `Ack.enumString(List values)`: Creates a `StringSchema` limited to `values`, for string lists without a Dart enum. +- `Ack.enumValues(List values)`: Creates an `EnumSchema` that parses enum `.name` strings into typed enum values. Prefer it over `enumString` when a Dart enum exists. +- `Ack.integer()`: Creates an `IntegerSchema` for finite numbers with no fractional part. It normalizes lossless inputs such as `42.0` to `int`. +- `Ack.double()`: Creates a `DoubleSchema` for finite numbers. It normalizes lossless inputs such as `42` to `double`. +- `Ack.number()`: Creates a `NumberSchema` for finite `num` values and keeps their `int` or `double` representation. +- `Ack.boolean()`: Creates a `BooleanSchema` for `bool` values. +- `Ack.list(AckSchema itemSchema)`: Creates a `ListSchema` for arrays. Item schemas cannot be nullable; make the list nullable instead. +- `Ack.object(Map properties, {bool additionalProperties = false})`: Creates an `ObjectSchema` for objects. +- `Ack.map(AckSchema valueSchema)`: Creates a `MapSchema` for objects with arbitrary string keys whose values match `valueSchema`. Use `Ack.map(Ack.any().nullable())` for a `JsonMap`. +- `Ack.anyOf(List schemas)`: Creates an `AnyOfSchema` that accepts a value matching any listed schema. +- `Ack.any()`: Creates an `AnySchema` that accepts any non-null JSON-safe value. Chain `.nullable()` to allow `null`. +- `Ack.discriminated(...)`: Creates a `DiscriminatedObjectSchema`, a union selected by a string discriminator property. The union owns the discriminator. Branches normally omit it. The boundary payload must include it. A branch that declares the discriminator must use `Ack.literal(...)` or `Ack.enumString(...)` containing the branch key. Exports expose each branch discriminator as an exact literal. +- `Ack.lazy(String name, AckSchema Function() builder, {int maxDepth = 100})`: Creates a memoized, deferred schema reference for recursive graphs. `maxDepth` must be at least `1` and limits parsing, validation and encoding. Export renders Draft-7 `definitions` and `$ref` by `name` and warns that the depth limit is omitted. A lazy schema cannot be a discriminated-union branch. +- `Ack.instance()`: Creates a schema that checks a value is a Dart instance of `T`. Use it as a codec `output` schema. +- `Ack.preserveBoundary(schema)`: Creates a `BoundarySchema` that validates like `schema` but returns the detached, unmodifiable JSON map. Put `withDefault` outside it. +- `Ack.codec(...)`: Creates a `CodecSchema` from an `input` schema, `decode` and `encode`. See [Codecs](../core-concepts/codecs.mdx). +- `Ack.date()`, `Ack.datetime()`, `Ack.uri()`, `Ack.duration()`: Create built-in codecs. See [Built-in codecs](../core-concepts/codecs.mdx#built-in-codecs). `Ack.date()` decodes to the local value of `DateTime(year, month, day)`. +- `Ack.fromJsonSchema(Object document, {Uri? baseUri, Map documents, bool assertFormats, String Function(String)? unicodeNormalizer})`: Imports a decoded Draft 2020-12 or Draft-7 JSON Schema. Ack never fetches referenced documents; supply them in `documents`. See [JSON Schema Integration](../guides/json-schema-integration.mdx). +- `deepUnmodifiableJsonMap(JsonMap value)`: Creates a detached, recursively unmodifiable snapshot of nested maps, lists and sets. It does not validate. Use it in hand-written constructors that store dynamic JSON maps. + +## `AckSchema` + +Base class of all schemas. `Boundary` is the wire type and `Runtime` is the parsed type. + +### Properties + +- `isNullable`: The nullability setting of this schema, from `nullable()` or an imported schema. It is not the whole answer: a union with a nullable branch or a default can still accept `null`. To learn whether `null` parses, call `safeParse(null)`. +- `isOptional`: The optionality setting of this schema, from `optional()`. An object field with a default can also be omitted; see [Defaults](../core-concepts/schemas.mdx#defaults). +- `description`: The text set by `describe`. +- `constraints`: The unmodifiable list of attached constraints. +- `refinements`: The unmodifiable list of attached refinements. + +### Parse and encode + +- `safeParse(Object? data, {String? debugName})`: Validates `data` and returns a `SchemaResult`. Invalid input and recoverable `Exception` values from constraints, refinements or codec callbacks become failures. Programmer `Error` values are rethrown with their stack trace. +- `parse(Object? data, {String? debugName})`: Validates `data` and returns the value. It throws `AckException` on failure. +- `safeParseAs(Object? data, TOut? Function(Runtime?) map, {String? debugName})`: Parses, then maps the value. A mapper `Exception` becomes a `SchemaTransformError`. +- `parseAs(Object? data, TOut Function(Runtime?) map, {String? debugName})`: Throwing variant of `safeParseAs`. +- `safeEncode(Runtime? value, {String? debugName})`: Encodes a runtime value to the boundary representation and returns a `SchemaResult`. +- `encode(Runtime? value, {String? debugName})`: Throwing variant of `safeEncode`. + +String and boolean schemas require their exact Dart runtime type. Numeric schemas require a `num` and follow JSON Schema value semantics instead of the platform `int` or `double` representation. `IntegerSchema` normalizes lossless zero-fraction values to `int`. `DoubleSchema` normalizes exactly representable values to `double`. `NumberSchema` keeps the input representation. In `Ack.anyOf`, integer and double branches overlap for integral values, and the first match decides the runtime value. See [Primitive inputs and numeric normalization](../core-concepts/validation.mdx#primitive-inputs-and-numeric-normalization). + +### Modify + +- `nullable({bool value = true})`: Returns a copy that also accepts `null`. +- `optional({bool value = true})`: Returns a copy marked optional as an object field. It does not allow `null`; combine it with `.nullable()` for that. See [Optional vs nullable](../core-concepts/schemas.mdx#optional-vs-nullable). +- `describe(String description)`: Returns a copy with a description for documentation and JSON Schema export. +- `withDefault(Runtime value)`: Returns a `DefaultSchema` that supplies `value` when the input is `null`. See [Defaults](../core-concepts/schemas.mdx#defaults). +- `refine(bool Function(Runtime) validate, {String message})`: Returns a copy with a custom predicate. See [Cross-field rules with `.refine()`](../guides/custom-validation.mdx#cross-field-rules-with-refine). +- `constrain(Constraint constraint, {String? message})`: Returns a copy with a custom constraint. The constraint must mix in `Validator`, or `constrain` throws `ArgumentError`. See [Creating a value constraint](../guides/custom-validation.mdx#creating-a-value-constraint). +- `transform(R Function(Runtime) transformer)`: Returns a one-way `CodecSchema` that converts the parsed value. Encoding fails. This is an extension method. See [Transforming values with `transform`](../guides/custom-validation.mdx#transforming-values-with-transform). +- `codec({required decode, required encode, AckSchema? output})`: Returns a two-way `CodecSchema`. This is an extension method. See [Codecs](../core-concepts/codecs.mdx). + +### Export + +- `toJsonSchema()`: Returns a JSON Schema map. Imported Draft 2020-12 resources are preserved by default, and native Ack schemas render as Draft-7. +- `toJsonSchemaDraft7()`: Returns the map with imported schemas lowered to Draft-7 `definitions` and `$ref` when possible. +- `toSchemaModel()`: Returns the canonical, target-independent `AckSchemaModel` for adapters, including export warnings. +- `toSchemaModelDraft7()`: Returns the model with imported schemas lowered to Draft-7 when possible. + +See [JSON Schema Integration](../guides/json-schema-integration.mdx) and [Creating Adapter Packages](../guides/creating-schema-converter-packages.mdx). + +## Schema types + +- `AckSchemaModel`: The canonical export model. `schema.toSchemaModel().toJsonSchema()` equals `schema.toJsonSchema()`. Adapters for non-JSON targets translate it instead of walking `AckSchema` subclasses. +- `EnumSchema`: Maps enum `.name` strings to typed enum values. `encode` maps them back. +- `AnyOfSchema`: A union that matches one of several schemas. +- `DiscriminatedObjectSchema`: A discriminated union. `effectiveBranch(String discriminatorValue)` returns the branch schema with the discriminator injected as an exact literal. +- `AnySchema`: Accepts any non-null JSON-safe value. Parsing returns a detached, unmodifiable snapshot. +- `MapSchema`: An object with arbitrary string keys. It exports as `{"type": "object", "additionalProperties": }`. Errors report the value's key path. +- `CodecSchema`: Decodes boundary values and encodes runtime values. See [Codecs](../core-concepts/codecs.mdx). +- `DefaultSchema`: Wraps a schema with a default value. +- `BoundarySchema`: A wire view of an object schema, created by `Ack.preserveBoundary`. +- `JsonMaybe`: A sealed class for class-first models that tells an omitted property (`JsonAbsent`) from a present one (`JsonValue`, including `null`). It has `absent()`, `value(T?)` and `nullValue()` constructors and the getters `isAbsent`, `isPresent` and `valueOrNull`. See [Model Code Generation](../core-concepts/typesafe-schemas.mdx). + +## `StringSchema` constraints + +See [String constraints](../core-concepts/validation.mdx#string-constraints). String lengths count Unicode code points. + +| Method | Rule | +|---|---| +| `minLength(int)`, `maxLength(int)`, `length(int)` | Minimum, maximum or exact length | +| `notEmpty()` | At least one character (same as `minLength(1)`) | +| `matches(String pattern, {example, message})` | Regex match. Patterns are not anchored; use `^...$` for the full value | +| `contains(String)`, `startsWith(String)`, `endsWith(String)` | Literal substring, prefix or suffix | +| `email()`, `uuid()` | Email or UUID format | +| `uri()` | Absolute URI with a scheme and host | +| `ip({int? version})`, `ipv4()`, `ipv6()` | IP address | +| `date()` | ISO 8601 date (`YYYY-MM-DD`) | +| `datetime()` | ISO 8601 datetime. Announced RFC leap seconds are accepted and kept as strings | +| `time()` | Time as `HH:MM:SS` | +| `trim()`, `toLowerCase()`, `toUpperCase()` | Normalizers that change the parsed value | + +## Number constraints + +`IntegerSchema`, `DoubleSchema` and `NumberSchema` share these methods. The parameter type is `int`, `double` or `num` to match the schema. See [Number constraints](../core-concepts/validation.mdx#number-constraints). + +| Method | Rule | +|---|---| +| `min(limit)`, `max(limit)` | Inclusive bounds | +| `greaterThan(limit)`, `lessThan(limit)` | Exclusive bounds | +| `positive()`, `negative()` | Greater than or less than 0 | +| `multipleOf(factor)` | Multiple of `factor` | +| `finite()` | Finite value (`DoubleSchema` and `NumberSchema`; already the default) | +| `safe()` | Within the safe integer range (`IntegerSchema` only) | ## `BooleanSchema` -Schema for validating booleans. Validates `true` and `false` values strictly — non-boolean inputs are rejected. For boundary types that arrive as strings (e.g. `"true"`/`"false"`), use a `transform` or `codec` to convert before validation. +Accepts only `true` and `false`. For string input such as `"true"`, use a `codec` to convert first. -## `ListSchema` +## `ListSchema` constraints -Schema for validating arrays. See [List Validation](../core-concepts/validation.mdx#list-constraints). +See [List constraints](../core-concepts/validation.mdx#list-constraints). -- `minItems(int min)`: Minimum number of items -- `maxItems(int max)`: Maximum number of items -- `length(int exact)`: Exact number of items -- `notEmpty()`: List must have at least one item -- `unique()`: All items must be unique +| Method | Rule | +|---|---| +| `minItems(int)`, `maxItems(int)`, `length(int)` | Minimum, maximum or exact item count | +| `notEmpty()` | At least one item | +| `unique()` | No duplicate items | -## `ObjectSchema` +## `ObjectSchema` methods -Schema for validating objects (maps). See [Object Validation](../core-concepts/schemas.mdx#object). +See [Object schemas](../core-concepts/schemas.mdx#object). -- Constructed using `Ack.object(Map properties, {bool additionalProperties = false})`. -- Use `.pick(List keys)` to create schema with only specified properties. -- Use `.omit(List keys)` to create schema excluding specified properties. -- Use `.extend(Map newProperties)` to add more properties. -- Use `.partial()` to make all properties optional. -- Use `.strict()` to disallow additional properties. -- Use `.passthrough()` to allow and preserve additional properties not defined - in the schema. -- Use `.merge(ObjectSchema other)` to combine with another object schema. +- `pick(List keys)`: Returns a schema with only the listed properties. +- `omit(List keys)`: Returns a schema without the listed properties. +- `extend(Map newProperties)`: Returns a schema with more properties. +- `merge(ObjectSchema other)`: Returns a schema that combines both property sets. +- `partial()`: Returns a schema with every property optional. +- `strict()`: Returns a schema that rejects additional properties. +- `passthrough()`: Returns a schema that allows and keeps additional properties. -## `deepUnmodifiableJsonMap(JsonMap value)` +## Results and errors -Creates a detached, recursively unmodifiable snapshot of nested maps, lists, -and sets. It does not validate JSON shape or values. Use it in hand-written -constructors that store dynamic JSON maps and need stable equality and hashes. -## `SchemaResult` +See [Error Handling](../core-concepts/error-handling.mdx). -Object returned by `safeParse()`. See [Error Handling](../core-concepts/error-handling.mdx). - -- `bool isOk`: `true` if validation succeeded. -- `bool isFail`: `true` if validation failed. -- `T? getOrThrow()`: Returns the validated value (which can be `null` for a nullable schema), or throws `AckException` on failure. -- `T? getOrNull()`: Returns the validated value, or `null` on failure. -- `SchemaError getError()`: Returns the validation error; only valid when `isFail` is `true`. -- `T? getOrElse(T? Function() orElse)`: Returns the validated value, or calls `orElse` on failure. -- `SchemaResult map(R Function(T?) transform)`: Maps the successful value to a new result type; propagates failures unchanged. -- `R match({required R Function(T?) onOk, required R Function(SchemaError) onFail})`: Pattern-matches on success or failure. -- `void ifOk(void Function(T?) action)`: Executes `action` only when the result is successful. -- `void ifFail(void Function(SchemaError) action)`: Executes `action` only when the result is a failure. - -## `SchemaError` (and subclasses) - -Represents a validation failure. See [Error handling](../core-concepts/error-handling.mdx). - -- `String message`: Human-readable error message. -- `SchemaContext context`: Context about where the error occurred. - -**Subclasses:** +- `SchemaResult`: The result of `safeParse`, either `Ok` or `Fail`. Members: `isOk`, `isFail`, `getOrThrow()`, `getOrNull()`, `getOrElse()`, `getError()`, `map()`, `match()`, `ifOk()` and `ifFail()`. +- `SchemaError`: The base of all failures. Its members are described in [Understanding SchemaError](../core-concepts/error-handling.mdx#understanding-schemaerror). - `TypeMismatchError`: The input has the wrong Dart runtime type. -- `SchemaConstraintsError`: One or more constraint violations. -- `SchemaNestedError`: Validation failures in nested objects or arrays. -- `SchemaValidationError`: Custom refinement failures. -- `SchemaTransformError`: Decode/transform callback failures. -- `SchemaEncodeError`: Encode-path failures (non-nullable null, one-way transform, encoder threw, etc.). - -## `Constraint` - -Base class for custom validation rules. See [Custom validation](../guides/custom-validation.mdx). - -- `String constraintKey`: Unique identifier for the constraint. Built-in identifiers use snake_case. -- `String description`: Human-readable description. -- `Map toMap()`: Serializes the constraint for debugging. - -## `Validator` (mixin) - -Validation behavior mixin used with `Constraint`. - -- `bool isValid(T value)`: Returns `true` when the value passes validation. -- `String buildMessage(T value)`: Builds the validation failure message. -- `ConstraintError? validate(T value)`: Validates a value and returns an error if invalid. - -## Additional schema types - -Ack ships with a broad set of schema factories beyond what is listed here. -See [Schema types](../core-concepts/schemas.mdx) for the full catalogue, -including `Ack.date()`, `Ack.literal()`, and list/object combinators. - -### `Ack.discriminated(...)` - -Schema for polymorphic validation based on a string discriminator property. - -- Branch schemas normally omit the discriminator field. -- The boundary payload must still contain the discriminator key. -- If a branch schema includes the discriminator field, it must be - `Ack.literal(...)` matching the branch key or `Ack.enumString(...)` - containing it. Broad, transformed, refined, or otherwise restrictive - discriminator fields are rejected. -- Exported and generated schemas expose each branch discriminator as an exact - literal. -- Generated subtype `parse()` and `safeParse()` methods validate through the - union's effective branch. - -### `Ack.lazy(...)` - -Schema reference for recursive object graphs. - -- Created using `Ack.lazy(name, builder)`. `maxDepth` - defaults to `100` and must be at least `1`; pass it explicitly only to - override the default. -- The builder is resolved once and memoized. -- Exceeding `maxDepth` returns a validation failure during parsing, runtime - validation, or encoding. -- `toJsonSchema()` and `toSchemaModel()` export Draft-7 `definitions` / `$ref` - entries using the lazy `name`. The runtime-only depth limit cannot be - represented by `$ref`, so exported schema models warn that it was omitted. -- Bare or wrapped lazy schemas cannot be used as discriminated-union branches - because the branch discriminator must be analyzable at construction time. - -## Code generation annotations - -Use the [`ack_generator`](https://pub.dev/packages/ack_generator) builders in -either direction with one annotation, `@Schemable()`: on a top-level schema it -generates a model, on a class it generates a schema, and on a `library;` -directive it registers shared custom schemas via `@Schemable(schemas: [...])`. -`package:ack/ack.dart` exports `@Schemable`, `@AckKey`, and the `Is…`/`Has…` -rule annotations. -`AckSchema` is the runtime schema type; there is no `@AckSchema()` annotation. -After adding a `part '.g.dart';` directive, run: - -```bash -dart run build_runner build -``` +- `SchemaConstraintsError`: One or more constraints failed. +- `SchemaNestedError`: Failures inside nested objects or arrays. +- `SchemaValidationError`: A refinement failed. `JsonSchemaValidationError` is the subclass for a failed imported JSON Schema keyword; its `keyword` names the keyword, and `documentUri` and `pointer` locate it. +- `SchemaTransformError`: A decode or transform callback failed. +- `SchemaEncodeError`: Encoding failed, for example for a one-way transform. +- `AckException`: Thrown by `parse` and `getOrThrow`. Its `errors` list holds the `SchemaError` values. See [Error types](../core-concepts/error-handling.mdx#error-types). +- `JsonSchemaImportException`: Thrown when an import cannot complete safely. Its `diagnostics` list holds every reported issue. +- `JsonSchemaImportDiagnostic`: Describes one import issue through `code`, `documentUri`, `pointer`, `keyword` and `message`. -### `@Schemable()` on a top-level schema +## Constraints and `Validator` -**Target**: Schema variables and getters +See [Custom Validation](../guides/custom-validation.mdx#creating-a-value-constraint). -**Generates**: An immutable model class backed by the existing schema +- `Constraint`: The base class of validation rules. `constraintKey` is a unique snake_case identifier, `description` is readable text, and `toMap()` serializes the constraint for debugging. +- `Validator`: A mixin for constraints that validate values. `isValid(T)` checks a value, `buildMessage(T)` builds the failure message and `validate(T)` returns a `ConstraintError?`. -Annotate a top-level schema variable or getter. The schema stays in your source file and remains responsible for validation and codecs. +## Annotations -**Supported schema types:** -- `Ack.object({...})` → immutable object models -- Primitives: `Ack.string()`, `Ack.integer()`, `Ack.double()`, `Ack.boolean()` -- Collections: `Ack.list(...)`, `Ack.map(...)` fields, and codec-backed sets - and maps -- JSON values: `Ack.any()` fields as `Object` / `Object?` -- Enums: `Ack.literal()`, `Ack.enumString()`, `Ack.enumValues()` -- Discriminated unions: `Ack.discriminated(...)` +`package:ack/ack.dart` exports these annotations for code generation. -**Unsupported:** nullable roots, one-way transforms, `Ack.any()` and -`Ack.map()` roots, `Ack.anyOf()`, bare `Ack.instance()`, and anonymous -inline objects +- `@Schemable()`: On a top-level schema it generates a model. On a class it generates a schema. On a `library;` directive, `@Schemable(schemas: [...])` registers shared custom schemas. +- `@AckKey(name)`: Sets a field's wire name. +- Presence: `@IsRequired`, `@IsOptional`, `@IsNotNull`. +- Numbers: `@HasMin`, `@HasMax`, `@IsMultipleOf`, `@IsPositive`, `@IsNegative`. +- Strings: `@HasMinLength`, `@HasMaxLength`, `@HasMatch`, `@IsEmail`, `@IsNotEmpty`, `@IsUri`, `@IsUuid`, `@IsDate`, `@IsDateTime`, `@IsIp`. +- Collections: `@IsNotEmpty`, `@HasMinItems`, `@HasMaxItems`, `@HasUniqueItems`. +- `AckCaseStyle` and `AckUnknownPropertyPolicy`: Enums for the `caseStyle` and `unknownProperties` options of `@Schemable()`. -`name` sets the exact model class name; the class-only options are rejected -here. For `Ack.discriminated(...)` constraints, see -[Model Code Generation](../core-concepts/typesafe-schemas.mdx#schema-first-unions). +`AckSchema` is the runtime schema type. There is no `@AckSchema()` annotation. -**Example:** -```dart compile=reference-user -import 'package:ack/ack.dart'; +## Generator API -part 'user.g.dart'; +Run `dart run build_runner build` after you add a `part` directive. The `ack_generator` package provides these builders. -@Schemable() -final userSchema = Ack.object({ - 'name': Ack.string(), - 'email': Ack.string().email(), -}); +| Target | Generates | Guide | +|---|---|---| +| `@Schemable()` on a top-level schema | An immutable model class backed by the schema | [Schema-first models](../core-concepts/typesafe-schemas.mdx) | +| `@Schemable()` on a class | A `Schema` facade and the `_$ClassAck` mixin (`toJson`, `copyWith`, equality) | [Class-first models](../core-concepts/typesafe-schemas.mdx) | +| Sealed class with `@Schemable(discriminatorKey: ...)` | A discriminated union of its same-library branches | [Model Code Generation](../core-concepts/typesafe-schemas.mdx) | +| `lib/**/*.schema.json` with `ack_generator:ack_json_schema` | `.schema.dart`, compiled into typed models | [Generating Dart models from `.schema.json` files](../guides/json-schema-integration.mdx#generating-dart-models-from-schemajson-files) | -// Generated: -// - final class User { ... } -// - The schema variable remains unchanged +### `generateAckSchemaLibrary` -// Usage: -final user = User.parse({'name': 'Alice', 'email': 'alice@example.com'}); -print(user.name); // Type-safe String access -print(user.email); // Type-safe String access -print(user.toJson()); -``` +`package:ack_generator/ack_generator.dart` exposes the function behind the `.schema.json` builder. It returns an `AckJsonSchemaLibrary` with `source`, `effectiveDocument` and `widenedPointers`. All parameters are named. Set format assertion with `AckJsonSchemaLibraryOptions(assertFormats: true)`. -### `@Schemable()` on a class - -Concrete models and union branches must be `final class` declarations with -final stored fields. Annotated sealed union bases remain supported. Parsed -collections and captured extras are recursively unmodifiable; hand-written -constructors remain responsible for defensively copying direct inputs. - -**Target**: Public, constructable classes - -**Generates**: A public `Schema` facade backed by a private typed -codec (`_Schema`) and a `wireSchema` that validates like it but -returns the JSON map, plus the `_$ClassAck` mixin for `toJson`, `safeToJson`, -`copyWith`, and deep collection-aware `==` / `hashCode` / `toString` - -Ack infers schema fields from constructor-backed fields (including Dart 3.13+ -primary constructors). Required parameters, nullable types, optional parameters, -`JsonMaybe`, and constructor defaults determine field presence. Use -`caseStyle` for model-wide JSON naming and `@AckKey(...)` on the field -or primary constructor parameter for a wire-name override. Instantiable models -and implicit union branches must apply the generated mixin. In `copyWith`, -omission keeps the current value and explicit `null` clears a nullable field. -`copyWith` returns a typed interface, so a wrongly typed argument is a -compile-time error. - -**Inferred field types:** strings, booleans, numeric types, `DateTime`, `Uri`, -`Duration`, enums, `JsonMaybe`, nested lists, sets, and string-keyed maps - -**Rule annotations (from `package:ack/ack.dart`):** - -- presence & nullability: `@IsRequired`, `@IsOptional`, `@IsNotNull` -- numeric: `@HasMin`, `@HasMax`, `@IsMultipleOf`, `@IsPositive`, `@IsNegative` -- strings: `@HasMinLength`, `@HasMaxLength`, `@HasMatch`, `@IsEmail`, `@IsNotEmpty` -- string formats: `@IsUri`, `@IsUuid`, `@IsDate`, `@IsDateTime`, `@IsIp` (`version: 4` or `6` for one family) -- collections: `@IsNotEmpty`, `@HasMinItems`, `@HasMaxItems`, `@HasUniqueItems` - - -**Custom schemas:** a field of custom type `T` resolves through: -1. `@Schemable(schemas: [...])` on the class, union base, `library;` directive, or an imported `library;` directive; -2. a static `T.schema` / `T.schema(...)` on the type; -3. a unique top-level `AckSchema` variable, getter, or zero-argument function in the current library. - -A sealed base annotated with `@Schemable(discriminatorKey: ...)` generates a discriminated union from its -same-library concrete branches. Unknown properties use -`unknownProperties: AckUnknownPropertyPolicy.` (`reject` by default). -Raw `Ack.object(..., additionalProperties: true)` schemas preserve extras. -Class projection is a later step: `discard` is only for tolerant, read-only -consumers, while models that round-trip unknown keys must use `capture` and may -select the target map with `captureField`. - -```dart compile=reference-account -import 'package:ack/ack.dart'; - -part 'account.g.dart'; - -@Schemable(caseStyle: AckCaseStyle.snake) -final class const Account({ - @HasMinLength(2) required final String displayName, - final String role = 'member', -}) with _$AccountAck { - static final schema = AccountSchema.schema; - static final fromJson = AccountSchema.fromJson; -} - -final account = Account.schema.parse({'display_name': 'Ada'})!; -print(account.toJson()); -print(Account.schema.toJsonSchema()); +```dart compile=generator-signature +AckJsonSchemaLibrary generateAckSchemaLibrary({ + required Object? document, + required Uri documentUri, + required String partStem, + AckJsonSchemaLibraryOptions options = const AckJsonSchemaLibraryOptions(), + Map documents = const {}, + bool includeParts = true, + Version? languageVersion, +}) ``` -The facade exposes `schema`, `wireSchema`, `parse`, `safeParse`, `fromJson`, -`encode`, `safeEncode`, `toJsonSchema`, and `toSchemaModel`. -`static final schema = AccountSchema.schema;` attaches the facade's codec to -`Account.schema`. The backing codec variable is library-private and no public -lower-camel alias is generated. Set `schemaName: 'WireAccountSchema'` to choose the exact facade -class name. - -Nested class-first fields compose through `AddressSchema.schema` (or -`Address.schema` when declared on `Address`). Imports with combinators can -expose just `show Address` when `Address.schema` is declared, or -`show Address, AddressSchema` otherwise. A schema-first `@Schemable()` -declaration may also compose the facade explicitly, and class-first models can -use schema-first generated model types on a clean build. - -A class-first `@Schemable()` cannot share a class with `@JsonSerializable()`, -and `name` is rejected on a class. Class-first value roots, automatic recursive -graphs, and undiscriminated `anyOf` shapes -are unsupported; use a schema-first `@Schemable()` schema and named `Ack.lazy` for those -cases. See -[Model Code Generation](../core-concepts/typesafe-schemas.mdx) for the complete -tutorial and comparison. - -### `EnumSchema` - -Schema for mapping enum `.name` strings at the boundary to typed enum values at -runtime. Created using `Ack.enumValues(List values)` where `T extends Enum`; -`encode` and `safeEncode` map typed enum values back to their names. - -### `AnyOfSchema` - -Schema for union types; the value must match one of several schemas. Created using `Ack.anyOf(List schemas)`. - -### `DiscriminatedObjectSchema` - -Schema for polymorphic validation based on a discriminator field. - -- Created using `Ack.discriminated(...)` with - `discriminatorKey` and `schemas`. -- `effectiveBranch(String discriminatorValue)`: Returns the branch schema with - the discriminator injected as the exact branch literal. Generated subtypes use - this to validate a specific branch. - -### `AckSchemaModel` - -Canonical export model for Ack schemas. - -- Created by `schema.toSchemaModel()` (preserving imported Draft 2020-12 resources by default) or `schema.toSchemaModelDraft7()` (lowering imported schemas to Draft-7 `definitions` / `$ref`). -- Represents the boundary/export shape, JSON-compatible defaults, discriminator metadata, target-independent constraints, and export warnings. -- `schema.toSchemaModel().toJsonSchema()` returns the same JSON Schema map as `schema.toJsonSchema()` (and `schema.toSchemaModelDraft7().toJsonSchema()` matches `schema.toJsonSchemaDraft7()`). -- Adapters that need a JSON map should call `schema.toJsonSchema()`; adapters for non-JSON targets should convert from `AckSchemaModel` rather than traversing `AckSchema` subclasses directly. - -### `AnySchema` - -Accepts any non-null JSON-safe value without further validation. - -- Created by `Ack.any()`. -- Useful for dynamic payloads or pass-through metadata. -- Parsing returns a detached, recursively unmodifiable snapshot of the input; - encoding returns the runtime value unchanged after validating it. - -### `MapSchema` - -Schema for a JSON object with arbitrary string keys whose values all match -`valueSchema`. - -- Created by `Ack.map(valueSchema)`. -- Boundary and runtime types are `Map` and - `Map`. Nullability is a runtime flag in Ack, so the - static value type is nullable; a value is `null` only when `valueSchema` is - nullable. -- Parse runs `valueSchema` on every value and encode on every non-null value, - including codecs; errors report the value's key path. -- Exported to JSON Schema as - `{"type": "object", "additionalProperties": }`. - -### `CodecSchema` - -Schema that decodes boundary values into runtime values and encodes runtime -values back to the boundary representation. Use `encode` / `safeEncode` for the -reverse direction. See [Codecs](../core-concepts/codecs.mdx). - -- `schema.transform(R Function(Runtime) transformer)`: one-way transform - (parse only; `encode` fails with a one-way error). -- `schema.codec({required R Function(Runtime) decode, required Runtime Function(R) encode, AckSchema? output})`: - bidirectional codec; the optional `output` schema validates the runtime value. -- `Ack.codec({required input, required decode, required encode, output})`: - builds a codec from an `input` schema. - -**Built-in codecs:** - -- `Ack.date()` → `CodecSchema` (ISO `YYYY-MM-DD` ↔ local `DateTime(year, month, day)`) -- `Ack.datetime()` → `CodecSchema` (ISO 8601 ↔ UTC - `DateTime`; leap-second strings are rejected because Dart cannot represent - them) -- `Ack.uri()` → `CodecSchema` (absolute URI string ↔ `Uri`) -- `Ack.duration()` → `CodecSchema` (milliseconds ↔ `Duration`) - -### Optional schemas and `JsonMaybe` - -Every schema can be marked optional via the `optional({bool value = true})` fluent API. - -- `schema.optional()` sets `isOptional` to `true` without wrapping the schema. -- `schema.optional(value: false)` clears the optional flag. -- Optional affects object-field presence only; combine with `.nullable()` to also allow explicit `null`. - -In class-first `@Schemable()` models, use `sealed class JsonMaybe` (`JsonAbsent`, `JsonValue`) when you need to distinguish an omitted JSON property from an explicit `null` on both `parse` and `toJson`: - -- `const JsonMaybe.absent()` (`JsonAbsent`) — key omitted from JSON. -- `const JsonMaybe.value(T? value)` (`JsonValue`) — key present in JSON (with non-null or `null` value). -- `const JsonMaybe.nullValue()` — shorthand for `JsonValue(null)`. -- `maybe.isAbsent`, `maybe.isPresent`, `maybe.valueOrNull`. - -### `.schema.json` code generation (`ack_generator:ack_json_schema`) - -- **Builder (`build.yaml`)**: Enable `ack_generator:ack_json_schema` on `lib/**/*.schema.json` to emit `.schema.dart` (with `part '.schema.g.dart';`), which `ack_generator:ack_generator` compiles into typed `@Schemable()` models or validated value models. -- **Programmatic API (`package:ack_generator/ack_generator.dart`)**: - `generateAckSchemaLibrary` returns an `AckJsonSchemaLibrary` containing - `source`, `effectiveDocument`, and `widenedPointers`. All parameters are named: - - ```dart compile=generator-signature - AckJsonSchemaLibrary generateAckSchemaLibrary({ - required Object? document, - required Uri documentUri, - required String partStem, - AckJsonSchemaLibraryOptions options = const AckJsonSchemaLibraryOptions(), - Map documents = const {}, - bool includeParts = true, - Version? languageVersion, - }) - ``` - - Set format assertion through `AckJsonSchemaLibraryOptions(assertFormats: true)`. - -*See the [Schema types](../core-concepts/schemas.mdx) and [What's New & Migration Guide](../getting-started/migration-guide.mdx) for detailed usage and migration tables.* +For migration tables, see the [Migration Guide](../getting-started/migration-guide.mdx). diff --git a/docs/core-concepts/codecs.mdx b/docs/core-concepts/codecs.mdx index 605f7b95..93608e9a 100644 --- a/docs/core-concepts/codecs.mdx +++ b/docs/core-concepts/codecs.mdx @@ -13,17 +13,6 @@ final iso = when.encode(dt); // encode: DateTime -> String Ack calls the wire shape the **boundary** (JSON-safe primitives like `String` or `int`) and the Dart value the **runtime** (a `DateTime`, `Uri`, `Duration`, or your own type). Parsing decodes boundary → runtime; encoding goes the other way. -## Transform vs. codec - -| Helper | Direction | Returns | -| --- | --- | --- | -| `schema.transform(fn)` | one-way (parse only) | `CodecSchema` | -| `schema.codec(decode: ..., encode: ...)` | bidirectional | `CodecSchema` | - -Use `transform` when you only ever decode. Encoding a transformed schema fails -with a `SchemaEncodeError` (a one-way transform has no encoder). Use `codec` -when you need a reversible encode path. - ## Built-in codecs Ack ships codecs for the most common boundary conversions: @@ -53,10 +42,13 @@ final event = schema.parse({ // event['timeout'] is a Duration (5 seconds) ``` -Each built-in enforces a runtime invariant on encode. `Ack.datetime()` requires -a UTC `DateTime`; convert local values with `.toUtc()` before encoding. It also -rejects RFC leap-second strings before decoding because Dart normalizes `:60`. -Use `Ack.string().datetime()` when leap-second text must be validated and +Each built-in enforces its runtime invariant on encode. `Ack.date()` and its +`min()` and `max()` bounds accept the value from `DateTime(year, month, day)` +in the local time zone. On days that skip midnight, Dart may construct this +value with a later time of day. `Ack.datetime()` requires a UTC `DateTime`; +convert local values with `.toUtc()` before encoding. It also rejects RFC +leap-second strings before decoding because Dart normalizes `:60`. Use +`Ack.string().datetime()` when leap-second text must be validated and preserved. ## Custom codecs @@ -74,7 +66,13 @@ csv.parse('a,b,c'); // ['a', 'b', 'c'] csv.encode(['a', 'b', 'c']); // 'a,b,c' ``` -The three type arguments are the boundary type, the input schema's runtime type, and the final runtime type. The optional `output` schema validates the decoded value (defaults to a type check on the runtime type). +`Ack.codec` takes three type arguments: + +- the boundary type (`String` above); +- the input schema's runtime type (`String` above); +- the final runtime type (`List` above). + +The optional `output` schema validates the decoded value. It defaults to a type check on the runtime type. Call `.codec(...)` on an existing schema to add a reversible conversion: @@ -85,9 +83,16 @@ final trimmed = Ack.string().codec( ); ``` -`Ack.date()` and its `min()` and `max()` bounds accept the value from -`DateTime(year, month, day)` in the local time zone. On days that skip -midnight, Dart may construct this value with a later time of day. +## One-way transform vs. codec + +| Helper | Direction | Returns | +| --- | --- | --- | +| `schema.transform(fn)` | one-way (parse only) | `CodecSchema` | +| `schema.codec(decode: ..., encode: ...)` | bidirectional | `CodecSchema` | + +Use `transform` when you only ever decode. Encoding a transformed schema fails +with a `SchemaEncodeError` (a one-way transform has no encoder). Use `codec` +when you need a reversible encode path. ## Encoding back to the boundary @@ -100,7 +105,7 @@ if (result.isOk) { } ``` -Both methods take `Runtime?`. The schema determines whether it accepts `null`. During encoding, +Both methods take the runtime value. The schema decides whether `null` is accepted. During encoding, schemas validate untyped nested lists and maps, including those produced by `jsonDecode`, and apply the numeric coercions of the relevant schemas. Parse values first when they need a codec's decoder, such as a date-time string that @@ -138,6 +143,7 @@ final wireMinimumLength = Ack.string().minLength(5).codec( ); print(wireMinimumLength.toJsonSchema()); ``` + `Ack.duration()` is the exception: its boundary is the milliseconds its `min()` and `max()` already compare, so those constraints do export. diff --git a/docs/core-concepts/configuration.mdx b/docs/core-concepts/configuration.mdx index 4fd1936c..a2d33d55 100644 --- a/docs/core-concepts/configuration.mdx +++ b/docs/core-concepts/configuration.mdx @@ -2,140 +2,13 @@ title: Configuration --- -Ack has no global configuration object. All behavior is configured at the schema level through the fluent API. - -## Schema-level configuration - -Define behavior when you create your schemas. - -### Optional and nullable values - -Fields in [`Ack.object`](./schemas.mdx#object) are required and non-nullable by -default. Use `.optional()` when a field may be omitted, `.nullable()` when a -present field may be `null`, or both when either state is valid. - -```dart compile=body -Ack.object({ - 'id': Ack.integer(), - 'nickname': Ack.string().optional(), - 'middleName': Ack.string().nullable(), - 'avatarUrl': Ack.string().uri().optional().nullable(), -}); -``` - -See [Optional vs nullable](./schemas.mdx#optional-vs-nullable) for the complete -presence and nullability matrix. - -### Additional properties - -Control how extra fields are handled with the `additionalProperties` parameter in [`Ack.object`](./schemas.mdx#object). - -```dart compile=body -// Reject extra properties (default) -Ack.object({'id': Ack.integer()}); -// or explicitly: -Ack.object({'id': Ack.integer()}, additionalProperties: false); - -// Allow extra properties -Ack.object({'id': Ack.integer()}, additionalProperties: true); -``` - -Use strict objects for data you own and want to detect drift in. At external -API boundaries, `additionalProperties: true` can make a schema resilient to -new response fields while still validating every field your application uses. - -### Default values - -Use `.withDefault(value)` when a missing object field should receive a runtime -value during parsing. Ack validates the runtime default the first time it is -resolved and caches the result. An invalid default fails validation when used. -A valid default with a JSON-safe encoded representation exports as the JSON -Schema `default`. A present `null` is a -value, not a missing key: it fails unless the field is also nullable, in which -case `.nullable().withDefault(value)` parses it as the default too. Parsing -`null` with a `withDefault` schema directly returns the default. - -```dart compile=settings -final settingsSchema = Ack.object({ - 'theme': Ack.enumString(['light', 'dark']).withDefault('light'), - 'pageSize': Ack.integer().min(1).max(100).withDefault(20), -}); -``` - -```dart compile=use-settings -settingsSchema.parse({}); // {'theme': 'light', 'pageSize': 20} -settingsSchema.safeParse({'theme': null}); // fails: theme is not nullable -``` - -During object encoding, both a missing defaulted field and a field holding -`null` encode as the validated default, through the field's encoder. A nullable -field without a default still encodes as `null`. These default/null rules are -breaking changes in 2.0.0-beta.2. - -For a non-nullable schema such as `Ack.string().withDefault('x')`: - -| Position | Parse `null` | Encode `null` | -| --- | --- | --- | -| Root | Returns `'x'` | Fails | -| Object field | Fails. An omitted key returns `'x'`. | Encodes `'x'` | -| `Ack.map` value | Returns `'x'` | Fails | - -A `transform()` or `codec()` applied after `withDefault()` receives that -default as input. For example, an omitted object field declared as -`Ack.string().withDefault('5').transform(int.parse)` parses as the integer -`5`. During object encoding, a codec also decodes then encodes its input -default for an omitted or null field. For an optional one-way transform, -encoding leaves an omitted field absent. A nullable one-way transform -encodes explicit `null` as `null`. - -Ack takes a detached snapshot of collection defaults when you call -`withDefault`. `DefaultSchema.defaultValue` reads that snapshot before -validation. A resolved default keeps the typed, unmodifiable collections -produced by its runtime schema. Opaque collection types that require a -mutable copy receive a fresh copy each time. Collection defaults compare -by contents in schema equality. - -Defaults change the parsed result; `.optional()` only changes whether an object -field is required. - -### Schema metadata - -Attach a description with `.describe()` when the schema is also used for JSON -Schema export or adapter packages. - -```dart compile=library -final userIdSchema = Ack.string() - .uuid() - .describe('Stable identifier for a user account'); -``` - -### Custom error messages - -Built-in constraints provide default messages. APIs that accept `message:`, -such as `.matches()`, can replace that message inline. Use `.constrain()` to -provide a message for a reusable custom constraint. See [Custom error -messages](./error-handling.mdx#custom-error-messages). - -```dart compile=library -final usernameSchema = Ack.string().matches( - r'^[a-z0-9_]+$', - message: 'Use lowercase letters, numbers, and underscores only.', -); -``` - -### Custom validation logic - -Use `.constrain()` for reusable value-level checks and `.refine()` for cross-field rules — see [Custom Validation](../guides/custom-validation.mdx). - -## Code generation - -Annotate a top-level schema with `@Schemable()` to generate an immutable model, -or annotate a hand-written class with `@Schemable()` to generate its schema. -See [Model Code Generation](./typesafe-schemas.mdx) for both workflows. - -## Related guides - -- [Schema Types](./schemas.mdx) — factories, composition, and transformations -- [Validation Rules](./validation.mdx) — built-in constraints -- [Codecs](./codecs.mdx) — bidirectional boundary/runtime configuration -- [JSON Schema Integration](../guides/json-schema-integration.mdx) — exported metadata and defaults +Ack has no global configuration object. Configure behavior on each schema. + +- **Presence and defaults:** [Optional vs nullable](./schemas.mdx#optional-vs-nullable) and [Defaults](./schemas.mdx#defaults). +- **Extra properties:** [Additional properties](./schemas.mdx#additional-properties). +- **Constraints and normalizers:** [Validation Rules](./validation.mdx). +- **Custom rules and messages:** [Custom Validation](../guides/custom-validation.mdx), including [error messages](../guides/custom-validation.mdx#overriding-error-messages). +- **Value conversion:** [`transform`](../guides/custom-validation.mdx#transforming-values-with-transform) and [Codecs](./codecs.mdx). +- **Errors:** [Error Handling](./error-handling.mdx). +- **Descriptions and export:** [JSON Schema Integration](../guides/json-schema-integration.mdx). Attach a description with `.describe()`. +- **Generated models:** [Model Code Generation](./typesafe-schemas.mdx). diff --git a/docs/core-concepts/error-handling.mdx b/docs/core-concepts/error-handling.mdx index 3300f906..b94e54ed 100644 --- a/docs/core-concepts/error-handling.mdx +++ b/docs/core-concepts/error-handling.mdx @@ -6,17 +6,19 @@ When validation fails, you want to know what went wrong and where. `safeParse()` ## The `SchemaResult` object -`safeParse()` returns a `SchemaResult`. Its value is nullable — a nullable schema can succeed with `null`. - -- `result.isOk`: `true` if validation succeeded. -- `result.isFail`: `true` if validation failed. -- `result.getOrThrow()`: Returns the validated value, or throws `AckException` on failure. -- `result.getOrNull()`: Returns the validated value, or `null` on failure. -- `result.getError()`: Returns the `SchemaError` on failure, or throws `StateError` if called on a success. -- `result.getOrElse(() => defaultValue)`: Returns the validated value on success, or calls the fallback on failure. -- `result.match(onOk: (value) => ..., onFail: (error) => ...)`: Collapses both cases into a single value. -- `result.map((value) => ...)`: Transforms the success value and leaves failures untouched. -- `result.ifOk((value) { ... })` / `result.ifFail((error) { ... })`: Runs a side effect for just one case. +`safeParse()` returns a `SchemaResult`. Its value is nullable, because a nullable schema can succeed with `null`. + +| Method | On success | On failure | +| --- | --- | --- | +| `isOk` | `true` | `false` | +| `isFail` | `false` | `true` | +| `getOrThrow()` | Returns the value | Throws `AckException` | +| `getOrNull()` | Returns the value | Returns `null` | +| `getOrElse(() => fallback)` | Returns the value | Calls the fallback and returns its result | +| `getError()` | Throws `StateError` | Returns the `SchemaError` | +| `match(onOk: ..., onFail: ...)` | Calls `onOk` with the value | Calls `onFail` with the error | +| `map((value) => ...)` | Returns a result holding the transformed value | Returns the failure unchanged | +| `ifOk((value) { ... })` / `ifFail((error) { ... })` | `ifOk` runs the side effect | `ifFail` runs the side effect | ```dart compile=body import 'package:ack/ack.dart'; @@ -43,22 +45,23 @@ if (result.isFail) { ## Understanding `SchemaError` -`SchemaError` contains details about the validation failure. Its -`toString()` prints one `path: message` line per failure. A root error starts -with `#:`. When a callback throws, the line includes `(callback threw)`. -Built-in messages omit raw input and callback exception text, which makes -`toString()` safe to display to end users. For diagnostic logs, use -`SchemaError.toMap()` or `AckException.toJson()`. Both include the input value -and the cause's text (or `null` when there is no cause). `toJson()` preserves -the error structure and represents unsupported diagnostic values as strings. +A `SchemaError` describes one validation failure. Read its members to find what failed and where. -- `error.name`: The context name at the failure point. For a root error, this defaults to `schemaTypeName` (for example, `object` or `array`). Pass `debugName` to choose the root name. -- `error.value`: The value that failed validation. -- `error.schema`: The schema being validated against. -- `error.path`: The RFC 6901 JSON Pointer path to the failure (for example, `#/address/city`). +| Member | Meaning | +| --- | --- | +| `message` | The failure message. | +| `path` | The RFC 6901 JSON Pointer to the failure. The root is `#`. A nested path looks like `#/address/city`. | +| `name` | The context name at the failure point. For a root error, it defaults to the schema type name (for example `object` or `array`). Pass `debugName` to choose the root name. | +| `value` | The input value that failed validation. | +| `schema` | The schema that rejected the value. | +| `context` | The `SchemaContext` of the failure. Its `operation` is `SchemaOperation.parse` or `SchemaOperation.encode`. | +| `cause` | The exception a callback threw, or `null`. | +| `stackTrace` | The stack trace of that exception, or `null`. | +| `toString()` | One `path: message` line per failure. Ack never adds input values or callback exception text; a callback failure adds `(callback threw)`. Messages you write and paths built from input keys can still contain input, so review them before you show errors to users. | +| `toErrorString()` | A single `message at path: path` string. | +| `toMap()` | A map for logs. It includes `value` and `cause` text. | -A `SchemaContext.operation` is either `SchemaOperation.parse` or -`SchemaOperation.encode`. Both values are available from `package:ack/ack.dart`. +`AckException.toJson()` returns the same data as pretty-printed JSON, and keeps the error structure. It represents unsupported diagnostic values as strings. Use `toMap()` and `toJson()` for diagnostic logs, never for end-user text. ```dart compile=body final userSchema = Ack.object({ @@ -82,16 +85,14 @@ final result = userSchema.safeParse(invalidData); if (result.isFail) { final error = result.getError(); print('Error Name: ${error.name}'); // object - print('Error Path: ${error.path}'); // # for the outer error - print('Failed Value: ${error.value}'); // Example: the invalid data - print(error); // #/age and #/address/city each appear on their own line. - - // Note: The exact error structure (especially for nested errors) can vary. - // Sometimes the top-level error might be SchemaNestedError, - // and you might need to inspect its nested errors. + print('Error Path: ${error.path}'); // # + print('Failed Value: ${error.value}'); // the whole invalid map + print(error); // one line per failure: #/age: ... and #/address/city: ... } ``` +When an object fails on more than one property, `getError()` returns a `SchemaNestedError`. Walk its `errors` to reach each failure. Each child has its own `path`. See [`SchemaNestedError`](#schemanestederror). + ## Error types Each `SchemaError` subtype carries specific information about why validation failed. @@ -208,9 +209,7 @@ For example, `Ack.datetime()` rejects a non-UTC `DateTime` with that type. ### Working with error types -Switch exhaustively on `SchemaError` by covering the error types below. -When listing the public concrete `AckSchema` types in a switch, include a -fallback branch for other implementations, including imported schemas. +Switch exhaustively on `SchemaError` by covering the error types above. ```dart compile=error-data final result = schema.safeParse(data); @@ -235,38 +234,9 @@ if (result.isFail) { } ``` -## Displaying errors in UI (Flutter example) - -In a `TextFormField` validator, return the error string directly: - -```dart compile=field-validator -// Inside TextFormField validator -validator: (value) { - final result = someSchema.safeParse(value); - if (result.isFail) { - return result.getError().message; - } - return null; -} -``` - -*See the [Form Validation Guide](../guides/flutter-form-validation.mdx) for details.* +## Showing errors in a UI -## Custom error messages - -Built-in constraints ship with default messages. For a custom message, pass `message:` to `.refine()`, or attach a constraint with `.constrain(..., message: ...)` — see [Custom Validation](../guides/custom-validation.mdx). - -```dart compile=body -final schema = Ack.string().refine( - (value) => value.startsWith('ACK_'), - message: 'Value must start with ACK_', -); - -final result = schema.safeParse('nope'); -if (result.isFail) { - print(result.getError().message); // Value must start with ACK_ -} -``` +To show errors in Flutter form fields, see the [Flutter form validation guide](../guides/flutter-form-validation.mdx). To change a message, see [Overriding error messages](../guides/custom-validation.mdx#overriding-error-messages). ## Next steps diff --git a/docs/core-concepts/json-serialization.mdx b/docs/core-concepts/json-serialization.mdx index f02273d3..57d771be 100644 --- a/docs/core-concepts/json-serialization.mdx +++ b/docs/core-concepts/json-serialization.mdx @@ -2,23 +2,17 @@ title: JSON Serialization --- -Ack validates decoded JSON at your application boundary. On the way back out, -plain schemas produce JSON-native Dart values directly, while -[codecs](./codecs.mdx) encode rich runtime values such as `DateTime` and `Uri` -back to their wire representation. +Ack validates JSON after you decode it, and checks values before you encode them. Ack does not parse JSON text. Use `dart:convert` for that. ## Validating JSON data -Validating incoming JSON data involves two steps: - -1. **Decode JSON:** Use `dart:convert` to parse the JSON string into a Dart object (usually `Map` or `List`). -2. **Validate:** Pass the decoded object to your [Ack schema](./schemas.mdx)'s `safeParse()` method. +1. Decode the JSON string with `jsonDecode`. +2. Pass the decoded object to the schema's `safeParse()`. ```dart compile=serialization import 'dart:convert'; import 'package:ack/ack.dart'; -// Define userSchema using correct Ack API final userSchema = Ack.object({ 'name': Ack.string(), 'age': Ack.integer().min(0), @@ -26,28 +20,20 @@ final userSchema = Ack.object({ }); void processApiResponse(String jsonString) { - // 1. Decode JSON string into a Dart object. - // jsonDecode returns an unknown structure until the schema validates it. - Object? jsonData; + final Object? jsonData; try { jsonData = jsonDecode(jsonString); - } catch (e) { + } on FormatException catch (e) { print('Failed to decode JSON: $e'); return; } - // 2. Validate the decoded data against your defined schema. final result = userSchema.safeParse(jsonData); if (result.isOk) { - // Structure and types are valid. - final validDataMap = result.getOrThrow()!; - print('Valid JSON received: $validDataMap'); - - // Pass the validated map to your own model layer, - // or use an Ack-generated model (see next section). + final validData = result.getOrThrow()!; + print('Valid JSON received: $validData'); } else { - // Handle validation errors (see the Error Handling guide). print('Invalid JSON data: ${result.getError()}'); } } @@ -55,56 +41,14 @@ void processApiResponse(String jsonString) { // Example Usage processApiResponse('{"name": "Alice", "age": 30, "email": "alice@example.com"}'); processApiResponse('{"name": "Bob", "age": -5}'); // Invalid: age fails min(0) -processApiResponse('{"age": 25}'); // Invalid: missing required field 'name' processApiResponse('not valid json'); // Decoding error ``` -*Learn more about [Error Handling](./error-handling.mdx).* - -## Working with validated data - -After successful validation, `result.getOrThrow()` returns a `Map` whose structure and types match your schema. You can work with it directly, pass it into your own model class, or parse it into a generated immutable model: - -```dart compile=serialized-map -final result = userSchema.safeParse(jsonData); - -if (result.isOk) { - final validData = result.getOrThrow()!; - - // Option 1: Work directly with the validated Map - final name = validData['name'] as String; - final age = validData['age'] as int; - - // Option 2: Pass the validated map into your own model layer - // - Constructor: User(name: validData['name'], age: validData['age']) - // - generated model: User.parse(validData) - // - freezed: User.fromJson(Map.from(validData)) - // - dart_mappable: UserMapper.fromMap(validData) - // - Manual factory: User.fromMap(validData) -} -``` - -## Parsing JSON into generated models - -Once a schema is annotated with `@Schemable()` (see [Model Code Generation](./typesafe-schemas.mdx) for setup), parse JSON into a generated immutable model. Public `fromJson` / `toJson` cross the source Ack schema and map the validated runtime value directly onto stored fields. - -```dart compile=serialized-model -import 'dart:convert'; - -final jsonData = jsonDecode('{"name": "Alice", "email": "alice@example.com"}'); -final result = User.safeParse(jsonData); - -if (result.isOk) { - final user = result.getOrThrow()!; - print(user.name); // typed String - print(user.email); // typed String? -} -``` +A successful result is a `Map` that matches the schema. To get typed fields, annotate the schema with `@Schemable()` and parse into a generated immutable model. See [Model Code Generation](./typesafe-schemas.mdx). To read errors, see [Error Handling](./error-handling.mdx). ## Encoding validated data -For schemas whose runtime values are already JSON-native (`String`, `num`, -`bool`, `List`, `Map`, and `null`), pass the validated value to `jsonEncode`: +`jsonEncode` writes Dart values as they are. Pass it the validated value directly only when the schema has no codec, `transform`, `Ack.enumValues`, or `Ack.instance`: then the runtime value already has the wire shape. ```dart compile=serialized-map import 'dart:convert'; @@ -117,40 +61,8 @@ final result = userSchema.safeParse({ if (result.isOk) { final validData = result.getOrThrow()!; - final jsonString = jsonEncode(validData); - print(jsonString); + print(jsonEncode(validData)); } ``` -When a schema decodes boundary values into richer Dart types, encode through -the schema before calling `jsonEncode`. This applies each codec in the nested -structure and restores the JSON-safe boundary shape: - -```dart compile=body -import 'dart:convert'; - -final eventSchema = Ack.object({ - 'name': Ack.string(), - 'startsAt': Ack.datetime(), -}); - -final event = eventSchema.parse({ - 'name': 'Launch', - 'startsAt': '2026-01-15T14:00:00Z', -}); - -final boundaryData = eventSchema.encode(event); -final jsonString = jsonEncode(boundaryData); -``` - -Use `safeEncode()` when you want a `SchemaResult` instead of an exception. -See [Codecs](./codecs.mdx) for runtime invariants and custom bidirectional -conversions. - -## Key considerations - -- **`dart:convert`:** Use `jsonDecode` and `jsonEncode` for JSON text. Ack - validates values and encodes codec runtime values back to their boundary - representation. -- **Type safety:** `jsonDecode` produces `dynamic`, but successful validation guarantees the structure and types of the resulting `Map`. -- **Model conversion:** After validation, how you convert the validated map into an app model is up to you. Generated models parse and encode through an Ack schema and map that runtime value directly onto stored fields in a single `.g.dart` part. `@Schemable()` on a top-level schema starts from the schema, while `@Schemable()` on a class starts from your class. +When the runtime type differs from the wire type, as with a codec, `Ack.datetime()`, or `Ack.enumValues`, call `schema.encode(value)` first so the schema restores the wire form, then pass the result to `jsonEncode`. A value can look JSON-safe and still have the wrong wire type: a string-to-int codec turns `"42"` into `42`. Use `safeEncode()` for a `SchemaResult` instead of an exception. A one-way `transform` and `Ack.instance` have no wire encoder; convert those values yourself, or use a codec instead. See [Codecs](./codecs.mdx) for built-in codecs and custom bidirectional conversions. diff --git a/docs/core-concepts/schemas.mdx b/docs/core-concepts/schemas.mdx index 2bd3a270..4e3cf38a 100644 --- a/docs/core-concepts/schemas.mdx +++ b/docs/core-concepts/schemas.mdx @@ -2,43 +2,22 @@ title: Schemas --- -A schema describes the shape your data should have. You build one with the `Ack` factory, then validate input against it. This page tours every schema type and how to compose them. +A schema describes the shape your data should have. You build one with the `Ack` factory, then validate input against it. This page tours the schema types and how to compose them. For a first run, see the [Quickstart](../getting-started/quickstart-tutorial.mdx). ```dart compile=body -import 'package:ack/ack.dart'; - -// Define schema final userSchema = Ack.object({ 'name': Ack.string().minLength(2), 'age': Ack.integer().min(0), - 'email': Ack.string().email(), -}); - -// Validate data -final result = userSchema.safeParse({ - 'name': 'John', - 'age': 30, - 'email': 'john@example.com', }); -if (result.isOk) { - final validData = result.getOrThrow()!; - print('Valid: ${validData['name']}'); -} else { - print('Error: ${result.getError()}'); -} +final result = userSchema.safeParse({'name': 'John', 'age': 30}); +print(result.isOk); // true ``` -Parse and encode allow up to 100 nested collections along each path they -traverse, including the outermost collection. A depth violation reports a -`max_collection_depth` constraint failure at the offending path. Recursive -`Ack.lazy` calls count toward the lazy schema's own `maxDepth` and restart -the collection limit. A single recursive reference can traverse up to -`maxDepth * 100` nested collections through its invocations. The Dart call -stack can overflow before either configured limit is reached. - ## Schema types +The types below cover JSON values. Codec types (`date`, `datetime`, `duration`, `uri`) return Dart runtime values and live on the [Codecs](./codecs.mdx) page. + ### String ```dart compile=library @@ -66,12 +45,17 @@ enum Role { admin, user, guest } final roleSchema = Ack.enumValues(Role.values); ``` -> **`Ack.string().date()` vs `Ack.date()`:** `Ack.string().date()` checks the -> format and keeps the value a `String`. [`Ack.date()`](./codecs.mdx) (a codec) -> validates the same format but returns a `DateTime`. The same applies to -> `Ack.string().datetime()` vs `Ack.datetime()`, except announced leap seconds: -> the string schema preserves them, while the codec rejects them because Dart's -> `DateTime` cannot represent `:60`. +Use `Ack.string().date()` to keep a `String`. Use the [`Ack.date()` codec](./codecs.mdx) to get a `DateTime`. + +**Factories for fixed values.** `Ack.enumString` and `Ack.literal` are `Ack` factories, not fluent methods. + +- `Ack.enumString(List allowedValues)` creates a `StringSchema` that accepts only values in `allowedValues`. Use it for ad-hoc string lists. Prefer `Ack.enumValues(MyEnum.values)` when a Dart enum exists. +- `Ack.literal(String value)` creates a `StringSchema` that requires an exact string match. + +```dart compile=expressions +Ack.enumString(['active', 'inactive', 'pending']) +Ack.literal('admin') +``` ### Number @@ -152,20 +136,7 @@ final userSchema = Ack.object({ }); ``` -**Working with validated data:** - -```dart compile=read-nested-object -final result = userSchema.safeParse(data); - -if (result.isOk) { - final validData = result.getOrThrow()!; - - // Type cast when accessing - final name = validData['name'] as String; - final address = validData['address'] as Map; - final city = address['city'] as String; -} -``` +To read values from a validated object, see [JSON serialization](./json-serialization.mdx). ### Union types @@ -218,6 +189,7 @@ referenced rather than inlined forever. `maxDepth` defaults to `100`, must be at least `1`, and returns a validation failure when parsing, runtime validation, or encoding exceeds the limit. Because the limit is runtime-only and cannot be represented by `$ref`, exported schema models warn that it was omitted. +Each `Ack.lazy` call counts toward its own `maxDepth` and restarts the 100-collection limit. A single recursive reference can traverse up to `maxDepth * 100` nested collections. The Dart call stack can overflow before either limit is reached. ### Any @@ -295,8 +267,13 @@ userSchema.safeParse({'name': 'John', 'bio': null}); userSchema.safeParse({'name': 'John', 'bio': 'Developer'}); ``` -**`.withDefault(value)`** — A missing field parses as `value`. A present `null` -still fails unless the field is nullable: +> **Distinguishing omitted vs. `null` in generated models (`JsonMaybe`):** In raw map schemas (`Ack.object`), `map.containsKey('bio')` tells you whether `'bio'` was omitted or set to `null`. In class-first `@Schemable()` models, declare the field as `JsonMaybe` (`JsonAbsent` when omitted, `JsonValue(null)` when explicitly `null`, `JsonValue('...')` when present) so `PATCH` requests round-trip both states accurately. See [Model Code Generation](./typesafe-schemas.mdx). + +## Defaults + +Use `.withDefault(value)` when a missing object field should receive a runtime value during parsing. A present `null` is a value, not a missing key. It fails unless the field is also nullable. `.nullable().withDefault(value)` parses a present `null` as the default. Parsing `null` with a `withDefault` schema directly returns the default. + +`withDefault` does not validate the default when you call it. Ack validates the default the first time it is used and caches the result. An invalid default fails validation at that point. A valid default with a JSON-safe encoded representation exports as the JSON Schema `default`. ```dart compile=body final userSchema = Ack.object({ @@ -310,16 +287,37 @@ userSchema.safeParse({'role': null}); // ❌ role is not nullable userSchema.encode({'role': null, 'theme': null}); // defaults: member and light ``` -In 2.0.0-beta.2, object encoding uses the default for both missing and null -defaulted fields. Parsing a present null still requires a nullable property. +```dart compile=settings +final settingsSchema = Ack.object({ + 'theme': Ack.enumString(['light', 'dark']).withDefault('light'), + 'pageSize': Ack.integer().min(1).max(100).withDefault(20), +}); +``` -> **Distinguishing omitted vs. `null` in generated models (`JsonMaybe`):** In raw map schemas (`Ack.object`), `map.containsKey('bio')` tells you whether `'bio'` was omitted or set to `null`. In class-first `@Schemable()` models, declare the field as `JsonMaybe` (`JsonAbsent` when omitted, `JsonValue(null)` when explicitly `null`, `JsonValue('...')` when present) so `PATCH` requests round-trip both states accurately. See [Model Code Generation](./typesafe-schemas.mdx). +```dart compile=use-settings +settingsSchema.parse({}); // {'theme': 'light', 'pageSize': 20} +settingsSchema.safeParse({'theme': null}); // fails: theme is not nullable +``` + +Defaults change the parsed result. `.optional()` only changes whether an object field is required. + +During object encoding, both a missing defaulted field and a field holding `null` encode as the validated default, through the field's encoder. A nullable field without a default still encodes as `null`. For a non-nullable schema such as `Ack.string().withDefault('x')`: + +| Position | Parse `null` | Encode `null` | +| --- | --- | --- | +| Root | Returns `'x'` | Fails | +| Object field | Fails. An omitted key returns `'x'`. | Encodes `'x'` | +| `Ack.map` value | Returns `'x'` | Fails | + +A `transform()` or `codec()` applied after `withDefault()` receives that default as input. For example, an omitted object field declared as `Ack.string().withDefault('5').transform(int.parse)` parses as the integer `5`. During object encoding, a codec decodes and then encodes its input default for an omitted or null field. For an optional one-way transform, encoding leaves an omitted field absent. A nullable one-way transform encodes explicit `null` as `null`. + +Ack takes a detached snapshot of collection defaults when you call `withDefault`. `DefaultSchema.defaultValue` reads that snapshot before validation. A resolved default keeps the typed, unmodifiable collections produced by its runtime schema. Opaque collection types that require a mutable copy receive a fresh copy each time. Collection defaults compare by contents in schema equality. ## Object schema operations -Shape an object before calling `refine()`. The `pick`, `omit`, `partial`, -`merge`, and `extend` methods throw `ArgumentError` if an operand already has -an object-level refinement. When merging, the receiving schema determines the +Object shape operations (`pick`, `omit`, `partial`, `merge`, `extend`) reject +refined operands and throw `ArgumentError`. Shape the object first, then call +`refine()`. When merging, the receiving schema determines the additional-property policy. Apply `strict()` or `passthrough()` to the result to set it explicitly. @@ -433,76 +431,22 @@ passthrough.safeParse({'id': '1', 'name': 'John', 'role': 'admin'}); // ✅ Pass ## Custom validation -### Refinements - -Add custom validation logic: - -```dart compile=body -// Password confirmation -final passwordSchema = Ack.object({ - 'password': Ack.string().minLength(8), - 'confirmPassword': Ack.string(), -}).refine( - (data) => data['password'] == data['confirmPassword'], - message: 'Passwords must match', -); - -// Business logic validation -final orderSchema = Ack.object({ - 'items': Ack.list(Ack.object({ - 'price': Ack.double(), - 'quantity': Ack.integer(), - })), - 'total': Ack.double(), -}).refine( - (order) { - final items = order['items'] as List; - final calculatedTotal = items.fold(0, (sum, item) { - final itemMap = item as Map; - final price = itemMap['price'] as double; - final qty = itemMap['quantity'] as int; - return sum + (price * qty); - }); - final total = order['total'] as double; - return (calculatedTotal - total).abs() < 0.01; - }, - message: 'Total must match sum of items', -); -``` - -### Transformations - -Transform validated data after parsing: - -```dart compile=body -// Transform to uppercase. The callback receives the non-null validated -// runtime value; nullable handling happens on the surrounding schema. -final upperSchema = Ack.string().transform((s) => s.toUpperCase()); - -// Add computed fields -final userWithAgeSchema = Ack.object({ - 'name': Ack.string(), - 'birthYear': Ack.integer(), -}).transform((data) { - final birthYear = data['birthYear'] as int; - final age = DateTime.now().year - birthYear; - return {...data, 'age': age}; -}); - -// Type transformation -final dateSchema = Ack.string() - .matches(r'^\d{4}-\d{2}-\d{2}$') - .transform((s) => DateTime.parse(s)); -``` +- Cross-field rules: [`refine`](../guides/custom-validation.mdx#cross-field-rules-with-refine). +- Value conversion: [`transform`](../guides/custom-validation.mdx#transforming-values-with-transform). +- Reusable value checks: [`constrain`](../guides/custom-validation.mdx#creating-a-value-constraint). ## Validation result Every `safeParse()` returns a `SchemaResult` holding the validated value or a `SchemaError`. See [Error Handling](./error-handling.mdx) for reading values and errors. +## Limits + +Parse and encode allow up to 100 nested collections along each path they traverse, including the outermost collection. A depth violation reports a `max_collection_depth` constraint failure at the offending path. For recursive schemas, see [Recursive schemas](#recursive-schemas). + ## Next steps - **[Validation rules](./validation.mdx)**: All built-in constraints and strict parsing - **[Error handling](./error-handling.mdx)**: Handle validation errors effectively - **[Custom validation](../guides/custom-validation.mdx)**: Create custom constraints and refinements - **[JSON serialization](./json-serialization.mdx)**: Validate and transform JSON data -- **[Common recipes](../guides/common-recipes)**: Practical schema patterns +- **[Common recipes](../guides/common-recipes.mdx)**: Practical schema patterns diff --git a/docs/core-concepts/typesafe-schemas.mdx b/docs/core-concepts/typesafe-schemas.mdx index ee38fe3d..7071dbb0 100644 --- a/docs/core-concepts/typesafe-schemas.mdx +++ b/docs/core-concepts/typesafe-schemas.mdx @@ -9,7 +9,7 @@ from a Dart class, or start from a `.schema.json` document. | --- | --- | --- | | A top-level Ack schema (`final userSchema = ...`) | `@Schemable()` | Immutable `User` class, `User.schema`, `parse`/`safeParse`, `fromJson`/`toJson`, `copyWith` in `.g.dart` | | A Dart class or sealed union (`final class Account`) | `@Schemable()` | `_accountSchema` codec, `AccountSchema` facade, and `_$AccountAck` mixin in `.g.dart` | -| A JSON Schema asset (`lib/**/*.schema.json`) | `ack_generator:ack_json_schema` in `build.yaml` | `.schema.dart` + `.schema.g.dart` with typed `@Schemable()` models or validated value models | +| A JSON Schema asset (`lib/**/*.schema.json`) | `ack_generator:ack_json_schema` in `build.yaml` | `.schema.dart` with typed `@Schemable()` models (plus `.schema.g.dart`) or validated value models (no part file) | `@Schemable()`, `@AckKey`, and the `Is…`/`Has…` rule annotations (such as `@IsRequired()` and `@HasMinLength(2)`) all come from `package:ack/ack.dart` @@ -19,6 +19,20 @@ runtime type returned by factories such as `Ack.string()` and `Ack.object()`. > **Upgrading from Ack 1.x?** See the [What's New & Migration Guide](../getting-started/migration-guide.mdx) for a complete table of changes, removed 1.x annotations, and drop-in 2.0 substitutions. +## Where to find the rules + +| Question | Section | +| --- | --- | +| Which direction should I use? | [Which direction should you choose?](#which-direction-should-you-choose) | +| How does a JSON key become a Dart field name? | [Naming and reserved names](#naming-and-reserved-names) | +| How do I rename keys on the wire? | [JSON key names](#json-key-names) | +| What makes a field required, optional, nullable or defaulted? | [Presence comes from the constructor](#presence-comes-from-the-constructor) | +| Which annotations add constraints? | [Rule annotations](#rule-annotations) | +| How do unions and discriminators work? | [Schema-first unions](#schema-first-unions) and [Class-first unions](#class-first-unions) | +| How does a type own its schema (`static schema`)? | [Custom schemas and types that own their schema](#custom-schemas-and-types-that-own-their-schema) | +| How do I write a codec? | [Custom codecs](./codecs.mdx#custom-codecs) | +| How do I keep or capture unknown keys? | [Additional properties](#additional-properties) | + ## Install the generator ```bash @@ -84,13 +98,19 @@ print(account.toJson()); // validated snake_case JSON ``` The schema-first and class-first declarations may live in the same library. -Ordinary `@JsonSerializable()` classes keep their separate `.g.dart` file, -but do not put `@Schemable()` and `@JsonSerializable()` on the same class. -`name` applies only to a top-level schema. `schemaName`, `description`, -`caseStyle`, the discriminator options, `unknownProperties`, and -`captureField` apply only to a class. Generation fails when an option is set -for the other target. +Each `@Schemable()` option applies to one target. Generation fails when you set +an option for the other target. + +| Option | Schema-first (top-level schema) | Class-first (class) | +| --- | --- | --- | +| `name` | Yes | No | +| `schemaName` | No | Yes | +| `description` | No | Yes | +| `caseStyle` | No | Yes | +| `discriminatorKey`, `discriminatorValue` | No | Yes | +| `unknownProperties`, `captureField` | No | Yes | +| `schemas` | No | Yes (also on a `library;` directive) | ## Schema-first: `@Schemable()` on a top-level schema @@ -133,37 +153,19 @@ Fields may use `Ack.any()` for JSON-safe `Object` values and `Ack.map(...)` for string-keyed `Map` values. `Ack.any().nullable()` infers `Object?`, and `Ack.map(Ack.any().nullable())` infers `Map`. +An `Ack.anyOf(...)` field whose branches are all native JSON (strings, numbers, +booleans, `Ack.any()`, inline objects, and lists, maps, or unions of those) +becomes an `Object` field, also as a list item or map value. A branch must not +decode its value: `Ack.datetime()`, `Ack.enumValues(...)`, `.codec(...)`, +`Ack.instance()`, model schemas, and nullable branches are rejected. Mark the +union itself `.nullable()` instead, and use `Ack.discriminated(...)` for a union +of models. + One-way transforms cannot back a generated model because there is no encoder. -Generation also rejects nullable roots, `Ack.any()` and `Ack.map()` roots, -`Ack.anyOf()`, bare `Ack.instance()`, anonymous inline object fields, +Generation also rejects nullable roots, `Ack.any()`, `Ack.map()`, and +`Ack.anyOf()` roots, 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: @@ -184,6 +186,41 @@ final petSchema = Ack.discriminated( This generates a sealed `Pet` base plus `Cat` and `Dog` branches. +### Naming and reserved names + +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. + +| JSON key | Dart field | Type name segment | +| --- | --- | --- | +| `UserID`, `userID`, `user_id` | `userId` | `UserId` | +| `URLs` | `urls` | `Urls` | +| `address_2` | `address2` | `Address2` | +| `café`, `já_ok` | Rejected: non-ASCII letters | Rejected | + +Generation also rejects empty names, field names that start with a digit, Dart +reserved words, and keys that produce the same Dart member. For any rejected +key, use a class-first model with `@AckKey` to keep the wire key and choose +the Dart field name. + +Schema-first keys that shadow a name the generated code references are +rejected. 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. The workaround is the same: use a class-first +model with `@AckKey`. + ## Class-first: `@Schemable()` on a class Use class-first generation when the Dart class is the primary artifact. Ack @@ -247,20 +284,14 @@ Both lines are optional: if omitted, `ProfileSchema` still provides every static entry point and nested `@Schemable()` models still compose automatically. Generation rejects a `schema` static whose type produces another class. -If a framework specifically requires a factory constructor for `fromJson`, use: +If a framework requires a factory constructor for `fromJson`, use one instead +of the static field: ```dart compile=profile-factory factory Profile.fromJson(Map json) => ProfileSchema.fromJson(json); ``` -An explicit function-field type is also valid but normally unnecessary: - -```dart compile=profile-typed-member -static final Profile Function(Map) fromJson = - ProfileSchema.fromJson; -``` - Use `@Schemable(description: ...)` and a single-line `@description` tag in a `///` or `/** */` doc comment on classes, fields, or constructor parameters to export schema descriptions. Only the text after the tag, on the same line, is @@ -327,14 +358,13 @@ final class Profile with _$ProfileAck { | Optional `T?` | `.optional().nullable()` | May be omitted | Omitted when null | | Constructor default, such as `this.tools = const []` | `.withDefault(const [])` | A missing key uses the default; JSON `null` requires `T?` | A null stored value encodes as the default | -In 2.0.0-beta.2, a constructor default fills an omitted key. A present JSON -`null` is rejected for `T`, including defaulted fields. Declare `T?` to accept -it, or use the existing `@IsNotNull()` to reject it on a nullable field. -With `String? label` and `this.label = 'fallback'`, missing input and JSON -`null` both parse as `'fallback'`. A directly constructed `label: null` now -encodes as `'fallback'` too. With `this.label = null`, missing input and JSON -`null` parse as null and the encoded object keeps the key with a null value. -These changes are breaking relative to beta.1. +A constructor default fills an omitted key. A present JSON `null` is rejected +for `T`, including defaulted fields. Declare `T?` to accept it, or use +`@IsNotNull()` to reject it on a nullable field. With `String? label` and +`this.label = 'fallback'`, missing input and JSON `null` both parse as +`'fallback'`. A directly constructed `label: null` encodes as `'fallback'` too. +With `this.label = null`, missing input and JSON `null` parse as null and the +encoded object keeps the key with a null value. Presence and nullability rules also apply to fields backed by registered or type-owned custom schemas. A custom schema's own default does not become a @@ -373,9 +403,12 @@ and `{"label": null}` fails. Encoding omits a null Dart value. Here `@IsOptional()` only restates what the constructor already infers; `@IsNotNull()` is the annotation that changes null acceptance. +### Inferred field types + The generator infers `String`, `bool`, numeric types, `DateTime`, `Uri`, -`Duration`, enums, nested lists, and sets. Sets use a list codec. Open JSON -values use the Dart types you already write: +`Duration`, enums, nested lists, and sets. A generated `Set` field rejects +duplicate JSON values and exports `uniqueItems: true`. Open JSON values use the +Dart types you already write: | Dart field | Inferred schema | | --- | --- | @@ -412,6 +445,14 @@ Map values may be `null` only when the value type is nullable. `List` stays rejected because `Ack.list` has no nullable-item contract. Parsed `Object` values are recursively unmodifiable, like other stored collections. +A field whose schema is `Ack.preserveBoundary(...)` stores the JSON of a +codec-bearing object, map, or discriminated union. Ack validates the value with +the full typed schema but keeps the wire value, so a field over a preserved +object is a `Map`. Put `withDefault(...)` outside the preserved +schema; a default inside it does not apply. + +### Rule annotations + Rule annotations follow the field type. `Is…` names what the value is, and `Has…` names a bound or property it has: @@ -421,13 +462,14 @@ Rule annotations follow the field type. `Is…` names what the value is, and - string formats: `@IsUri`, `@IsUuid`, `@IsDate`, `@IsDateTime`, `@IsIp` (`version: 4` or `6` for one family); - lists and sets: `@IsNotEmpty`, `@HasMinItems`, `@HasMaxItems`, `@HasUniqueItems`. - `@HasMatch` is the annotation form of `Ack.string().matches(...)`. Like `matches()`, it is not anchored: the pattern may match anywhere in the string, so use `^...$` for a full-string match. Numeric constraint values must be finite. On a `Set>` field the collection constraints apply to the outer set. +### JSON key names + Use `caseStyle` for model-wide JSON names. Supported values are `none`, `snake`, `kebab`, `pascal`, and `screamingSnake`. Use `@AckKey('wire_name')` on the field or primary constructor parameter for @@ -448,8 +490,9 @@ its schema in the following priority order: `AckSchema` variable, getter, or zero-argument function in the current library. -A type you own can declare its schema once, as a static member named -`schema`. Any field of that type then resolves to it with no annotation on +To write the codec for such a type, see +[Custom codecs](./codecs.mdx#custom-codecs). A type you own can declare its +schema once, as a static member named `schema`. Any field of that type then resolves to it with no annotation on the field, also as a `List` or `Set` item and as a `Map` value: ```dart compile=section @@ -579,21 +622,30 @@ The generated parse and encode helpers, including `toJson()` and 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. +A class with a refinement has two schemas: + +- `XSchema.schema` (and `wireSchema`) is the generated schema without the + class's own refinement. A class-owned schema starts from it, for example + `static final schema = RangeSchema.schema.refine(...)`. +- `X.schema` is the full schema. `XSchema.parse`, `safeParse`, `fromJson`, + `encode`, `safeEncode`, `toJsonSchema()`, and `toSchemaModel()` use it when + the class declares one. Parsing and encoding apply the refinement, and the + export includes the schema's description and exportable constraints. + Refinements never export. To compose the model into another schema with its + refinement, use `X.schema`. + +A class-owned `schema` must not call the facade's own `parse`, `safeParse`, or +`encode`, for example in a codec callback. That recurses forever. Build it from +`XSchema.schema` instead. A sealed-union base or branch may declare +`static schema` only as a direct alias of its generated facade's schema (see +[Class-first unions](#class-first-unions)). ### 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. +A union base or branch may declare `static schema` only as a direct alias of +its 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. Annotate a sealed base with a discriminator key. Concrete branches in the same library are included automatically, and inherited constructor fields may use @@ -616,10 +668,19 @@ final class const Dog({required super.id, required final String breed}) The base and every concrete branch receive facades (`PetSchema`, `CatSchema`, and `DogSchema`), including branches without their own `@Schemable` annotation. -Without an explicit `discriminatorValue`, the wire value is the verbatim class -name (`Dog` above). Set explicit values when the wire format must remain stable -through class renames. Class-first `anyOf` and value roots are not supported; -use schema-first generation for those shapes. +Set explicit `discriminatorValue` values when the wire format must remain stable +through class renames. Defaults for the union options: + +| Option | Default | +| --- | --- | +| `discriminatorKey` | None. Set it on the sealed base. | +| `discriminatorValue` | The verbatim class name (`Dog` above). | +| `caseStyle` on a branch | The sealed base's `caseStyle`, including branches with `discriminatorValue`. Set the branch's own `caseStyle` to override it; `AckCaseStyle.none` keeps the branch's Dart field names. | +| `caseStyle` elsewhere | `AckCaseStyle.none` | + +A class-first model cannot be an `anyOf` union or a value root. Use a sealed +class for a union of models, an `Object` field for any JSON value, or a +schema-first model with an `Ack.anyOf(...)` field of native JSON branches. ### Additional properties @@ -705,19 +766,6 @@ 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 compile=json-key-field -@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 @@ -748,12 +796,20 @@ targets: 4. Put `@Schemable()` on a top-level schema or on a class. 5. Run `dart run build_runner build`. -## Migrating from 1.x +## Interop + +Ordinary `@JsonSerializable()` classes keep their separate `.g.dart` file. Do +not put `@Schemable()` and `@JsonSerializable()` on the same class. + +### `json_serializable` -- Remove `ack_annotations`, `json_serializable`, and `json_annotation` from `pubspec.yaml` (unless used by non-Ack classes), and import `package:ack/ack.dart`. -- Replace `part '.ack.dart';` + `part '.ack.g.dart';` with a single `part '.g.dart';`. -- Replace `@AckType()`, `@AckInfer()`, and `@AckModel()` with `@Schemable()`. -- Replace top-level presence and constraint annotations (`@Optional`, `@Required`, `@NotNull`, `@Min`, `@Max`, `@MinLength`, `@Matches`, `@Email`, `@DateTime`, etc.) with the rule annotations (`@IsOptional`, `@IsRequired`, `@IsNotNull`, `@HasMin`, `@HasMax`, `@HasMinLength`, `@HasMatch`, `@IsEmail`, `@IsDateTime`, etc.). -- Replace `@JsonKey(name: '...')` on `@Schemable` fields with `@AckKey('...')`. +When a `@JsonSerializable()` class holds an Ack model, specify the converters +on that field. For an Ack class with an `AccountSchema` facade, use -See the [What's New & Migration Guide](../getting-started/migration-guide.mdx) for the complete substitution tables and side-by-side before/after examples. +```dart compile=json-key-field +@JsonKey(fromJson: AccountSchema.fromJson, toJson: AccountSchema.encode) +final Account account; +``` + +Use `JsonKey` from `package:json_annotation/json_annotation.dart` on the +container field. diff --git a/docs/core-concepts/validation.mdx b/docs/core-concepts/validation.mdx index e3f81bf0..8850dab2 100644 --- a/docs/core-concepts/validation.mdx +++ b/docs/core-concepts/validation.mdx @@ -4,15 +4,13 @@ title: Validation Rules Constraints turn "a string" into "an email between 2 and 50 characters." Chain them onto any schema — each comes with a sensible default error message, and you can supply your own (see [Custom Validation](../guides/custom-validation.mdx)). -## Common constraints +## `nullable()` and `optional()` -### `nullable()` and `optional()` +`.nullable()` lets a present field hold `null`. `.optional()` lets a field be omitted. They are not constraints. See [Optional vs nullable](./schemas.mdx#optional-vs-nullable). -`.nullable()` lets a present field hold `null`; `.optional()` lets it be omitted. These are field-presence modifiers rather than constraints — see [Optional vs nullable](./schemas.mdx#optional-vs-nullable). +## Custom constraints -### `constrain(Constraint constraint, {String? message})` - -Applies a custom `Constraint` that also implements `Validator`. See the [Custom Validation](../guides/custom-validation.mdx) guide. +Use `constrain(Constraint constraint, {String? message})` to apply a custom `Constraint` that also implements `Validator`. See [Creating a value constraint](../guides/custom-validation.mdx#creating-a-value-constraint). ## String constraints @@ -69,19 +67,35 @@ Ack.string().contains('.') // Matches "a.b" Ack.string().matches(r'[A-Z]') // Matches "Password" ``` -### `email()` +### `startsWith(String prefix)` +Requires the string to start with `prefix`. +```dart compile=expressions +Ack.string().startsWith('https://') +``` + +### `endsWith(String suffix)` +Requires the string to end with `suffix`. +```dart compile=expressions +Ack.string().endsWith('.dart') +``` + +### String formats + +These constraints check the format of the string. + +#### `email()` Requires a valid email address format. ```dart compile=expressions Ack.string().email() ``` -### `date()` +#### `date()` Requires a valid date string in `YYYY-MM-DD` format. ```dart compile=expressions Ack.string().date() ``` -### `datetime()` +#### `datetime()` Requires a valid ISO 8601 date-time string with a timezone. Announced RFC 3339 leap seconds are accepted and preserved because this schema returns the input `String`. The `Ack.datetime()` codec rejects leap seconds because Dart's @@ -90,7 +104,7 @@ leap seconds are accepted and preserved because this schema returns the input Ack.string().datetime() ``` -### `time()` +#### `time()` Requires a 24-hour time string in `HH:MM:SS` format with no offset or fractional seconds. JSON Schema export uses a `pattern` for this same rule. The constraint key is `string_time`. @@ -98,7 +112,7 @@ The constraint key is `string_time`. Ack.string().time() ``` -### `uri()` +#### `uri()` Requires a valid absolute URI with a scheme and host. This is the network-URI subset Ack accepts, rather than every relative or non-host URI permitted by RFC 3986. @@ -106,51 +120,25 @@ subset Ack accepts, rather than every relative or non-host URI permitted by RFC Ack.string().uri() ``` -### `uuid()` +#### `uuid()` Requires a valid UUID per RFC 4122. ```dart compile=expressions Ack.string().uuid() ``` -### `ipv4()` +#### `ipv4()` Requires a valid IPv4 address. ```dart compile=expressions Ack.string().ipv4() ``` -### `ipv6()` +#### `ipv6()` Requires a valid IPv6 address. ```dart compile=expressions Ack.string().ipv6() ``` - - -### `Ack.enumString(List allowedValues)` -An `Ack` factory (not a fluent method) that creates a `StringSchema` accepting only values in `allowedValues`. Use for ad-hoc string lists; prefer `Ack.enumValues(MyEnum.values)` when a Dart enum exists. -```dart compile=expressions -Ack.enumString(['active', 'inactive', 'pending']) -``` - -### `Ack.literal(String value)` -An `Ack` factory (not a fluent method) that creates a `StringSchema` requiring an exact string match. -```dart compile=expressions -Ack.literal('admin') -``` - -### `startsWith(String prefix)` -Requires the string to start with `prefix`. -```dart compile=expressions -Ack.string().startsWith('https://') -``` - -### `endsWith(String suffix)` -Requires the string to end with `suffix`. -```dart compile=expressions -Ack.string().endsWith('.dart') -``` - -### `ip({int? version})` +#### `ip({int? version})` Requires a valid IP address. Set `version` to `4` or `6` to restrict the version. ```dart compile=expressions Ack.string().ip() // Any IP (v4 or v6) @@ -158,15 +146,16 @@ Ack.string().ip(version: 4) // IPv4 only Ack.string().ip(version: 6) // IPv6 only ``` +For `Ack.enumString` and `Ack.literal`, see [String](./schemas.mdx#string). + ## String normalizers These methods live directly on `StringSchema` and normalize the string in declaration order alongside constraints during both `parse` and `encode`. Because they return `StringSchema`, you can continue chaining string -constraints (`Ack.string().trim().minLength(2)`), use them inside `@Schemable()` -models, and export the string type. The export of -`Ack.string().trim().minLength(2)` is `{ "type": "string" }` because the minimum -applies to the trimmed text. Keep the native schema for that validation. +constraints (`Ack.string().trim().minLength(2)`) and use them inside `@Schemable()` +models. JSON Schema export omits constraints that apply to trimmed text; see +[JSON Schema integration](../guides/json-schema-integration.mdx). ### `trim()` Removes leading and trailing whitespace on parse and encode. @@ -358,35 +347,18 @@ stringOrNumber.safeParse(42); // ✅ Matches integer branch ### Converting boundary types -When your boundary payload uses a different shape than your runtime model (for example, ISO strings → `DateTime`, or `"true"`/`"false"` → `bool`), express the conversion explicitly with [`transform`](./schemas.mdx#transformations) or a `codec`: - -```dart compile=body -// Boundary "true"/"false" string → runtime bool -final boolFromString = Ack.enumString(['true', 'false']) - .transform((s) => s == 'true'); - -boolFromString.safeParse('true'); // ✅ runtime value: true -boolFromString.safeParse('false'); // ✅ runtime value: false -boolFromString.safeParse(true); // ❌ FAIL: string schema rejects bool -``` - -Use `schema.codec(decode: ..., encode: ...)` when you also need a reversible encode path back to the boundary type. +When your boundary payload uses a different shape than your runtime model (for example, ISO strings to `DateTime`, or `"true"`/`"false"` to `bool`), convert explicitly. Use [`transform`](../guides/custom-validation.mdx#transforming-values-with-transform) for one-way conversion, or a [codec](./codecs.mdx) when you also need a reversible encode path. ## Combining constraints -You can chain multiple constraints. Ack evaluates them in the order you apply them. +Constraints run in the order you apply them. Here `trim()` runs first, so the length checks count the trimmed text. ```dart compile=body final usernameSchema = Ack.string() - .minLength(3) // First: check min length - .maxLength(20) // Second: check max length - .matches(r'^[a-z0-9_]+$') // Third: require only lowercase letters, digits, or underscores - .notEmpty(); // Redundant if minLength(>0) is used, but illustrates chaining - -final quantitySchema = Ack.integer() - .min(1) // Must be at least 1 - .max(100) // Must be at most 100 - .multipleOf(1); // Must be an integer (redundant for Ack.integer) + .trim() + .minLength(3) + .maxLength(20) + .matches(r'^[a-z0-9_]+$'); ``` ## Next steps diff --git a/docs/getting-started/installation.mdx b/docs/getting-started/installation.mdx index 76061efc..48e85894 100644 --- a/docs/getting-started/installation.mdx +++ b/docs/getting-started/installation.mdx @@ -4,6 +4,13 @@ title: Installing Ack Ack is a pure-Dart package with no required build step. Add the core library — and, optionally, the code generator for immutable models. +## Requirements + +- Dart SDK: `>=3.13.0 <4.0.0` for all Ack packages. Dart 3.13 adds the + primary constructors that the class-first examples use. +- Flutter: `>=3.47.0` (which bundles Dart 3.13.0) for Flutter apps and when + using `ack_firebase_ai`. + ## Add to your project Add Ack to your project using the Dart CLI: @@ -17,13 +24,7 @@ flutter pub add ack:^2.0.0-beta.3 ``` These docs describe the 2.0.0-beta.3 prerelease. An unversioned -`dart pub add ack` selects the latest stable release instead. You can also add -the constraint to your `pubspec.yaml`: - -```yaml -dependencies: - ack: ^2.0.0-beta.3 -``` +`dart pub add ack` selects the latest stable release instead. ## Optional code generator @@ -34,59 +35,18 @@ add `ack` and the generator package: dart pub add ack:^2.0.0-beta.3 dev:ack_generator:^2.0.0-beta.3 dev:build_runner ``` -Or add them to your `pubspec.yaml`: - -```yaml -dependencies: - ack: ^2.0.0-beta.3 - -dev_dependencies: - ack_generator: ^2.0.0-beta.3 - build_runner: ^2.4.0 -``` - -The generator works in both directions with one annotation, `@Schemable()`, -and a set of `Is…`/`Has…` rule annotations such as `@HasMinLength(2)`, all -exported from `package:ack/ack.dart`. `@Schemable()` on a top-level schema -generates an immutable model. `@Schemable()` on a hand-written class generates -a public `Schema` facade and JSON helpers. There is no `@AckSchema()` annotation; `AckSchema` is the runtime -schema type. - -```dart compile=model -import 'package:ack/ack.dart'; - -part 'user.g.dart'; - -@Schemable() -final userSchema = Ack.object({ - 'name': Ack.string(), - 'email': Ack.string().email(), -}); - -@Schemable() -final class const Account({@HasMinLength(2) required final String name}) - with _$AccountAck { - static final schema = AccountSchema.schema; - static final fromJson = AccountSchema.fromJson; -} -``` - -Run the generator: +Annotate a class or a top-level schema with `@Schemable()`. +There is no `@AckSchema()` annotation. Add a `part` directive named after the +source file, for example `part 'user.g.dart';` in `user.dart`. Then run the +generator: ```bash dart run build_runner build ``` -See [Model Code Generation](../core-concepts/typesafe-schemas.mdx) for working -tutorials, supported shapes, and guidance on choosing a direction. +See [Model Code Generation](../core-concepts/typesafe-schemas.mdx) for +examples, supported shapes, and guidance on choosing a direction. ## Next step -Import `package:ack/ack.dart` and you're ready — the [Quickstart Tutorial](./quickstart-tutorial.mdx) takes you from your first schema to handling every validation outcome. Upgrading from Ack 1.x? See the [What's New & Migration Guide](./migration-guide.mdx) for a complete table of changes and drop-in substitutions. - -## Requirements - -- Dart SDK: `>=3.13.0 <4.0.0` for all Ack packages. Dart 3.13 adds the - primary constructors that the class-first examples use. -- Flutter: `>=3.47.0` (which bundles Dart 3.13.0) for Flutter apps and when - using `ack_firebase_ai`. +Import `package:ack/ack.dart` and you're ready. The [Quickstart Tutorial](./quickstart-tutorial.mdx) takes you from your first schema to handling every validation outcome. Upgrading from Ack 1.x? See the [What's New & Migration Guide](./migration-guide.mdx). diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index fafbc9cf..8001ab54 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -2,124 +2,27 @@ title: What's New & Migration Guide --- -This guide summarizes **what exists in Ack today**, **what changed in 1.7 and 2.0 (and why)**, and **every removed 1.x symbol with its exact substitution**. +This guide lists what changed in Ack 2.0 and 1.7, and the replacement for every removed 1.x symbol. Find your starting version, then work through that section. ---- - -## 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 -has: - -```dart compile=migration-account -@Schemable() -final class const Account({ - @HasMinLength(2) required final String name, - @IsEmail() required final String email, -}) with _$AccountAck { - static final schema = AccountSchema.schema; - static final fromJson = AccountSchema.fromJson; -} -``` - -Use the -[validation annotation table](#validation-annotations) to rename every use; -`ipv4()` and `ipv6()` become `@IsIp(version: 4)` and `@IsIp(version: 6)`. -`@Schemable` and `@AckKey` keep their names, and the fluent API -(`Ack.string().minLength(3)`) is unchanged. - -Class-first examples now attach the generated facade with -`static final schema = AccountSchema.schema;` instead of naming the private -codec variable. Both forms generate the same code, so existing classes keep -working. - -### Dart 3.13 and primary constructors - -2.0.0-beta.3 requires Dart `>=3.13.0`, and Flutter `>=3.47.0` (the first -release that bundles Dart 3.13.0). Ack 1.7.1 supported Dart 3.9 and -Flutter 3.35. Upgrade to the new floors before moving to Ack 2.0. Class-first examples now use Dart 3.13 primary -constructors, with the rule annotations and `@AckKey` on the declaring -parameters, as in the `Account` example above. A classic constructor with -annotated fields still works and generates identical code, so existing models -need no change. - -## Beta.1 to beta.2: defaults and explicit null - -These are breaking changes in 2.0.0-beta.2: +## Before you upgrade -- `Ack.object({'role': Ack.string().withDefault('member')})` parses `{}` as - `{'role': 'member'}`, but rejects `{'role': null}`. Add `.nullable()` before - `.withDefault('member')` to accept a present null and parse it as the default. - Calling the defaulted schema's `parse(null)` directly still uses the default. -- Object encoding substitutes the validated default for a missing or null - defaulted property. A nullable defaulted model constructed with `label: null` - now encodes its non-null default. A nullable field without a default keeps - its existing null behavior. -- Generated fields follow Dart nullability: `T` rejects explicit JSON null; - `T?` accepts it unless marked `@IsNotNull()`. Constructor defaults - fill missing keys and follow the same encoding rules as object schemas. - -Regenerate model parts after updating `ack` and `ack_generator` together to -beta.2. - -## 1. What Exists in Ack - -Ack is organized into five coordinated packages that share one version number and one canonical schema representation (`AckSchema`): - -| Package | Role | Key Capabilities | -| --- | --- | --- | -| **`ack`** | Core runtime & annotations | • Fluent schema builders: `Ack.string()`, `Ack.integer()`, `Ack.double()`, `Ack.number()`, `Ack.boolean()`, `Ack.list()`, `Ack.map()`, `Ack.object()`, `Ack.any()`, `Ack.literal()`, `Ack.enumString()`, `Ack.enumValues()`, `Ack.anyOf()`, `Ack.discriminated()`, `Ack.lazy()`
• Bidirectional `CodecSchema`: `Ack.date()`, `Ack.datetime()`, `Ack.uri()`, `Ack.duration()`, `.codec()`, `.transform()`
• Two-way string normalizers: `.trim()`, `.toLowerCase()`, `.toUpperCase()`
• `JsonMaybe` (`JsonAbsent` / `JsonValue`) for tri-state `PATCH` payloads
• JSON Schema Draft 2020-12 import and runtime validation (`Ack.fromJsonSchema()`); native schemas export Draft-7, while `toJsonSchema()` preserves imported 2020-12 resources (`toJsonSchemaDraft7()` explicitly lowers them)
• Sealed `SchemaResult` (`Ok` / `Fail`) and sealed `SchemaError` hierarchy
• Unified codegen annotations in `package:ack/ack.dart`: `@Schemable()`, `@AckKey()`, and the `Is…`/`Has…` rule annotations (`@IsRequired()`, `@HasMinLength(n)`, `@IsEmail()`, …) | -| **`ack_generator`** | Two-way code generator | • **Schema-first (`@Schemable()` on a top-level schema)**: Generates an immutable model class, `Model.schema`, `parse`/`safeParse`, `fromJson`/`toJson`/`safeToJson`, typed `copyWith`, and deep `==`/`hashCode` in `.g.dart`
• **Class-first (`@Schemable()` on a `final class` or `sealed class`)**: Supports standard and Dart 3.13+ primary constructors; generates the `Schema` facade and the `_$Ack` mixin in `.g.dart`
• **`.schema.json` codegen (`ack_generator:ack_json_schema`)**: Compiles `lib/**/*.schema.json` assets into `.schema.dart` + `.schema.g.dart` | -| **`ack_mcp_dart`** | MCP tool input adapter | • `server.registerAckTool(name, input: schema, callback: ...)`, `schema.toMcpToolInputSchema()`, and `parseMcpToolArguments(...)`; callbacks return `CallToolResult` and own output validation | -| **`ack_firebase_ai`** | Firebase AI (Gemini) adapter | • `schema.toFirebaseAiResponseJsonSchema()` for the map-based `GenerationConfig.responseJsonSchema` field | -| **`ack_json_schema_builder`** | `json_schema_builder` bridge | • Bidirectional `schema.toJsonSchemaBuilder()` and `jsbSchema.toAckSchema()` | - ---- +- 2.0.0-beta.3 requires Dart `>=3.13.0`, and Flutter `>=3.47.0` (the first release that bundles Dart 3.13.0). Ack 1.7.1 supported Dart 3.9 and Flutter 3.35. Upgrade to the new floors before moving to Ack 2.0. +- Update `ack` and `ack_generator` together to the same version. +- Rerun `dart run build_runner build` to regenerate every model part. -## 2. What Changed & Why - -| Change | Introduced | What Changed | Why It Changed | -| --- | --- | --- | --- | -| **Annotations merged into `package:ack`** | `1.7.0` | `ack_annotations` was retired and model/validation annotations moved into `ack`. In 2.0, the public annotation API is `@Schemable()`, `@AckKey()`, and the `Is…`/`Has…` rule annotations from `package:ack/ack.dart`. | Eliminated version skew between `ack` and a separate annotations package and reduced model files to a single `import 'package:ack/ack.dart';`. | -| **Unified `@Schemable()` annotation** | `1.7.0` | `@Schemable()` drives both schema-first and class-first generation, replacing `@AckInfer()`, `@AckModel()`, and `@AckType()`. | One annotation and one mental model whether you start from an `AckSchema` or a hand-written Dart `class`. | -| **`Is…`/`Has…` rule annotations** | `2.0.0-beta.3` | Field and parameter rules—presence (`@IsRequired()`, `@IsOptional()`), nullability (`@IsNotNull()`), bounds (`@HasMin(0)`), formats (`@IsEmail()`, `@IsDateTime()`, `@IsUri()`), and collection rules (`@IsNotEmpty()`, `@HasUniqueItems()`)—are top-level classes in `package:ack/ack.dart`. Use the validation annotation table to migrate from the 2.0 beta rule namespace. | Top-level 1.x classes (`@Required`, `@Email`, `@Uuid`, `@Date`, `@Uri`, `@DateTime`, `@Pattern`) collided with `package:meta` / Flutter (`Required`), `dart:core` (`Uri`, `DateTime`, `Pattern`), and `package:uuid`, forcing import prefixes (`as ack`). The beta `Validate` namespace avoided that with a prefix on every use. The `Is…`/`Has…` names need neither: none of them collides with the Dart SDK, Flutter, or common packages. | -| **Single `.g.dart` part & direct JSON emitter** | `2.0.0` | `ack_generator:ack_generator` is a `SharedPartBuilder` that emits `.g.dart` directly with no `json_serializable` or `json_annotation` dependency. | In 1.x, every model required two `part` directives (`.ack.dart` + `.ack.g.dart`) and a second `json_serializable` pass. Direct emission cuts build steps in half, uses standard `part '.g.dart';`, and coexists with Freezed or Riverpod in the same file. | -| **Generator Analyzer dependency** | `2.0.0` | `ack_generator` requires Analyzer `>=13.3.0 <15.0.0`. Update dependencies or overrides that pin Analyzer below 13.3.0. | The minimum matches the version verified by the generator suite on the 2.0 baseline. The wider upper bound lets the generator resolve with current Freezed and build_runner releases. | -| **Layered custom schema resolution (`T.schema`, `schemas: [...]`)** | `1.7.0` / `2.0.0` | Custom field types resolve via `@Schemable(schemas: [...])` (on classes, unions, or `library;` directives), type-owned `T.schema` / `T.schema
()` factories, or automatic detection of a unique top-level `AckSchema` in the current library. | Removed per-field `@AckField(schema: ...)` boilerplate on every field that uses a domain value object, extension type, enum, or generic wrapper. | -| **Typed `$ClassCopyWith` getter** | `1.7.0` | `model.copyWith` returns a typed callable interface instead of widening parameters to `Object?`. | Passing `model.copyWith(age: 'wrong')` previously compiled and failed only at runtime (`TypeError`). Now mistyped arguments fail at compile time while `model.copyWith(age: null)` still clears nullable fields. | -| **Two-way string normalizers (`.trim()`, `.toLowerCase()`, `.toUpperCase()`)** | `2.0.0` | Normalizers live directly on `StringSchema` and run in declaration order alongside constraints during both `parse` and `encode`. | In 1.x, `.trim()` used a one-way `.transform()`, which failed on `encode()`, was rejected by `@Schemable()`, and emitted `'x-transformed': true` in JSON Schema. | -| **`JsonMaybe` (`JsonAbsent` / `JsonValue`)** | `2.0.0` | Tri-state field container for class-first `@Schemable()` models. | A plain `String?` field in Dart cannot distinguish `{"bio": null}` (clear field in a `PATCH` request) from `{}` (leave field unchanged) when encoding back to JSON. | -| **Sealed `SchemaError` & `AckSchema` hierarchies + decoder `Error` propagation** | `2.0.0` | `SchemaError` and `AckSchema` are `sealed class`es. `CodecSchema` rethrows programmer `Error`s (`TypeError`, `StateError`) on `parse`/`safeParse` and catches only `Exception`s as `SchemaTransformError`. | Enables exhaustive `switch (error)` pattern matching without a wildcard branch, and prevents programming bugs inside `decode` callbacks from being masked as user input errors. | -| **JSON Schema Draft 2020-12 default + `.schema.json` codegen** | `2.0.0` | `Ack.fromJsonSchema()` supports the full required Draft 2020-12 keyword suite (`$dynamicRef`, `unevaluatedProperties`, `prefixItems`, `minContains`/`maxContains`, `dependentSchemas`, `patternProperties`, and all 19 formats when `assertFormats: true`). `toJsonSchema()` preserves 2020-12 resources by default (`toJsonSchemaDraft7()` lowers to Draft-7). | Enables lossless round-tripping of modern protocol schemas (MCP, A2UI v0.9, OpenAPI 3.1) and compile-time Dart codegen from `.schema.json` files. | -| **ECMA-262 Unicode mode (`u`) for imported `pattern`** | `1.7.0` | Imported JSON Schema `pattern` expressions compile with ECMA-262 Unicode semantics. | Required by the JSON Schema specification so `.` matches full Unicode code points (including emoji) and `\p{...}` property escapes work identically to Ajv. | -| **NFKC normalization for international formats** | `2.0.0` | Imported JSON Schema checks for international hostnames and email addresses validate labels as supplied by default. | To restore the earlier behavior, import `nfkc` from `package:unorm_dart` and pass `unicodeNormalizer: nfkc` to `Ack.fromJsonSchema()`. | +## What's new in 2.0 ---- +- Schema-first models get lowerCamelCase Dart field names from JSON keys. Wire keys keep their original spelling. +- Annotated union branches inherit the base `caseStyle`. +- Generated `Set` fields reject duplicate JSON values and export `uniqueItems: true`. +- `SchemaError.toString()` prints one `path: message` line per failure. Ack no longer adds input values or callback exception text; messages you write can still contain input. +- The `Is…`/`Has…` rule annotations replace the beta rule namespace. `ack_generator` supports Analyzer 13.3 to 14.x. -## 3. What Doesn't Exist Anymore & Exact Substitutions +## From Ack 1.x -### Packages & Imports +### Packages and imports -| Removed Item | Removed In | Exact Substitution | +| Removed Item | Removed In | Replace with | | --- | --- | --- | | `ack_annotations` package in `pubspec.yaml` | `1.7.0` | Remove `ack_annotations`; `ack` includes all annotations. | | `import 'package:ack_annotations/ack_annotations.dart';` | `1.7.0` | `import 'package:ack/ack.dart';` | @@ -128,9 +31,11 @@ Ack is organized into five coordinated packages that share one version number an | `import 'package:ack/format_annotations.dart';` | `2.0.0` | `import 'package:ack/ack.dart';` (use `@IsDateTime()`, `@IsUri()`, `@IsIp()`, `@IsIp(version: 4)`, `@IsIp(version: 6)`) | | `json_serializable` & `json_annotation` for `@Schemable()` models | `2.0.0` | Remove unless used by other non-Ack classes; `ack_generator` emits `toJson` / `fromJson` directly. | -### Model & Field Annotations +### Removed 1.x and beta annotations + +Model and field annotations: -| Removed Symbol | Removed In | Exact Substitution | +| Removed Symbol | Removed In | Replace with | | --- | --- | --- | | `@AckType()` | `2.0.0` | `@Schemable()` on the top-level schema | | `@AckInfer(...)` | `2.0.0` | `@Schemable(...)` on the top-level schema | @@ -143,18 +48,11 @@ 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. +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 +Validation annotations. The top-level 1.x validation and presence classes were removed in `2.0.0`. Ack 2.0 also removes the deprecated beta rule namespace. Use the concrete annotations from `package:ack/ack.dart`. Code that reads a rule’s former `kind` and `value` getters can inspect its concrete type and named fields. -The top-level 1.x validation and presence classes were removed in `2.0.0`. -Ack 2.0 also removes the deprecated beta rule namespace. Use the concrete -annotations from `package:ack/ack.dart`. Code that reads a rule’s former -`kind` and `value` getters can inspect its concrete type and named fields. - -| Removed `1.x` annotation | Removed 2.0 beta annotation | Ack 2.0 rule annotation | +| Removed `1.x` annotation | Removed 2.0 beta annotation | Replace with | | --- | --- | --- | | `@Optional()` | `@Validate.optional()` | `@IsOptional()` | | `@Required()` | `@Validate.required()` | `@IsRequired()` | @@ -181,30 +79,53 @@ annotations from `package:ack/ack.dart`. Code that reads a rule’s former | `@MaxItems(n)` | `@Validate.maxItems(n)` | `@HasMaxItems(n)` | | `@UniqueItems()` | `@Validate.uniqueItems()` | `@HasUniqueItems()` | +Rename annotations as in this example. `ipv4()` and `ipv6()` become `@IsIp(version: 4)` and `@IsIp(version: 6)`. `@Schemable` and `@AckKey` keep their names, and the fluent API (`Ack.string().minLength(3)`) is unchanged. -### Generated Files, Builders & Runtime APIs +```dart compile=migration-account +@Schemable() +final class const Account({ + @HasMinLength(2) required final String name, + @IsEmail() required final String email, +}) with _$AccountAck { + static final schema = AccountSchema.schema; + static final fromJson = AccountSchema.fromJson; +} +``` + +Class-first examples attach the generated facade with `static final schema = AccountSchema.schema;` instead of naming the private codec variable. Both forms generate the same code, so existing classes keep working. Class-first examples also use Dart 3.13 primary constructors, with the rule annotations and `@AckKey` on the declaring parameters. A classic constructor with annotated fields still works and generates identical code, so existing models need no change. -| Removed `1.x` Item | Removed In | Exact `2.0` Substitution | +### Breaks compilation + +| Removed or changed item | Changed in | Replace with | | --- | --- | --- | -| `part 'model.ack.dart';` + `part 'model.ack.g.dart';` | `2.0.0` | Single `part 'model.g.dart';` | -| `ack_generator\|ack_models` & `ack_generator\|ack_model_json` in `build.yaml` | `2.0.0` | `ack_generator:ack_generator` (plus optional `ack_generator:ack_json_schema` for `.schema.json` files) | -| `@AckType()` `*Type` extension type, `.args`, `ModelType.parse(...)` | `2.0.0` | Generated `Model` class with typed fields, `Model.parse(...)`, `Model.safeParse(...)`, `Model.fromJson(...)`, `model.toJson()` | | `Ack.preserveBoundary` over other value shapes, or `BoundarySchema` | `2.0.0` | Use `Ack.preserveBoundary` with a JSON object schema. Use the nongeneric `BoundarySchema` type. | | Subclasses of `Ok`, `Fail`, `AckException`, `ConstraintError`, or `DurationConstraint` | `2.0.0` | These classes are `final`. Compose them or use their public constructors and factories. | -| Implicit defaults for a present null object field | `2.0.0` | Defaults fill omitted keys. Declare `.nullable().withDefault(value)` to accept an explicit null and apply the default on parse. Object encoding uses the default for missing or null defaulted fields. | | `Ack.enumCodec(MyEnum.values)` | `2.0.0` | `Ack.enumValues(MyEnum.values)` | -| Draft-7 `dependencies` passed to `Ack.fromJsonSchema` | `2.0.0` | Convert the resource to Draft 2020-12. Use `dependentRequired` for property lists and `dependentSchemas` for schema dependencies. | -| Lowering an imported Draft 2020-12 schema that contains `dependencies` to Draft-7 | `2.0.0` | Use `toJsonSchema()` to preserve the original document, or remove the ignored `dependencies` keyword before calling `toJsonSchemaDraft7()`. | -| A quoted email local part has unbalanced or misplaced quotes | `2.0.0` | Imported `email` and `idn-email` assertions reject it. Provide a valid email address. | -| Imported hostname or email domain assertions that relied on lowercasing non-ASCII labels | `2.0.0` | Ack lowercases ASCII only. Supply labels valid under IDNA2008, such as the permitted lowercase form of a disallowed Unicode capital letter. | | `AckRawSchemaModel(indexedSchemas: …)` | `2.0.0` | Omit the internal schema index when constructing a raw schema model. | | `ListSchema.minLength`, `maxLength`, `exactLength`, `nonEmpty` | `2.0.0` | Use `minItems`, `maxItems`, `length`, and `notEmpty`, respectively. | | `StringSchema.url()` | `2.0.0` | Use `StringSchema.uri()` for the same validation and schema export. | -| Code matching a renamed built-in constraint key | `2.0.0` | `string.startsWith` → `string_starts_with`, `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique_items`, `number.isFinite` → `number_finite`, `integer.isSafe` → `number_safe_integer`, `string_format_time` → `string_time`. | | `AckRule` from `package:ack/annotations.dart` | `2.0.0` | Use the concrete rule annotation type for rule-specific data, or `Object` for a mixed list. | | `implements SchemaContext` | `2.0.0` | Read the context from `SchemaError.context`. `SchemaContext` is a `base` class, so external subclasses require a `base`, `final`, or `sealed` modifier. | | `SchemaContext.transparent` | `2.0.0` | Ack uses the internal `createTransparentChild` and `isTransparent` helpers for wrapper contexts. Read the resulting context through `SchemaError.context`. | | `AckSchemaModel.finishTypeJson` or `AckSchemaModel.finishCompositionJson` | `2.0.0` | Render the public model with `toJsonSchema()` and apply any custom JSON Schema keywords to the resulting map. | +| `schema.toMap()` | `2.0.0` | `schema.toJsonSchema()` or `schema.toSchemaModel()` | +| `server.registerAckModelTool(...)` (`ack_mcp_dart`) | `2.0.0` | `server.registerAckTool(name, input: Model.schema, callback: ...)`; return a `CallToolResult` from the callback | +| `convertAckSchemaModelToBuilder(model)` (`ack_json_schema_builder`) | `2.0.0` | `schema.toJsonSchemaBuilder()` | +| `AckSchemaModel.withJsonSchemaKeywords` | `2.0.0` | The method remains callable and is marked `@internal`. External calls produce an analyzer warning. Render with `toJsonSchema()` and apply custom keywords to the resulting map. | +| `SchemaContext.createChild` | `2.0.0` | Use the nested error's `context` to inspect its value and path. Ack creates child contexts during validation. | +| `withConstraint(c)` or `withConstraints([a, b])` | `2.0.0` | Use `constrain(c)` or chain `constrain(a).constrain(b)`. Both former methods are marked `@internal`. | + +### Changes runtime behavior + +| Removed or changed item | Changed in | Replace with | +| --- | --- | --- | +| `ack_generator\|ack_models` & `ack_generator\|ack_model_json` in `build.yaml` | `2.0.0` | `ack_generator:ack_generator` (plus optional `ack_generator:ack_json_schema` for `.schema.json` files) | +| Implicit defaults for a present null object field | `2.0.0` | Defaults fill omitted keys. Declare `.nullable().withDefault(value)` to accept an explicit null and apply the default on parse. Object encoding uses the default for missing or null defaulted fields. | +| Draft-7 `dependencies` passed to `Ack.fromJsonSchema` | `2.0.0` | Convert the resource to Draft 2020-12. Use `dependentRequired` for property lists and `dependentSchemas` for schema dependencies. | +| Lowering an imported Draft 2020-12 schema that contains `dependencies` to Draft-7 | `2.0.0` | Use `toJsonSchema()` to preserve the original document, or remove the ignored `dependencies` keyword before calling `toJsonSchemaDraft7()`. | +| A quoted email local part has unbalanced or misplaced quotes | `2.0.0` | Imported `email` and `idn-email` assertions reject it. Provide a valid email address. | +| Imported hostname or email domain assertions that relied on lowercasing non-ASCII labels | `2.0.0` | Ack lowercases ASCII only. Supply labels valid under IDNA2008, such as the permitted lowercase form of a disallowed Unicode capital letter. | +| Code matching a renamed built-in constraint key | `2.0.0` | `string.startsWith` → `string_starts_with`, `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique_items`, `number.isFinite` → `number_finite`, `integer.isSafe` → `number_safe_integer`, `string_format_time` → `string_time`. | | UTF-16 code-unit counts in string `minLength`, `maxLength`, and `length` | `2.0.0` | Adjust limits to count Unicode code points. Use a custom refinement based on `String.length` if a protocol measures UTF-16 code units. | | JSON Schema `format: time` from `Ack.string().time()` | `2.0.0` | Read the exported `pattern`. To require RFC 3339 time with an offset, import a schema with `format: time` and pass `assertFormats: true`. | | Parse or encode traversing more than 100 nested collections | `2.0.0` | Flatten the input or process it in smaller subtrees. A `max_collection_depth` failure identifies the path. For recursive schemas, configure `Ack.lazy` with `maxDepth`. The exported collection snapshot helpers cap nesting at 100 and throw `ArgumentError` for a cycle or excessive depth. | @@ -217,26 +138,36 @@ annotations from `package:ack/ack.dart`. Code that reads a rule’s former | Mutating a collection passed to `withDefault` or returned from `defaultValue` | `2.0.0` | Create a new schema to change the default. Ack takes a detached snapshot and exposes an unmodifiable value or a fresh copy. | | Defaulted fields listed as JSON Schema `required` when a transform or codec follows `withDefault` | `2.0.0` | Treat these fields as omittable in the exported schema. The transform or codec receives the input default during parse. | | Equality between schemas with different generic types, including discriminated object schemas | `2.0.0` | Construct both schemas with the same boundary and runtime types when you need them to compare equal. | -| `schema.toMap()` | `2.0.0` | `schema.toJsonSchema()` or `schema.toSchemaModel()` | -| `server.registerAckModelTool(...)` (`ack_mcp_dart`) | `2.0.0` | `server.registerAckTool(name, input: Model.schema, callback: ...)`; return a `CallToolResult` from the callback | -| `convertAckSchemaModelToBuilder(model)` (`ack_json_schema_builder`) | `2.0.0` | `schema.toJsonSchemaBuilder()` | | `Ack.fromJsonSchema(...)` enforcing `format` by default | `2.0.0` | Pass `Ack.fromJsonSchema(schema, assertFormats: true)` (or declare `format-assertion` in `$vocabulary`) when format assertions are required | | `schema.toJsonSchema()` lowering imported 2020-12 schemas to Draft-7 | `2.0.0` | `schema.toJsonSchema()` now preserves Draft 2020-12 resources by default; call `schema.toJsonSchemaDraft7()` when Draft-7 lowering is required | +| Raw constraints in `copyWith(constraints:)` or `withRuntimeConfig(constraints:)` | `2.0.0` | Replacement constraints must mix in `Validator`. Use `constrain(c)` to add a custom constraint. | -### Internal Runtime APIs +### Changes generated code -| `1.x` Item | Changed In | Exact `2.0` Substitution | +| Removed or changed item | Changed in | Replace with | | --- | --- | --- | -| `AckSchemaModel.withJsonSchemaKeywords` | `2.0.0` | The method remains callable and is marked `@internal`. External calls produce an analyzer warning. Render with `toJsonSchema()` and apply custom keywords to the resulting map. | -| `SchemaContext.createChild` | `2.0.0` | Use the nested error's `context` to inspect its value and path. Ack creates child contexts during validation. | -| `withConstraint(c)` or `withConstraints([a, b])` | `2.0.0` | Use `constrain(c)` or chain `constrain(a).constrain(b)`. Both former methods are marked `@internal`. | -| Raw constraints in `copyWith(constraints:)` or `withRuntimeConfig(constraints:)` | `2.0.0` | Replacement constraints must mix in `Validator`. Use `constrain(c)` to add a custom constraint. | - ---- +| `part 'model.ack.dart';` + `part 'model.ack.g.dart';` | `2.0.0` | Single `part 'model.g.dart';` | +| `@AckType()` `*Type` extension type, `.args`, `ModelType.parse(...)` | `2.0.0` | Generated `Model` class with typed fields, `Model.parse(...)`, `Model.safeParse(...)`, `Model.fromJson(...)`, `model.toJson()` | -## 4. Before & After Migration Examples +### What changed in 1.7 and 2.0 -### Class-First Model Migration +| Change | Introduced | Action | +| --- | --- | --- | +| **Annotations merged into `package:ack`** | `1.7.0` | `ack_annotations` was retired. Import only `package:ack/ack.dart` and use `@Schemable()`, `@AckKey()`, and the `Is…`/`Has…` rule annotations. | +| **Unified `@Schemable()` annotation** | `1.7.0` | Replace `@AckInfer()`, `@AckModel()`, and `@AckType()` with `@Schemable()`. It drives both schema-first and class-first generation. | +| **`Is…`/`Has…` rule annotations** | `2.0.0-beta.3` | Use the top-level classes in `package:ack/ack.dart` for presence (`@IsRequired()`, `@IsOptional()`), nullability (`@IsNotNull()`), bounds (`@HasMin(0)`), formats (`@IsEmail()`, `@IsDateTime()`, `@IsUri()`), and collection rules (`@IsNotEmpty()`, `@HasUniqueItems()`). Rename each 1.x and beta annotation with the [annotation table](#removed-1x-and-beta-annotations). None of the names collides with the Dart SDK, Flutter, or common packages, so no import prefix is needed. | +| **Single `.g.dart` part and direct JSON emitter** | `2.0.0` | Declare one `part '.g.dart';`. `ack_generator:ack_generator` is a `SharedPartBuilder` that emits `toJson`/`fromJson` directly, so it needs no `json_serializable` or `json_annotation` and coexists with Freezed or Riverpod in the same file. | +| **Generator Analyzer dependency** | `2.0.0` | Update dependencies or overrides that pin Analyzer below 13.3.0. `ack_generator` requires Analyzer `>=13.3.0 <15.0.0`. | +| **Layered custom schema resolution (`T.schema`, `schemas: [...]`)** | `1.7.0` / `2.0.0` | Replace per-field `@AckField(schema: ...)` with `@Schemable(schemas: [...])` (on classes, unions, or `library;` directives), a type-owned `T.schema` / `T.schema()` factory, or a unique top-level `AckSchema` in the current library. | +| **Typed `$ClassCopyWith` getter** | `1.7.0` | Fix call sites that passed a wrong type to `model.copyWith(...)`: they now fail at compile time instead of throwing `TypeError`. `model.copyWith(age: null)` still clears nullable fields. | +| **Two-way string normalizers (`.trim()`, `.toLowerCase()`, `.toUpperCase()`)** | `2.0.0` | Replace a one-way `.trim()` built on `.transform()` with the `StringSchema` normalizers. They run in declaration order alongside constraints during both `parse` and `encode`, work with `@Schemable()`, and add no `'x-transformed': true` to JSON Schema. | +| **`JsonMaybe` (`JsonAbsent` / `JsonValue`)** | `2.0.0` | Use `JsonMaybe` in class-first `@Schemable()` models to tell `{"bio": null}` (clear the field in a `PATCH` request) from `{}` (leave it unchanged). | +| **Sealed `SchemaError` & `AckSchema` hierarchies + decoder `Error` propagation** | `2.0.0` | Match `SchemaError` exhaustively with `switch (error)` and no wildcard branch. `CodecSchema` rethrows programmer `Error`s (`TypeError`, `StateError`) on `parse`/`safeParse` and catches only `Exception`s as `SchemaTransformError`. | +| **JSON Schema Draft 2020-12 default + `.schema.json` codegen** | `2.0.0` | `Ack.fromJsonSchema()` supports the full required Draft 2020-12 keyword suite (`$dynamicRef`, `unevaluatedProperties`, `prefixItems`, `minContains`/`maxContains`, `dependentSchemas`, `patternProperties`, and all 19 formats when `assertFormats: true`). `toJsonSchema()` preserves 2020-12 resources by default; call `toJsonSchemaDraft7()` to lower to Draft-7. Compile Dart models from `.schema.json` files with `ack_generator:ack_json_schema`. | +| **ECMA-262 Unicode mode (`u`) for imported `pattern`** | `1.7.0` | Imported JSON Schema `pattern` expressions compile with ECMA-262 Unicode semantics. `.` matches full Unicode code points (including emoji) and `\p{...}` property escapes work as in Ajv. | +| **NFKC normalization for international formats** | `2.0.0` | Imported checks for international hostnames and email addresses validate labels as supplied. To restore the earlier behavior, import `nfkc` from `package:unorm_dart` and pass `unicodeNormalizer: nfkc` to `Ack.fromJsonSchema()`. | + +### Before and after **Compile check skipped:** This historical example requires Ack 1.6 and its retired generator. @@ -283,40 +214,48 @@ final class const Account({ } ``` -### Schema-First Model Migration +For a schema-first model, see [Model Code Generation](../core-concepts/typesafe-schemas.mdx#schema-first-schemable-on-a-top-level-schema). Replace `@AckInfer()` with `@Schemable()` and drop the `.ack.dart` and `.ack.g.dart` parts. -**Compile check skipped:** This historical example requires Ack 1.6 and its retired generator. +## From a 2.0 beta -```dart -// ❌ BEFORE (Ack 1.6, @AckInfer) -import 'package:ack/ack.dart'; -import 'package:ack_annotations/ack_annotations.dart'; +### Beta.3 to 2.0: generated models -part 'user.ack.dart'; -part 'user.ack.g.dart'; +| Affected code | Changed in | Replace with | +| --- | --- | --- | +| 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. | -@AckInfer() -final userSchema = Ack.object({ - 'name': Ack.string().minLength(2), - 'email': Ack.string().email(), -}); -``` +### Beta rule namespace -```dart compile=model -// ✅ AFTER (Ack 2.0) -import 'package:ack/ack.dart'; +Replace the deprecated `@Validate.*` namespace with the `Is…`/`Has…` annotations. Use the [annotation table](#removed-1x-and-beta-annotations). -part 'user.g.dart'; +### Beta.1 to beta.2: defaults and explicit null -@Schemable() -final userSchema = Ack.object({ - 'name': Ack.string().minLength(2), - 'email': Ack.string().email(), -}); - -// Generated class User provides: -// - User.schema (AckSchema, User>) -// - User.parse(...) / User.safeParse(...) -// - User.fromJson(...) / user.toJson() / user.safeToJson() -// - user.copyWith(...) / deep == and hashCode -``` +These are breaking changes in 2.0.0-beta.2: + +- `Ack.object({'role': Ack.string().withDefault('member')})` parses `{}` as + `{'role': 'member'}`, but rejects `{'role': null}`. Add `.nullable()` before + `.withDefault('member')` to accept a present null and parse it as the default. + Calling the defaulted schema's `parse(null)` directly still uses the default. +- Object encoding substitutes the validated default for a missing or null + defaulted property. A nullable defaulted model constructed with `label: null` + now encodes its non-null default. A nullable field without a default keeps + its existing null behavior. +- Generated fields follow Dart nullability: `T` rejects explicit JSON null; + `T?` accepts it unless marked `@IsNotNull()`. Constructor defaults + fill missing keys and follow the same encoding rules as object schemas. + +Regenerate model parts after updating `ack` and `ack_generator` together to +beta.2. diff --git a/docs/getting-started/quickstart-tutorial.mdx b/docs/getting-started/quickstart-tutorial.mdx index 00099c52..04c80cf1 100644 --- a/docs/getting-started/quickstart-tutorial.mdx +++ b/docs/getting-started/quickstart-tutorial.mdx @@ -2,11 +2,7 @@ title: Quickstart Tutorial --- -This tutorial validates a Dart map — the kind you get from `jsonDecode()` of an API response or a form submission — and handles every outcome. - -## Prerequisites - -[Install Ack](./installation.mdx) in your Dart or Flutter project. +This tutorial validates a Dart map — the kind you get from `jsonDecode()` of an API response or a form submission — and handles every outcome. [Install Ack](./installation.mdx) in your Dart or Flutter project first. ## 1. Define a schema @@ -27,8 +23,7 @@ See [Schema Types](../core-concepts/schemas.mdx) and [Validation Rules](../core- Call `safeParse()` with the data you received — for example `jsonDecode(response.body)`. It returns a `SchemaResult`, so expected validation -failures stay in normal control flow instead of throwing. For callback, -transform, and codec failure semantics, see [Error Handling](../core-concepts/error-handling.mdx). +failures stay in normal control flow instead of throwing. ```dart compile=quickstart-parse final result = userSchema.safeParse({'name': 'Alice', 'age': 30}); @@ -45,33 +40,45 @@ Prefer exceptions? Use `parse()` instead — it returns the value or throws `Ack ## 3. Handle every outcome -A schema accepts valid data and rejects each way it can be wrong. This runnable example checks four inputs: +A schema accepts valid data and rejects each way it can be wrong. Run the same `safeParse()` call on four inputs: + +| Input | Outcome | +| --- | --- | +| `{'name': 'Alice', 'age': 30}` | OK | +| `{'name': 'Bob'}` | OK: `age` is optional | +| `{'name': 'X', 'age': 25}` | Fails: `name` is shorter than 2 characters | +| `{'age': 40}` | Fails: `name` is missing | + +Each failure prints one `path: message` line. See [Error Handling](../core-concepts/error-handling.mdx) to read and display errors. -```dart +## 4. Generate a typed model (optional) + +To get typed fields instead of map access, add `ack_generator` and `build_runner` ([Installation](./installation.mdx#optional-code-generator)). Put `@Schemable()` on a top-level schema and add the generated part: + +```dart compile=model import 'package:ack/ack.dart'; +part 'user.g.dart'; + +@Schemable() +final userSchema = Ack.object({ + 'name': Ack.string().minLength(2), + 'email': Ack.string().email(), +}); + void main() { - final userSchema = Ack.object({ - 'name': Ack.string().minLength(2), - 'age': Ack.integer().min(0).optional(), - }); - - checkResult(userSchema.safeParse({'name': 'Alice', 'age': 30})); // OK - checkResult(userSchema.safeParse({'name': 'Bob'})); // OK: age omitted - checkResult(userSchema.safeParse({'name': 'X', 'age': 25})); // name too short - checkResult(userSchema.safeParse({'age': 40})); // name missing + final user = User.parse({'name': 'Ada', 'email': 'ada@example.com'}); + print(user.name); // typed String } +``` -void checkResult(SchemaResult result) { - if (result.isOk) { - print('OK: ${result.getOrThrow()}'); - } else { - print(result.getError()); // one path: message line per failure - } -} +Run the generator: + +```bash +dart run build_runner build ``` -See [Error Handling](../core-concepts/error-handling.mdx) to read and display errors. +See [Model Code Generation](../core-concepts/typesafe-schemas.mdx) for details, including class-first models. ## Next steps @@ -79,3 +86,5 @@ See [Error Handling](../core-concepts/error-handling.mdx) to read and display er - [Validation Rules](../core-concepts/validation.mdx) — built-in constraints - [Custom Validation](../guides/custom-validation.mdx) — add your own logic - [JSON Serialization](../core-concepts/json-serialization.mdx) — parse and encode JSON +- [Flutter Form Validation](../guides/flutter-form-validation.mdx) — show field errors in a form +- [Codecs](../core-concepts/codecs.mdx) — parse dates, URIs, and durations diff --git a/docs/guides/common-recipes.mdx b/docs/guides/common-recipes.mdx index 38f0b23f..0df159fa 100644 --- a/docs/guides/common-recipes.mdx +++ b/docs/guides/common-recipes.mdx @@ -2,169 +2,31 @@ title: Common Recipes --- -Quick solutions to common validation scenarios. Each recipe shows a working -schema pattern you can copy and adapt. Examples assume -`package:ack/ack.dart` is imported unless the snippet shows other imports. +Find the page for a common task, or follow the full recipe for validating an API +response. -## Email and password validation +| Recipe | Where to find it | +|---|---| +| Email and password rules | [Validation Rules](../core-concepts/validation.mdx) and [Flutter Form Validation](./flutter-form-validation.mdx) | +| Nested objects, optional and nullable fields | [Schema Types](../core-concepts/schemas.mdx#optional-vs-nullable) | +| Lists with length limits | [Schema Types](../core-concepts/schemas.mdx) and [Validation Rules](../core-concepts/validation.mdx) | +| Enums | [Schema Types](../core-concepts/schemas.mdx#string) | +| Custom constraints and cross-field rules | [Custom Validation](./custom-validation.mdx#creating-a-value-constraint) | -Validate user credentials with proper constraints: - -```dart compile=body -import 'package:ack/ack.dart'; - -// Email with proper format -final emailSchema = Ack.string() - .email() - .notEmpty(); - -// Password with security requirements -final passwordSchema = Ack.string() - .minLength(8) - .matches(r'.*[A-Z].*', message: 'Password must contain an uppercase letter') - .matches(r'.*[a-z].*', message: 'Password must contain a lowercase letter') - .matches(r'.*[0-9].*', message: 'Password must contain a number'); - -// Login form schema -final loginSchema = Ack.object({ - 'email': emailSchema, - 'password': passwordSchema, -}); - -// Usage -final result = loginSchema.safeParse({ - 'email': 'user@example.com', - 'password': 'SecurePass123', -}); - -if (result.isOk) { - print('Credentials valid'); -} else { - print('Error: ${result.getError()}'); -} -``` - -## Nested object validation - -Validate nested data structures like addresses: - -```dart compile=library -final addressSchema = Ack.object({ - 'street': Ack.string().notEmpty(), - 'city': Ack.string().notEmpty(), - 'zipCode': Ack.string().matches(r'^\d{5}(-\d{4})?$'), - 'country': Ack.string().notEmpty(), -}); - -final userWithAddressSchema = Ack.object({ - 'name': Ack.string(), - 'email': Ack.string().email(), - 'shippingAddress': addressSchema, - 'billingAddress': addressSchema.optional().nullable(), -}); - -// Usage -final result = userWithAddressSchema.safeParse({ - 'name': 'John Doe', - 'email': 'john@example.com', - 'shippingAddress': { - 'street': '123 Main St', - 'city': 'Springfield', - 'zipCode': '12345', - 'country': 'USA', - }, -}); -``` - -## List validation - -Validate lists with constraints on items and length: - -```dart compile=library -// Shopping cart with at least 1 item -final cartSchema = Ack.object({ - 'userId': Ack.string(), - 'items': Ack.list(Ack.object({ - 'productId': Ack.string(), - 'quantity': Ack.integer().positive(), - 'price': Ack.double().positive(), - })).minItems(1).maxItems(50), -}); - -// Tags with max 5 items -final postSchema = Ack.object({ - 'title': Ack.string().minLength(5).maxLength(100), - 'content': Ack.string().minLength(10), - 'tags': Ack.list(Ack.string()).maxItems(5), -}); -``` - -## Enum validation - -Validate values against a set of allowed options using Dart enums: - -```dart compile=library -enum OrderStatus { pending, processing, shipped, delivered, cancelled } -enum Priority { low, medium, high } - -final orderSchema = Ack.object({ - 'orderId': Ack.string(), - 'status': Ack.enumValues(OrderStatus.values), - 'priority': Ack.enumValues(Priority.values), -}); - -// Usage -final result = orderSchema.safeParse({ - 'orderId': 'ORD-123', - 'status': 'shipped', - 'priority': 'high', -}); -``` - -## Custom validation - -Create reusable custom validators for domain-specific rules: - -```dart compile=library -import 'package:ack/ack.dart'; - -// Custom phone number constraint -class PhoneNumberConstraint extends Constraint with Validator { - PhoneNumberConstraint() - : super( - constraintKey: 'phone_number', - description: 'Must be valid phone number (e.g., +1-234-567-8900)', - ); - - final _regex = RegExp(r'^\+\d{1,3}-\d{3}-\d{3}-\d{4}$'); - - @override - bool isValid(String value) => _regex.hasMatch(value); - - @override - String buildMessage(String value) => - 'Must be valid phone number (e.g., +1-234-567-8900)'; -} +## API response validation -final registrationSchema = Ack.object({ - 'username': Ack.string().minLength(3), - 'email': Ack.string().email(), - 'phone': Ack.string().constrain(PhoneNumberConstraint()), - 'password': Ack.string().minLength(8), - 'confirmPassword': Ack.string().minLength(8), -}).refine( - (data) => data['password'] == data['confirmPassword'], - message: 'Passwords do not match', -); -``` +Goal: check an external API response before your code uses it. -## API response validation +APIs add fields over time. Declare only the fields your application uses, and set +`additionalProperties: true` so the other fields pass through. -Validate external API responses before using the payload. APIs commonly add -fields over time, so this boundary schema validates the fields the application -uses while allowing the rest of GitHub's response to pass through. +1. Add the HTTP client: `dart pub add http`. +2. Declare a schema for the fields you use, with `additionalProperties: true`. +3. Decode the body with `jsonDecode`. +4. Call `safeParse` and handle both outcomes. -Add the HTTP client first with `dart pub add http`. +Use `safeParse` for data you do not control. It returns a result instead of +throwing. `parse` throws on invalid data. ```dart compile=library import 'dart:convert'; @@ -172,7 +34,6 @@ import 'dart:convert'; import 'package:ack/ack.dart'; import 'package:http/http.dart' as http; -// GitHub user API response final githubUserSchema = Ack.object({ 'login': Ack.string(), 'id': Ack.integer(), @@ -186,7 +47,6 @@ final githubUserSchema = Ack.object({ 'created_at': Ack.string().datetime(), }, additionalProperties: true); -// Usage in API call Future fetchUser(String username) async { final response = await http.get( Uri.parse('https://api.github.com/users/$username'), @@ -208,11 +68,12 @@ Future fetchUser(String username) async { } ``` +The result is a validated map. Fields not in the schema stay in the map. + ## See also -- [Custom validation guide](./custom-validation.mdx) — deep dive into custom validators -- [Flutter form validation](./flutter-form-validation.mdx) — integrate with Flutter forms -- [Codecs](../core-concepts/codecs.mdx) — date, URI, and custom value conversions -- [JSON Schema integration](./json-schema-integration.mdx) — export schemas for API docs and tools -- [Schema types](../core-concepts/schemas.mdx) — all available schema types -- [Validation rules](../core-concepts/validation.mdx) — complete constraint reference +- [Custom Validation](./custom-validation.mdx) +- [Flutter Form Validation](./flutter-form-validation.mdx) +- [Codecs](../core-concepts/codecs.mdx) +- [JSON Schema Integration](./json-schema-integration.mdx) +- [Error Handling](../core-concepts/error-handling.mdx) diff --git a/docs/guides/creating-schema-converter-packages.mdx b/docs/guides/creating-schema-converter-packages.mdx index d4734f2d..bec271d6 100644 --- a/docs/guides/creating-schema-converter-packages.mdx +++ b/docs/guides/creating-schema-converter-packages.mdx @@ -2,10 +2,22 @@ title: Creating Adapter Packages --- -An adapter exports an Ack boundary contract to another schema system. Choose the -export surface according to the target, and reject semantics you cannot preserve. -See [Ecosystem Integrations](./ecosystem-integrations.mdx) to use an existing -adapter. +An adapter exports an Ack boundary contract to another schema system. This guide +shows how to choose the export surface, translate the schema and test the result. +To use an existing adapter, see [Ecosystem Integrations](./ecosystem-integrations.mdx). + +> **Quick start** +> +> - A JSON Schema target calls `toJsonSchema()`. +> - Other targets translate `toSchemaModel()` and reject what they cannot keep. +> - Test the exported contract. + +**Prerequisites:** read [JSON Schema Integration](./json-schema-integration.mdx), +which describes the rendered dialects and the +[adapter model](./json-schema-integration.mdx#adapter-model). + +**Done when:** your adapter exports a target document for real Ack schemas, fails +clearly on semantics it cannot keep, and has tests for both. ## Choose the export surface @@ -15,17 +27,17 @@ adapter. | Requires legacy Draft-7 | `schema.toJsonSchemaDraft7()` | Handle unsupported lowering explicitly. | | Uses a different schema language | `schema.toSchemaModel()` | Translate the canonical model and its metadata, or reject unsupported cases. | -Native Ack schemas render as Draft-7. Imported Draft 2020-12 resources retain +Native Ack schemas render as Draft-7. Imported Draft 2020-12 resources keep their dialect and resource semantics by default. Do not silently lower them or strip keywords to make a target accept the document. -Non-JSON adapters should consume `AckSchemaModel`, rather than walking runtime -`AckSchema` subclasses or reverse-engineering rendered JSON. That keeps wrapper, -codec, default, and discriminator handling in Ack's export layer. +Non-JSON adapters consume `AckSchemaModel`. Do not walk runtime `AckSchema` +subclasses or reverse-engineer rendered JSON. The model keeps wrapper, codec, +default and discriminator handling in Ack's export layer. ## JSON-map adapters -If the target accepts Ack's rendered JSON Schema, the conversion can be small: +If the target accepts Ack's rendered JSON Schema, the adapter can be small: ```dart compile=target-extension import 'package:ack/ack.dart'; @@ -35,84 +47,18 @@ extension TargetJsonSchemaExtension on AckSchema { } ``` -This is the approach used by `ack_firebase_ai` for the map-based -`GenerationConfig.responseJsonSchema` field. It does not convert to Firebase's -native `Schema` class or normalize a provider-specific subset. -The `ack_json_schema_builder` bridge similarly wraps the rendered map in -`jsb.Schema.fromMap(...)` and offers a separate Draft-7 lowering method. +`ack_firebase_ai` uses this approach for the map-based +`GenerationConfig.responseJsonSchema` field. `ack_json_schema_builder` wraps the +rendered map in `jsb.Schema.fromMap(...)` and adds a Draft-7 lowering method. -A response schema guides generation; validate returned data with Ack as well. -A target may not enforce refinements or every keyword it accepts. Make that -boundary explicit in the adapter's documentation. +A response schema guides generation. A target may not enforce refinements or +every keyword it accepts. State that boundary in the adapter's README, and tell +users to validate returned data with Ack. -## Non-JSON targets - -Route on the sealed model variants, then implement the semantics needed by the -target. A type-name match alone is not a complete conversion. - -| Model | Mapping to consider | -|---|---| -| `AckStringSchemaModel` | String literals/enums, length, pattern, and format | -| `AckIntegerSchemaModel`, `AckNumberSchemaModel` | Bounds, exclusivity, and numeric constraints | -| `AckBooleanSchemaModel`, `AckNullSchemaModel` | Boolean and null support | -| `AckObjectSchemaModel` | Properties, required keys, extra-property policy, and metadata | -| `AckArraySchemaModel` | Item schema and collection constraints | -| `AckAnyOfSchemaModel`, `AckOneOfSchemaModel`, `AckAllOfSchemaModel` | Branch semantics, discriminator metadata, and compositions | -| `AckRefSchemaModel` | Definitions, reference identity, and recursive resolution | -| `AckRawSchemaModel` | Imported resource dialect and vocabulary semantics | - -Apply the same checks recursively. A supported object can contain an unsupported -raw import or reference. Rejecting only unsupported roots is insufficient. - -### Presence, nullability, and additional properties - -Required-key membership and nullability are separate. A required nullable field -must still be present. Do not infer key presence from the field's Dart type or -map nullability onto a target's required marker without checking its semantics. - -`AckObjectSchemaModel.additionalProperties` can allow extras, disallow them, or -specify a schema for their values. Preserve that distinction. `Ack.map(...)` -uses object-model metadata without a fixed list of declared properties. - -For targets such as GraphQL, nullable values and non-null field markers need -explicit mapping. Reject structures the target cannot express rather than -silently replacing them with a string or unrestricted object. - -### Codecs, defaults, and warnings - -The model describes boundary values. A DateTime codec exports its string wire -shape; runtime constraints are projected only when their meaning survives that -mapping. One-way transforms do not give an adapter a reverse conversion. - -Inspect `model.allWarnings` for warning codes, messages, and JSON Pointer -locations, including in nested nodes and lazy definitions. For example, a default -that cannot be exported safely produces a warning. Runtime refinements are not -represented in the exported schema; a refinement on `Ack.string()` is omitted -without emitting a warning. Decide which warnings the adapter can return to -callers and which require an explicit failure. Do not promise that exporting a -schema preserves arbitrary runtime validation. - -Keep descriptions, export-safe defaults, and discriminator metadata when the -target supports them. A strict conversion mode can reject unsupported metadata -or semantics; document precisely what it checks. - -### References and imported resources +### Test the exported contract -A native lazy schema can produce `AckRefSchemaModel`. Supporting it means -resolving and emitting its definitions, not just copying a reference name. -Recursive graphs also need cycle handling; an unbounded recursive traversal is -not a reference implementation. - -An imported resource can produce `AckRawSchemaModel` directly or inside a -composition. It may use custom dialects, `$dynamicRef`, or vocabularies that -cannot be translated to the target. Implement those semantics or throw a clear -unsupported-conversion error. For JSON Schema targets, prefer the complete -renderer so definitions and resource identities remain intact. - -## Test the exported contract - -Use meaningful assertions against real Ack schemas. For the JSON-map extension -above, a small fixture can verify required keys, constraints, and codec boundaries: +Use real Ack schemas. For the extension above, a small fixture checks required +keys, constraints and codec boundaries: ```dart compile=target-test import 'package:ack/ack.dart'; @@ -141,30 +87,64 @@ void main() { } ``` -For a non-JSON adapter, test the actual target representation and its validation -behavior where a target validator is available. Include nullable and optional -fields, enums, compositions, extra-property rules, omitted runtime semantics, -and unsupported raw/reference cases. Test both nested and root cases. -For recursive/reference support, include a fixture with repeated and cyclic -references, not only an inline schema. +## Non-JSON targets + +Route on the sealed model variants, then implement the semantics the target +needs. A type-name match alone is not a complete conversion. + +| Model | Mapping to consider | +|---|---| +| `AckStringSchemaModel` | String literals/enums, length, pattern, and format | +| `AckIntegerSchemaModel`, `AckNumberSchemaModel` | Bounds, exclusivity, and numeric constraints | +| `AckBooleanSchemaModel`, `AckNullSchemaModel` | Boolean and null support | +| `AckObjectSchemaModel` | Properties, required keys, extra-property policy, and metadata | +| `AckArraySchemaModel` | Item schema and collection constraints | +| `AckAnyOfSchemaModel`, `AckOneOfSchemaModel`, `AckAllOfSchemaModel` | Branch semantics, discriminator metadata, and compositions | +| `AckRefSchemaModel` | Definitions, reference identity, and recursive resolution | +| `AckRawSchemaModel` | Imported resource dialect and vocabulary semantics | + +Apply the checks recursively. A supported object can contain an unsupported raw +import or reference, so rejecting only unsupported roots is not enough. + +For a non-JSON adapter, test the real target representation. Where the target +has a validator, test its validation behavior too. + +### Presence, nullability and additional properties + +- Do treat required-key membership and nullability as separate. A required nullable field must still be present. +- Do preserve the three `additionalProperties` cases: extras allowed, extras disallowed, and a schema for extra values. `Ack.map(...)` uses object-model metadata without declared properties. +- Do map nullable values and non-null markers explicitly, for example in GraphQL. +- Do not infer key presence from the Dart field type. +- Do not replace a structure the target cannot express with a string or an unrestricted object. Reject it. -When claiming imported JSON Schema compatibility, test a representative bundled -resource and its exported dialect. Do not treat a non-null conversion result as -proof that validation semantics survived. +### Codecs, defaults and warnings + +- Do export the wire shape of a codec. A `DateTime` codec exports its string shape. +- Do read `model.allWarnings` for codes, messages and JSON Pointer locations, including nested nodes and lazy definitions. A default that cannot be exported safely produces a warning. +- Do decide which warnings the adapter returns to callers and which cause a failure. +- Do keep descriptions, export-safe defaults and discriminator metadata when the target supports them. +- Do not expect a reverse conversion from a one-way transform. +- Do not promise that export preserves runtime validation. Runtime refinements are not in the exported schema, and a refinement on `Ack.string()` is omitted without a warning. + +See [Codecs](../core-concepts/codecs.mdx#codecs-and-json-schema) for what each codec exports. + +### References and imported resources + +- Do resolve and emit definitions for an `AckRefSchemaModel`. Copying the reference name is not enough. +- Do handle cycles in recursive graphs. Test repeated and cyclic references, not only inline schemas. +- Do implement, or reject with a clear unsupported-conversion error, an `AckRawSchemaModel` that uses custom dialects, `$dynamicRef` or vocabularies. +- Do not build your own renderer for JSON Schema targets. Use the complete renderer so definitions and resource identities stay intact. +- Do not treat a non-null result as proof that validation semantics survived. When you claim imported JSON Schema compatibility, test a representative bundled resource and its exported dialect. ## Add an adapter to this repository -Use an `ack_` package name and follow the nearest existing package's -layout and SDK constraints. Workspace membership lives in the root -`pubspec.yaml`; this repository has no `melos.yaml` package list. -Keep hosted sibling dependency constraints suitable for publishing. +Use an `ack_` package name. Follow the nearest existing package's layout +and SDK constraints. Workspace membership lives in the root `pubspec.yaml`; this +repository has no `melos.yaml` package list. Keep hosted sibling dependency +constraints suitable for publishing. Follow [CONTRIBUTING.md](https://github.com/btwld/ack/blob/main/CONTRIBUTING.md) -for checks, and [PUBLISHING.md](https://github.com/btwld/ack/blob/main/PUBLISHING.md) +for checks and [PUBLISHING.md](https://github.com/btwld/ack/blob/main/PUBLISHING.md) for coordinated versions and tag-only publishing. A new adapter needs a reviewed -integration before publication; the first package upload has a documented manual -bootstrap exception. Do not publish from a package-template checklist. - -Document the target's supported schema shapes, dialects, and explicit failures in -its README. Keep target-specific SDK examples in the adapter package instead of -copying a general package scaffold into every guide. +integration before publication. Document the supported schema shapes, dialects +and explicit failures in the adapter's README. diff --git a/docs/guides/custom-validation.mdx b/docs/guides/custom-validation.mdx index b7f913e3..fa02f3be 100644 --- a/docs/guides/custom-validation.mdx +++ b/docs/guides/custom-validation.mdx @@ -4,16 +4,12 @@ title: Custom Validation Rules While Ack provides many [built-in validation rules](../core-concepts/validation.mdx), you can extend them with your own value-level constraints or object-level refinement logic. -## Prerequisites - -- **[Validation Rules](/core-concepts/validation)**: Built-in constraints and how they work -- **[Schema Types](/core-concepts/schemas)**: Different schema types and their behavior -- **[Error Handling](/core-concepts/error-handling)**: How validation errors are structured - ## Creating a value constraint To add reusable validation that only depends on the field value, implement a `Constraint` that mixes in `Validator`. Attach the rule with `constrain()`. It throws `ArgumentError` if the constraint lacks that validator. +`constraintKey` is a stable identifier for the rule. It identifies the rule in a `ConstraintError`. `description` explains the rule in words. The `Validator` mixin supplies the check: `isValid` decides, and `buildMessage` writes the failure text. To export the rule to JSON Schema, also mix in `JsonSchemaSpec` and implement `toJsonSchema()`. + ```dart compile=positive-constraint import 'package:ack/ack.dart'; @@ -57,9 +53,35 @@ final result = signUpSchema.safeParse({ print(result.isFail); // true ``` +## Transforming values with `.transform()` + +Use `.transform()` to convert a validated value into another value. The callback receives the non-null validated runtime value. Handle `null` on the surrounding schema. A transform is one-way. For a reversible conversion, use a [codec](../core-concepts/codecs.mdx). + +```dart compile=body +final upperSchema = Ack.string().transform((s) => s.toUpperCase()); + +// Type transformation +final dateSchema = Ack.string() + .matches(r'^\d{4}-\d{2}-\d{2}$') + .transform((s) => DateTime.parse(s)); +``` + +Convert a boundary `"true"`/`"false"` string into a `bool`: + +```dart compile=body +final boolFromString = Ack.enumString(['true', 'false']) + .transform((s) => s == 'true'); + +boolFromString.safeParse('true'); // ✅ runtime value: true +boolFromString.safeParse('false'); // ✅ runtime value: false +boolFromString.safeParse(true); // ❌ FAIL: string schema rejects bool +``` + +If the callback throws an `Exception`, the result is a `SchemaTransformError`. A Dart `Error`, such as a `StateError`, is a programming failure and propagates. + ## Overriding error messages -The optional `message` parameter on `.constrain()` lets you customize the failure message. +The optional `message` parameter on `.constrain()` customizes the failure message. The text that `.message` returns includes the `Constraints not met: ` prefix from `SchemaConstraintsError`. ```dart compile=price-message final schema = Ack.double() @@ -71,29 +93,20 @@ if (result.isFail) { } ``` -## Organizing reusable constraints +`.refine()` accepts the same `message:` parameter, and a refine failure prints its message without the prefix. Among the built-in string constraints, `.matches()` and `.contains()` accept `message:`; the others use their standard messages. -Move `IsPositiveConstraint` into `validation/constraints.dart` to share it across schemas. - -```dart compile=custom-constraint-library -// file: schemas/user_schema.dart -import 'package:ack/ack.dart'; -import '../validation/constraints.dart'; - -final userSchema = Ack.object({ - 'age': Ack.integer(), - 'salary': Ack.double().constrain(IsPositiveConstraint()), -}); -``` +To reuse a constraint across schemas, put it in a shared library and import it. -## When to use custom logic +## Choosing a tool -- **Complex business rules:** Domain-specific checks that built-ins don’t cover. -- **Cross-field relationships:** Comparing password and confirmation fields, for example. -- **Reusable patterns:** Common rules applied across multiple schemas. -- **External service checks:** Validating against APIs or databases (beware of latency). +| Need | Use | Error type on failure | +| --- | --- | --- | +| A rule that built-in constraints already express | Chain the [built-in constraints](../core-concepts/validation.mdx) | `SchemaConstraintsError` | +| A reusable check on one value | `constrain` with a `Constraint` | `SchemaConstraintsError` | +| A rule across fields, or a one-off check | `refine` | `SchemaValidationError` | +| A value conversion | `transform` (one-way) or a [codec](../core-concepts/codecs.mdx) (reversible) | `SchemaTransformError` when a transform or decoder throws an `Exception`; `SchemaEncodeError` when an encoder throws one. A Dart `Error` propagates. | -Chaining built-in constraints is often enough for simple cases. Use custom constraints or refinements when you need extra flexibility. +Checks against external services add latency. Run them outside the schema when you can. ## Next steps diff --git a/docs/guides/ecosystem-integrations.mdx b/docs/guides/ecosystem-integrations.mdx index bd30b6e1..1c657e42 100644 --- a/docs/guides/ecosystem-integrations.mdx +++ b/docs/guides/ecosystem-integrations.mdx @@ -2,192 +2,22 @@ title: Ecosystem Integrations --- -Reuse an `AckSchema` (or a `@Schemable()` model's `Model.schema`) across Ack's official adapter packages. Each adapter has its own supported schema shapes; MCP tool inputs, for example, must render as a non-null object root. +Ack's official adapters reuse one `AckSchema` (or a `@Schemable()` model's +`Model.schema`) in another package. Pick the adapter for your target, then follow +its README. -| Adapter Package | Target Ecosystem | Primary Entry Point | +| Adapter | Use it to | Learn more | | --- | --- | --- | -| **`ack_mcp_dart`** | [Model Context Protocol (`mcp_dart`)](https://pub.dev/packages/mcp_dart) | `server.registerAckTool(...)`, `schema.toMcpToolInputSchema()` | -| **`ack_firebase_ai`** | [Firebase AI Logic (`firebase_ai` / Gemini)](https://pub.dev/packages/firebase_ai) | `schema.toFirebaseAiResponseJsonSchema()` | -| **`ack_json_schema_builder`** | [`json_schema_builder`](https://pub.dev/packages/json_schema_builder) | `schema.toJsonSchemaBuilder()`, `jsbSchema.toAckSchema()` | +| `ack_mcp_dart` | Register [`mcp_dart`](https://pub.dev/packages/mcp_dart) tools with validated, typed input. | [README](https://github.com/btwld/ack/blob/main/packages/ack_mcp_dart/README.md) | +| `ack_firebase_ai` | Send a response schema to [`firebase_ai`](https://pub.dev/packages/firebase_ai) (Gemini) structured output. | [README](https://github.com/btwld/ack/blob/main/packages/ack_firebase_ai/README.md) | +| `ack_json_schema_builder` | Convert between `AckSchema` and [`json_schema_builder`](https://pub.dev/packages/json_schema_builder) in both directions. | [README](https://github.com/btwld/ack/blob/main/packages/ack_json_schema_builder/README.md) | ---- - -## 1. Define a Model or Schema Once - -```dart title="lib/weather_models.dart" compile=model -import 'package:ack/ack.dart'; - -part 'weather_models.g.dart'; - -@Schemable(description: 'Parameters for querying current weather.') -final class const WeatherQuery({ - /// @description City and country, e.g. "Tokyo, JP". - @HasMinLength(2) required final String city, - final String units = 'celsius', -}) with _$WeatherQueryAck { - static final schema = WeatherQuerySchema.schema; - static final fromJson = WeatherQuerySchema.fromJson; -} - -@Schemable(description: 'Current weather report.') -final class const WeatherReport({ - required final String city, - required final double temperatureC, -}) with _$WeatherReportAck { - static final schema = WeatherReportSchema.schema; - static final fromJson = WeatherReportSchema.fromJson; -} -``` - ---- - -## 2. MCP Tool Servers (`ack_mcp_dart`) - -`ack_mcp_dart` bridges `AckSchema` with `McpServer` from `package:mcp_dart/mcp_dart.dart`. It exports the tool's input JSON Schema, validates and decodes incoming arguments before your callback runs, and formats Ack validation failures as MCP `CallToolResult(isError: true)` responses. MCP's structural validation runs first; its failures do not reach the Ack callback. - -### Install - -```bash -dart pub add ack:^2.0.0-beta.3 ack_mcp_dart:^2.0.0-beta.3 mcp_dart -``` - -### Register a typed input tool - -Pass `WeatherQuery.schema` through `input`. The callback receives a `WeatherQuery` and returns a `CallToolResult`; output validation and serialization belong to the callback: - -```dart compile=library -import 'dart:convert'; - -import 'package:ack_mcp_dart/ack_mcp_dart.dart'; -import 'package:mcp_dart/mcp_dart.dart'; - -import 'weather_models.dart'; - -void registerWeatherTools(McpServer server) { - server.registerAckTool( - 'get_weather', - description: 'Fetch the current weather for a city.', - input: WeatherQuery.schema, - callback: (query, extra) { - final report = WeatherReport( - city: query.city, - temperatureC: 21.5, - ); - // Generated toJson validates and encodes the report. - final json = report.toJson(); - return CallToolResult( - content: [TextContent(text: jsonEncode(json))], - structuredContent: json, - ); - }, - ); -} -``` - -For manual registration, use `schema.toMcpToolInputSchema()`, -`parseMcpToolArguments(schema, args)`, and -`ackValidationErrorToCallToolResult(error, toolName: name)`. On the client, -validate structured output explicitly with -`WeatherReport.schema.safeParse(result.structuredContent)`. -The adapter does not register or advertise output schemas; use `mcp_dart` -directly when those are required. - ---- - -## 3. Firebase AI / Gemini Structured Outputs (`ack_firebase_ai`) - -`ack_firebase_ai` renders an Ack schema as the JSON-compatible map accepted by -`GenerationConfig.responseJsonSchema`. Use a model that supports that field, -initialize Firebase in your app, and validate the response with the same Ack -schema. This is not a converter to Firebase's native `Schema` type or a function -declaration helper. - -### Install - -```bash -flutter pub add ack:^2.0.0-beta.3 ack_firebase_ai:^2.0.0-beta.3 firebase_ai firebase_core -``` - -### Generate and validate structured output - -```dart compile=library -import 'dart:convert'; - -import 'package:ack_firebase_ai/ack_firebase_ai.dart'; -import 'package:firebase_ai/firebase_ai.dart'; - -import 'weather_models.dart'; - -Future askGeminiWeather( - String prompt, { - required String modelName, -}) async { - final model = FirebaseAI.googleAI().generativeModel( - model: modelName, - generationConfig: GenerationConfig( - responseMimeType: 'application/json', - responseJsonSchema: WeatherReport.schema.toFirebaseAiResponseJsonSchema(), - ), - ); - - final response = await model.generateContent([Content.text(prompt)]); - final decoded = jsonDecode(response.text ?? 'null'); - - // Validate and decode Gemini's response into WeatherReport - return WeatherReportSchema.parse(decoded); -} -``` - -The adapter returns `schema.toJsonSchema()` unchanged. It does not append -constraint descriptions or adapt keywords to a provider-specific subset. -Response schemas guide generation; Ack validation remains authoritative for -constraints and refinements that the provider does not enforce. - ---- - -## 4. `json_schema_builder` Bridge (`ack_json_schema_builder`) - -`ack_json_schema_builder` provides bidirectional conversion between `AckSchema` and `package:json_schema_builder`: - -### Install - -```bash -dart pub add ack:^2.0.0-beta.3 ack_json_schema_builder:^2.0.0-beta.3 json_schema_builder -``` - -### Convert in both directions - -```dart -import 'package:ack/ack.dart'; -import 'package:ack_json_schema_builder/ack_json_schema_builder.dart'; -import 'package:json_schema_builder/json_schema_builder.dart' as jsb; - -import 'weather_models.dart'; - -void main() { - // Native Ack schemas render as Draft-7; imported 2020-12 resources are preserved. - final jsb.Schema builderSchema = WeatherQuery.schema.toJsonSchemaBuilder(); - - // Need legacy Draft-7 definitions lowering instead? - final jsb.Schema draft7Schema = WeatherQuery.schema.toJsonSchemaBuilderDraft7(); - - // 2. json_schema_builder Schema -> executable AckSchema - final AckSchema importedValidator = jsb.Schema.object( - properties: {'city': jsb.Schema.string(minLength: 2)}, - required: ['city'], - ).toAckSchema(assertFormats: true); - - print(builderSchema.value); - print(draft7Schema.value); - final valid = importedValidator.parse({'city': 'Lisbon'}); - print(valid); -} -``` - ---- +Adapters render the schema for the target. Ack validation stays the authority +for rules that the target does not enforce, so validate the data with Ack as +well. -## Building Your Own Adapter Package +## Building your own adapter package -Want to convert Ack schemas to another target format (OpenAPI, Protobuf, GraphQL, or another LLM SDK)? Traverse `schema.toSchemaModel()` (`AckSchemaModel`). See: -- [Adapter Package Quickstart](./schema-converter-quickstart.mdx) -- [Creating Adapter Packages](./creating-schema-converter-packages.mdx) +To translate Ack schemas to another target, such as OpenAPI, Protobuf, GraphQL or +another LLM SDK, see +[Creating Adapter Packages](./creating-schema-converter-packages.mdx). diff --git a/docs/guides/flutter-form-validation.mdx b/docs/guides/flutter-form-validation.mdx index cd650260..fa1b612a 100644 --- a/docs/guides/flutter-form-validation.mdx +++ b/docs/guides/flutter-form-validation.mdx @@ -1,27 +1,40 @@ --- -title: Form Validation in Flutter with Ack +title: Flutter Form Validation --- -This guide shows how to use Ack for validating forms in Flutter applications. +Use Ack schemas as the validators of a Flutter `Form`. When you finish, each +`TextFormField` shows the message of its Ack schema, and the submit button +validates the whole form. ## Prerequisites -- **Flutter basics**: Creating widgets, managing state, and using forms -- **Ack fundamentals**: Creating schemas and validation (see [Quickstart Tutorial](/getting-started/quickstart-tutorial)) -- **Validation rules**: Built-in constraints (see [Validation Rules](/core-concepts/validation)) +- A Flutter project with Ack installed. See [Installation](../getting-started/installation.mdx). +- Basic knowledge of Flutter forms and state. +- The [Quickstart Tutorial](../getting-started/quickstart-tutorial.mdx) and [Validation Rules](../core-concepts/validation.mdx). -Install Ack in your Flutter project: +## 1. Define one schema per field -```bash -flutter pub add ack:^2.0.0-beta.3 -``` +Declare each schema as a field of your `State` class. Each schema lists the +rules for one input. See [Schema Types](../core-concepts/schemas.mdx) for the +types. + +## 2. Turn a schema into a form validator + +`TextFormField.validator` returns `String?`: an error message, or `null` when the +input is valid. Write one helper that runs `safeParse` and returns the message. +For an invalid email, the message starts with +`Constraints not met: Invalid email format`. + +## 3. Attach the helper to each field + +Pass `_validate(schema)` to each field. Set +`autovalidateMode: AutovalidateMode.onUserInteraction` to validate while the user +types. To change the text, pass `message:` to a constraint. See +[Overriding error messages](./custom-validation.mdx#overriding-error-messages). -## Basic form validation with `TextFormField` +## 4. Validate the form on submit -Ack works with Flutter form APIs by running `safeParse` inside -`TextFormField.validator` and returning a `String?` error message -(`null` when valid). For example, an invalid email can produce a message that -starts with `Constraints not met: Invalid email format`. +Call `_formKey.currentState!.validate()`. It runs every field validator. ```dart compile=sign-up import 'package:ack/ack.dart'; @@ -35,82 +48,72 @@ class SignUpForm extends StatefulWidget { } class _SignUpFormState extends State { - // GlobalKey to manage Form state final _formKey = GlobalKey(); - - // Controllers for input fields final _usernameController = TextEditingController(); final _emailController = TextEditingController(); final _passwordController = TextEditingController(); + final _confirmPasswordController = TextEditingController(); - // Define Ack schemas for validation rules - // See: [Schema Types](../core-concepts/schemas.mdx), [Validation Rules](../core-concepts/validation.mdx) final _usernameSchema = Ack.string() - .minLength(3) - .maxLength(20) - .matches(r'^[a-zA-Z0-9_]+$') - .notEmpty(); + .minLength(3) + .maxLength(20) + .matches(r'^[a-zA-Z0-9_]+$'); - final _emailSchema = Ack.string() - .email() - .notEmpty(); + final _emailSchema = Ack.string().email(); final _passwordSchema = Ack.string() - .minLength(8) - .matches(r'.*[A-Z].*') - .matches(r'.*[a-z].*') - .matches(r'.*[0-9].*') - .notEmpty(); + .minLength(8) + .matches(r'.*[A-Z].*') + .matches(r'.*[a-z].*') + .matches(r'.*[0-9].*'); + + final _confirmPasswordSchema = Ack.string().notEmpty(); + + FormFieldValidator _validate(AckSchema schema) { + return (value) { + final result = schema.safeParse(value); + return result.isFail ? result.getError().message : null; + }; + } @override Widget build(BuildContext context) { return Form( - key: _formKey, // Associate the key with the Form + key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - // Username Field TextFormField( controller: _usernameController, decoration: const InputDecoration(labelText: 'Username'), - // Use the schema's validate method in the validator - validator: (value) { - final result = _usernameSchema.safeParse(value); - // Return the error message if validation fails - // See: [Error Handling](../core-concepts/error-handling.mdx) - return result.isFail ? result.getError().message : null; - }, + validator: _validate(_usernameSchema), autovalidateMode: AutovalidateMode.onUserInteraction, ), const SizedBox(height: 16), - - // Email Field TextFormField( controller: _emailController, decoration: const InputDecoration(labelText: 'Email'), keyboardType: TextInputType.emailAddress, - validator: (value) { - final result = _emailSchema.safeParse(value); - return result.isFail ? result.getError().message : null; - }, + validator: _validate(_emailSchema), autovalidateMode: AutovalidateMode.onUserInteraction, ), const SizedBox(height: 16), - - // Password Field TextFormField( controller: _passwordController, decoration: const InputDecoration(labelText: 'Password'), obscureText: true, - validator: (value) { - final result = _passwordSchema.safeParse(value); - return result.isFail ? result.getError().message : null; - }, + validator: _validate(_passwordSchema), + autovalidateMode: AutovalidateMode.onUserInteraction, + ), + const SizedBox(height: 16), + TextFormField( + controller: _confirmPasswordController, + decoration: const InputDecoration(labelText: 'Confirm password'), + obscureText: true, + validator: _validate(_confirmPasswordSchema), autovalidateMode: AutovalidateMode.onUserInteraction, ), const SizedBox(height: 24), - - // Submit Button ElevatedButton( onPressed: _submitForm, child: const Text('Sign Up'), @@ -121,37 +124,87 @@ class _SignUpFormState extends State { } void _submitForm() { - // Validate the entire form using the GlobalKey if (_formKey.currentState!.validate()) { - // If the form is valid, display a Snackbar or proceed. ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Processing Data')), ); - print('Form is valid!'); - print('Username: ${_usernameController.text}'); - print('Email: ${_emailController.text}'); - // Usually, you would send this data to a server - } else { - print('Form is invalid.'); } } @override void dispose() { - // Dispose controllers when the widget is removed from the widget tree _usernameController.dispose(); _emailController.dispose(); _passwordController.dispose(); + _confirmPasswordController.dispose(); super.dispose(); } } ``` -Key steps: define an `AckSchema` per field; in `TextFormField.validator`, call `schema.safeParse(value)` and return `result.getError().message` on failure; trigger full-form validation via `_formKey.currentState!.validate()`; set `autovalidateMode: AutovalidateMode.onUserInteraction` for real-time feedback. Pass `message:` inside the schema definition for [custom error messages](../core-concepts/error-handling.mdx#custom-error-messages). +The field schemas do not call `.notEmpty()` after `.minLength(...)` or +`.email()`, because those rules already reject an empty string. + +## 5. Check the password confirmation + +A field validator sees one value, so it cannot compare two fields. To check that +the passwords match, validate the whole form map with an object schema. This +version replaces `_submitForm` in the example above and uses the +`_confirmPasswordController` declared there. The cross-field rule uses `refine`. +See [Cross-field rules with `.refine()`](./custom-validation.mdx#cross-field-rules-with-refine). + +```dart compile=form-submission +late final _formSchema = Ack.object({ + 'username': _usernameSchema, + 'email': _emailSchema, + 'password': _passwordSchema, + 'confirmPassword': Ack.string().notEmpty(), +}).refine( + (data) => data['password'] == data['confirmPassword'], + message: 'Passwords do not match', +); + +/// The form-level message to show near the submit button, or `null`. +String? _formError; + +void _submitForm() { + // Show every field's error, including fields the user has not touched. + final fieldsValid = _formKey.currentState!.validate(); + + final formData = { + 'username': _usernameController.text, + 'email': _emailController.text, + 'password': _passwordController.text, + 'confirmPassword': _confirmPasswordController.text, + }; + + final result = _formSchema.safeParse(formData); + final error = result.isFail ? result.getError() : null; + setState(() { + _formError = error is SchemaValidationError ? error.message : null; + }); + + if (fieldsValid && result.isOk) { + // Send formData to your server. + } +} +``` + +The two kinds of failure arrive differently: + +- A failed `refine`, such as mismatched passwords, is a `SchemaValidationError` + at the root path `#`. Show its message at form level, for example in a `Text` + widget that reads `_formError`. +- Field failures arrive as a `SchemaNestedError` at `#`; each child error has the + field's path, such as `#/email`. The field validators from step 3 already show + those messages. + +See [Understanding SchemaError](../core-concepts/error-handling.mdx#understanding-schemaerror) +for the error members. -## Real-time validation with `TextField` +## Optional: validate a `TextField` without a `Form` -Without a `Form` widget, listen to controller changes and update the error state directly. +Without a `Form` widget, listen to the controller and store the error in state. ```dart compile=library import 'package:ack/ack.dart'; @@ -166,36 +219,23 @@ class RealtimeValidationField extends StatefulWidget { class _RealtimeValidationFieldState extends State { final _emailController = TextEditingController(); - String? _emailErrorText; // State variable to hold the error message - - // Define the schema - final _emailSchema = Ack.string() - .email() - .notEmpty(); + final _emailSchema = Ack.string().email(); + String? _emailErrorText; @override void initState() { super.initState(); - // Add listener to validate on change _emailController.addListener(_validateEmail); } void _validateEmail() { final text = _emailController.text; - // Only validate if the field is not empty (or on first interaction) - // Adjust logic based on desired UX (e.g., validate after first blur) - if (text.isNotEmpty) { - final result = _emailSchema.safeParse(text); - // Update the error state variable, triggering a rebuild - setState(() { - _emailErrorText = result.isFail ? result.getError().message : null; - }); - } else { - // Clear error if field becomes empty - setState(() { - _emailErrorText = null; - }); - } + final result = _emailSchema.safeParse(text); + setState(() { + _emailErrorText = text.isNotEmpty && result.isFail + ? result.getError().message + : null; + }); } @override @@ -206,7 +246,6 @@ class _RealtimeValidationFieldState extends State { controller: _emailController, decoration: InputDecoration( labelText: 'Email', - // Display the error text from the state variable errorText: _emailErrorText, ), keyboardType: TextInputType.emailAddress, @@ -223,47 +262,6 @@ class _RealtimeValidationFieldState extends State { } ``` -Key steps: hold a state variable for the error message; add a listener to `TextEditingController` in `initState`; call `schema.safeParse()` inside the listener and `setState` with the result; remove the listener in `dispose`. - -## Validating entire forms on submission - -Instead of validating field by field, validate the complete data structure on submission using [`Ack.object`](../core-concepts/schemas.mdx#object). - -```dart compile=form-submission -// Define a schema for the whole form data -late final _formSchema = Ack.object({ - 'username': _usernameSchema, // Reuse field schemas - 'email': _emailSchema, - 'password': _passwordSchema, - 'confirmPassword': Ack.string() - .notEmpty(), -}).refine( - (data) => data['password'] == data['confirmPassword'], - message: 'Passwords do not match', -); - -void _submitForm() { - // Gather all form data into a map - final formData = { - 'username': _usernameController.text, - 'email': _emailController.text, - 'password': _passwordController.text, - 'confirmPassword': _confirmPasswordController.text, // Assume this controller exists - }; - - // Validate the entire map - final result = _formSchema.safeParse(formData); - - if (result.isOk) { - print('Entire form data is valid!'); - // Submit formData - } else { - final error = result.getError(); - print(error); // One path: message line per failure - // You might need to map the error path back to specific fields - // to display errors if not using TextFormField validators. - } -} -``` +## Next step -Key steps: build an [`Ack.object`](../core-concepts/schemas.mdx#object) schema that reuses your field schemas; add [`.refine()`](./custom-validation.mdx#cross-field-rules-with-refine) for cross-field rules; call `safeParse` on the full form map at submission. On failure, use [`error.path`](../core-concepts/error-handling.mdx#understanding-schemaerror) to map errors back to specific fields when not using `TextFormField`'s built-in display. +Write your own rules in [Custom Validation](./custom-validation.mdx). diff --git a/docs/guides/json-schema-integration.mdx b/docs/guides/json-schema-integration.mdx index 6c7acf45..ff075f53 100644 --- a/docs/guides/json-schema-integration.mdx +++ b/docs/guides/json-schema-integration.mdx @@ -2,25 +2,14 @@ title: JSON Schema Integration --- -Your Ack [schema](../core-concepts/schemas.mdx) already describes your data's shape — so you can import and export JSON Schema (preserving Draft 2020-12 resources for imported schemas and emitting Draft-7 for native schemas) and reuse it to document an API, drive a form library, or define an LLM tool, all from one source of truth. +Export any Ack [schema](../core-concepts/schemas.mdx) as JSON Schema, and import a published JSON Schema document as an Ack schema. -Draft-7 imports reject the `dependencies` keyword. Convert the schema to Draft -2020-12 and use `dependentRequired` or `dependentSchemas`. Draft-7 lowering -also rejects `dependencies` in imported 2020-12 schemas and reports the -keyword’s JSON Pointer. - -Imported schemas share the parse input limit of 100 nested lists or maps -along any path. +- **Export:** `toJsonSchema()` emits Draft-7 for native schemas. Imported schemas keep their Draft 2020-12 resources. See [Exporting JSON Schema](#exporting-json-schema). +- **Import:** `Ack.fromJsonSchema()` reads Draft 2020-12 and Draft-7 documents. See [Importing published schemas](#importing-published-schemas). +- **Models:** the generator compiles `.schema.json` files into Dart models. See [Generating Dart models from `.schema.json` files](#generating-dart-models-from-schemajson-files). ## Importing published schemas -Import schemas from sources you trust. The cost of compiling and validating a -schema can grow with nested composition and repeated references. Reuse the -compiled validator when checking multiple values against the same schema. -A `$dynamicRef` cycle or a schema nested several thousand levels deep can -throw `StackOverflowError` during import -([tracked for 2.0.x in #279](https://github.com/btwld/ack/issues/279)). - Use strict `Ack.fromJsonSchema()` to turn a decoded JSON Schema document (a map or boolean, not a JSON string) into an `AckSchema`. The input dialect is draft 2020-12 or Draft-7 @@ -60,13 +49,16 @@ Required means **key present**, not **non-null**; an omitted `type` does not implicitly require an object, string, or array. Integral numbers such as `1.0` match `integer`, and null array elements are supported. -### Design: reuse the existing export boundary +**Limits:** Import schemas from sources you trust. The cost of compiling and +validating a schema can grow with nested composition and repeated references. +Reuse the compiled validator when checking multiple values against the same +schema. A `$dynamicRef` cycle or a schema nested several thousand levels deep +can throw `StackOverflowError` during import +([tracked for 2.0.x in #279](https://github.com/btwld/ack/issues/279)). -`AckSchema.toJsonSchema()` remains the export API. Imported schemas participate -in the same `AckSchema` → `AckSchemaModel` → JSON Schema path as native schemas; -the builder bridge delegates to that path too. There is no second public -exporter or dependency on a Flutter runtime. +### Importing an existing export +Imported schemas export through the same `toJsonSchema()` as native schemas. You can import an existing export directly: ```dart compile=library @@ -75,7 +67,6 @@ final AckSchema schema = Ack.fromJsonSchema(document); final exportedAgain = schema.toJsonSchema(); ``` -The source document and executable validator are distinct. `Ack.fromJsonSchema()` is the single import entry point and always imports strictly. The importer preserves supported JSON validation semantics, not the original Dart declaration: JSON cannot recover codecs, Dart model @@ -147,6 +138,14 @@ treat `format` as an annotation unless configured to assert it. ### Supported import subset +Draft-7 imports reject the `dependencies` keyword. Convert the schema to Draft +2020-12 and use `dependentRequired` or `dependentSchemas`. Draft-7 lowering +also rejects `dependencies` in imported 2020-12 schemas and reports the +keyword’s JSON Pointer. + +Imported schemas share the parse input limit of 100 nested lists or maps +along any path. + | Area | Keywords | | --- | --- | | Schemas and types | Boolean schemas, `type` (including lists and `null`) | @@ -160,22 +159,26 @@ treat `format` as an annotation unless configured to assert it. | Annotations | `title`, `description`, `default`, `examples`, `$comment`, `readOnly`, `writeOnly`, `deprecated`, `contentEncoding`, `contentMediaType`, `contentSchema`, `x-*` vendor extensions | | Format | Full Draft 2020-12 format suite and standard numeric formats (`int32`, `int64`, `uint32`, `uint64`, `float`, `double`); asserted when `assertFormats: true` or `$vocabulary` enables `format-assertion` | -`pattern` compiles with ECMA-262's `u` flag, as the JSON Schema Test Suite -requires and Ajv does by default. `.` matches one code point, so -`pattern: "^.$"` accepts `"😀"`, and `\p{...}` is a Unicode property escape. -A pattern that is invalid in Unicode mode fails import with an -`invalid_schema` diagnostic. For example, an escaped hyphen outside a character -class (`^\d{3}\-\d{4}$`) is invalid; write the hyphen unescaped. -`Ack.string().matches()` uses Dart's default `RegExp`, without `u`. A native -pattern can match differently after export and import, and a native pattern -that is invalid in Unicode mode exports a schema that this importer and Ajv -reject. +### Differences between native Ack and imported schemas -Both native `.multipleOf()` and imported `multipleOf` divide exactly on the -decimal digits of the number, as the JSON Schema Test Suite requires, so `0.3` -and `0.6` are multiples of `0.1`, `1e308` is a multiple of `0.5`, and an -unrounded binary-float sum such as `0.1 + 0.2` (`0.30000000000000004`) is not. +| Keyword | Native Ack schema | Imported schema | +| --- | --- | --- | +| `matches` / `pattern` | `Ack.string().matches()` uses Dart's default `RegExp`, without `u`. | `pattern` compiles with ECMA-262's `u` flag. `.` matches one code point, and `\p{...}` is a Unicode property escape. A pattern that is invalid in Unicode mode fails import with an `invalid_schema` diagnostic. | +| `multipleOf` | Divides exactly on the decimal digits of the number. | Same behavior. | +| `format` | Constraints such as `email()` always assert. | An annotation by default. It asserts with `assertFormats: true` or a `format-assertion` vocabulary. | + +A native pattern can match differently after export and import. A native +pattern that is invalid in Unicode mode exports a schema that this importer and +Ajv reject. For example, an escaped hyphen outside a character class +(`^\d{3}\-\d{4}$`) is invalid in Unicode mode; write the hyphen unescaped. +`pattern` compiles with the `u` flag as the JSON Schema Test Suite requires +and Ajv does by default, so `pattern: "^.$"` accepts `"😀"`. + +Both native `.multipleOf()` and imported `multipleOf` divide exactly, as the JSON Schema Test Suite requires, +so `0.3` and `0.6` are multiples of `0.1`, `1e308` is a multiple of `0.5`, and +an unrounded binary-float sum such as `0.1 + 0.2` (`0.30000000000000004`) is +not. Unknown keywords, including non-`x-*` keywords, are accepted as annotations. An unsupported vocabulary marked as required (`true`) in `$vocabulary` fails @@ -240,9 +243,10 @@ validators assert international hostname and email formats. Add `unorm_dart` to the consuming package's runtime `dependencies` with `dart pub add unorm_dart` before building. -`ack_generator:ack_json_schema` emits `.schema.dart` (declaring -`part '.schema.g.dart';`), which `ack_generator:ack_generator` compiles -in the same `dart run build_runner build` pass: +`ack_generator:ack_json_schema` emits `.schema.dart`. When the file has +typed models, it declares `part '.schema.g.dart';`, which +`ack_generator:ack_generator` compiles in the same `dart run build_runner build` +pass: ```dart compile=person-schema import 'person.schema.dart'; @@ -263,6 +267,15 @@ print(person.toJson()); // {'name': 'Ada', 'age': 36} - For programmatic code generation outside `build_runner`, call `generateAckSchemaLibrary()` from `package:ack_generator/ack_generator.dart`. +Named `$defs` entries produce models. A schema with root assertions also +produces `Root`, or `DocumentRoot` when `$defs/Root` already uses that name. +A file whose models are all validated value models has no `part` directive and +no `.g.dart` file. `Model.parse(value)` returns a wrapper whose immutable +`value` is the validated JSON value, and `encode`, `safeEncode`, and `toJson()` +validate it again on output. Value models have no typed fields or typed +`copyWith`. The [`ack_generator` README](https://pub.dev/packages/ack_generator) +lists every builder option. + ### Validation errors When a value fails a keyword of an imported schema, the error is a @@ -304,34 +317,15 @@ empty when the root schema is `false`. ### Importing json_schema_builder models -The existing bridge works in both directions: - -```dart compile=library -import 'package:ack/ack.dart'; -import 'package:ack_json_schema_builder/ack_json_schema_builder.dart'; -import 'package:json_schema_builder/json_schema_builder.dart' as jsb; - -final AckSchema ackSchema = - jsb.Schema.string(minLength: 2).toAckSchema(); -final builderSchema = ackSchema.toJsonSchemaBuilder(); -``` - -`toAckSchema({baseUri, documents, assertFormats, unicodeNormalizer})` returns -the validator directly and accepts `Map` bundles. Pass -`unicodeNormalizer: unorm.nfkc` from `package:unorm_dart` to opt in to -[NFKC normalization](#importing-format) for international format checks. -`toJsonSchemaBuilder()` preserves imported Draft 2020-12 resources by default. -Use `toJsonSchemaBuilderDraft7()` when Draft-7 lowering is required. - -### A2UI compatibility and verification +The `ack_json_schema_builder` adapter converts between `json_schema_builder` +schemas and Ack schemas, and its `toAckSchema({baseUri, documents, assertFormats, unicodeNormalizer})` +accepts the same import options as `Ack.fromJsonSchema()`. Usage, including +[NFKC normalization](#importing-format), lives in the +[package README](https://github.com/btwld/ack/blob/main/packages/ack_json_schema_builder/README.md). -Offline regression fixtures pin five representative A2UI v0.9 protocol schemas -to upstream commit `f5e945a93da36a5d126228f2ad6fbe68809ef8f7`. All five A2UI -v0.9 schemas (including the basic catalog with `unevaluatedProperties`, -conditionals, and meta-schema references) import and validate cleanly in Ack 2.0, -and the full upstream JSON Schema Draft 2020-12 test suite passes offline. +Offline regression fixtures pin five A2UI v0.9 protocol schemas, and the upstream JSON Schema Draft 2020-12 test suite passes offline. -## Generating JSON schemas +## Exporting JSON Schema Call `toJsonSchema()` on any `AckSchema` instance. This uses the same renderer as `schema.toSchemaModel().toJsonSchema()`. Native schemas emit Draft-7 and imported schemas preserve their resources. @@ -365,37 +359,6 @@ void main() { } ``` -> **Building an adapter package?** Most users only need `toJsonSchema()` -> (above). To convert Ack schemas to another target format, render from -> `schema.toSchemaModel()` (the canonical `AckSchemaModel`) rather than the JSON -> Schema map. Start with the [adapter quickstart](./schema-converter-quickstart.mdx), -> then use the [complete adapter authoring guide](./creating-schema-converter-packages.mdx) -> for architecture and testing guidance. - -## Adapter model - -Use `toSchemaModel()` for a reusable, target-independent view of an Ack schema: - -```dart compile=exported-model -final model = userSchema.toSchemaModel(); -final jsonSchemaMap = model.toJsonSchema(); - -for (final warning in model.allWarnings) { - print('${warning.path} ${warning.code}: ${warning.message}'); -} -``` - -`model.warnings` holds the node's own warnings. The builder leaves their -`path` null. `model.allWarnings` yields the node's warnings first, then its -definition warnings, then its descendants' warnings. It fills null paths with -fragment JSON Pointers like `#` and `#/anyOf/0/properties/a~1b`, using RFC 6901 -token escaping without percent-encoding. It rebases any supplied -`#`-prefixed path to the warning's node and passes other paths through unchanged. - -`AckSchemaModel` describes the boundary values a schema accepts and exports, keeping adapter metadata such as property ordering and discriminator info. Native models render as Draft-7-compatible JSON Schema. Imported models -preserve supported Draft 2020-12 resources. Adapter renderers add -provider-specific hints. - **Output JSON (JSON Schema Object):** ```json @@ -477,30 +440,34 @@ provider-specific hints. Ack maps its [built-in constraints](../core-concepts/validation.mdx) to corresponding JSON Schema keywords: -| Ack Constraint or Schema | JSON Schema Keyword | Notes | +| Ack constraint or schema | JSON Schema keyword | Notes | | :----------------------- | :------------------ | :---- | -| [`minLength(n)`](../core-concepts/validation.mdx#string-constraints) | `minLength: n` | String | -| [`maxLength(n)`](../core-concepts/validation.mdx#string-constraints) | `maxLength: n` | String | -| [`matches(p)`](../core-concepts/validation.mdx#string-constraints) | `pattern: p` | String | -| [`email()`](../core-concepts/validation.mdx#string-constraints) | `format: email` | String | -| [`date()`](../core-concepts/validation.mdx#string-constraints) | `format: date` | String | -| [`datetime()`](../core-concepts/validation.mdx#string-constraints) | `format: date-time` | String | -| [`time()`](../core-concepts/validation.mdx#string-constraints) | `pattern: ^(?:[01][0-9]\|2[0-3]):[0-5][0-9]:[0-5][0-9]$` | String | -| [`uri()`](../core-concepts/validation.mdx#string-constraints) | `format: uri` | String | -| [`uuid()`](../core-concepts/validation.mdx#string-constraints) | `format: uuid` | String | -| [`ipv4()`](../core-concepts/validation.mdx#string-constraints) | `format: ipv4` | String | -| [`ipv6()`](../core-concepts/validation.mdx#string-constraints) | `format: ipv6` | String | -| [`Ack.enumString([...])`](../core-concepts/validation.mdx#string-constraints) | `enum: [...]` | String | -| [`min(n)`](../core-concepts/validation.mdx#number-constraints) | `minimum: n` | Number | -| [`max(n)`](../core-concepts/validation.mdx#number-constraints) | `maximum: n` | Number | -| [`greaterThan(n)`](../core-concepts/validation.mdx#number-constraints) | `exclusiveMinimum: n` | Number (exclusive) | -| [`lessThan(n)`](../core-concepts/validation.mdx#number-constraints) | `exclusiveMaximum: n` | Number (exclusive) | -| [`multipleOf(n)`](../core-concepts/validation.mdx#number-constraints) | `multipleOf: n` | Number | +| `minLength(n)` | `minLength: n` | String | +| `maxLength(n)` | `maxLength: n` | String | +| `length(n)` | `minLength: n`, `maxLength: n` | String | +| `matches(p)` | `pattern: p` | String | +| `contains(s)`, `startsWith(s)`, `endsWith(s)` | Escaped `pattern` | String | +| `email()` | `format: email` | String | +| `date()` | `format: date` | String | +| `datetime()` | `format: date-time` | String | +| `time()` | `pattern: ^(?:[01][0-9]\|2[0-3]):[0-5][0-9]:[0-5][0-9]$` | String | +| `uri()` | `format: uri` | String | +| `uuid()` | `format: uuid` | String | +| `ipv4()` | `format: ipv4` | String | +| `ipv6()` | `format: ipv6` | String | +| `ip()` | `anyOf` of `format: ipv4` and `format: ipv6` | String | +| `Ack.enumString([...])` | `enum: [...]` | String | +| `min(n)` | `minimum: n` | Number | +| `max(n)` | `maximum: n` | Number | +| `greaterThan(n)` | `exclusiveMinimum: n` | Number (exclusive) | +| `lessThan(n)` | `exclusiveMaximum: n` | Number (exclusive) | +| `multipleOf(n)` | `multipleOf: n` | Number | | [`minItems(n)`](../core-concepts/validation.mdx#list-constraints) | `minItems: n` | List (array) | | [`maxItems(n)`](../core-concepts/validation.mdx#list-constraints) | `maxItems: n` | List (array) | +| [`length(n)`](../core-concepts/validation.mdx#list-constraints) | `minItems: n`, `maxItems: n` | List (array) | | [`unique()`](../core-concepts/validation.mdx#list-constraints) | `uniqueItems: true` | List (array) | | [`nullable()`](../core-concepts/schemas.mdx#optional-vs-nullable) | `anyOf: [, {type: null}]` | Any schema | -| `withDefault(v)` | `default: v` | JSON/export-safe defaults only in `AckSchemaModel`; unsupported defaults are omitted with a warning | +| [`withDefault(v)`](../core-concepts/schemas.mdx#defaults) | `default: v` | JSON/export-safe defaults only in `AckSchemaModel`; unsupported defaults are omitted with a warning | | `describe(d)` | `description: d` | Any schema | | [`Ack.integer()`](../core-concepts/schemas.mdx#number) | `type: integer` | Type | | [`Ack.double()`](../core-concepts/schemas.mdx#number) | `type: number` | Type | @@ -510,55 +477,38 @@ Ack maps its [built-in constraints](../core-concepts/validation.mdx) to correspo | [`Ack.object(...)`](../core-concepts/schemas.mdx#object) | `type: object`, `properties: {...}`, `required: [...]` | Type | | [`Ack.lazy(...)`](../core-concepts/schemas.mdx#recursive-schemas) | `definitions`, `$ref` | Recursive type | +The constraint names link to [Validation Rules](../core-concepts/validation.mdx), which defines each one. + ## Shape stability notes `toJsonSchema()` renders generic Draft-7 JSON Schema with stable nullability rules: -- Primitive/object/list/enum schemas marked with `.nullable()` are emitted as: - - `anyOf: [, { "type": "null" }]` -- `Ack.anyOf([...]).nullable()` is emitted as - `anyOf: [{ "anyOf": [...] }, { "type": "null" }]` -- `Ack.discriminated(...)` is emitted as `anyOf` with effective object - branches. Each branch contains the exact required discriminator `const`. -- `Ack.discriminated(...).nullable()` wraps that `anyOf` union with a second - `{ "type": "null" }` branch. -- `Ack.lazy(name, ...)` is emitted as a Draft-7 `definitions` entry and local - `$ref` values such as `{ "$ref": "#/definitions/Category" }`. -- Non-null lazy refs that carry metadata such as `description` use `allOf` - around the `$ref` so Draft-7 validators do not ignore that metadata as a - `$ref` sibling. Nullable lazy refs keep metadata beside the top-level `anyOf`. - -This means nullable enums are represented as: - -```json -{ - "anyOf": [ - { "type": "string", "enum": ["admin", "user", "guest"] }, - { "type": "null" } - ] -} -``` - -And nullable discriminated unions are represented as: - -```json -{ - "anyOf": [ - { "anyOf": [/* effective discriminated object branches */] }, - { "type": "null" } - ] -} -``` - -If you build consumers that inspect generated schemas, treat nullability and union composition as separate concerns and don't assume enum values always live at the top level. - -The nested nullable-union shape is intentional for generic Draft-7 output and matches Zod v4's `toJSONSchema()` renderer. Don't flatten it in `AckSchema.toJsonSchema()`; provider-specific adapters that need a different shape should implement explicit adapter rendering. +| Ack schema | Exported shape | +| --- | --- | +| Primitive, object, list or enum with `.nullable()` | `anyOf: [, { "type": "null" }]` | +| `Ack.anyOf([...]).nullable()` | `anyOf: [{ "anyOf": [...] }, { "type": "null" }]` | +| `Ack.discriminated(...)` | `anyOf` with effective object branches. Each branch contains the exact required discriminator `const`. | +| `Ack.discriminated(...).nullable()` | The `anyOf` union wrapped with a second `{ "type": "null" }` branch | +| `Ack.lazy(name, ...)` | A Draft-7 `definitions` entry and local `$ref` values such as `{ "$ref": "#/definitions/Category" }` | +| Non-null lazy ref with metadata such as `description` | `allOf` around the `$ref`, so Draft-7 validators do not ignore the metadata as a `$ref` sibling | +| Nullable lazy ref with metadata | Metadata beside the top-level `anyOf` | + +Treat nullability and union composition as separate concerns when you inspect +exported schemas. For example, a nullable enum keeps its values inside the +first `anyOf` branch, not at the top level. Don't flatten the nested +nullable-union shape in `AckSchema.toJsonSchema()`. Provider-specific adapters +that need a different shape implement their own rendering. **Limitations:** -- **Custom Constraints:** [`Constraint` + `Validator`](./custom-validation.mdx) - instances added via `.constrain()` are **not** translated to JSON Schema - because there is no standard way to represent arbitrary logic. +- **Custom Constraints:** a [`Constraint` + `Validator`](./custom-validation.mdx) + added with `.constrain()` exports nothing unless it also mixes in + `JsonSchemaSpec`. With the mixin, its `toJsonSchema()` keywords export when + the constraint applies to the wire value. A constraint added after a + normalizer such as `.trim()`, or on a codec's runtime side (after + `.codec(...)`), checks a converted value, so Ack leaves it out of the + export. A built-in codec can map some runtime rules to the wire: + `Ack.duration()` exports its bounds in milliseconds. - **`additionalProperties`:** `Ack.object(..., additionalProperties: false)` becomes `additionalProperties: false`; `additionalProperties: true` is emitted as the boolean `true`. @@ -573,7 +523,7 @@ The nested nullable-union shape is intentional for generic Draft-7 output and ma to the lazy reference are runtime-only and are reported as schema-model warnings rather than emitted beside `$ref`. - **Date/time range constraints:** Draft-7 has no standard `formatMinimum` or - `formatMaximum` keywords. ACK validates `.min()` and `.max()` at runtime and + `formatMaximum` keywords. Ack validates `.min()` and `.max()` at runtime and records schema-model warnings instead of rendering non-standard keywords. - **List item nullability:** `Ack.list(item)` requires a schema that rejects null items. An imported schema without an explicit non-null type may admit @@ -585,68 +535,41 @@ The nested nullable-union shape is intentional for generic Draft-7 output and ma `Ack.enumString(...)` fields are accepted; generated branches expose the exact branch value as `const`. -## Integrating into API documentation +## Exporting to API documentation -Use the generated JSON Schema map within a larger API documentation structure. +Embed the exported map in a larger API document: ```dart compile=api-specification -// Assume you have a function to build the full API spec -Map buildApiSpecification() { - final userJsonSchema = userSchema.toJsonSchema(); - - return { - 'schemas': { - 'User': userJsonSchema - }, - 'endpoints': { - '/users': { - 'post': { - 'summary': 'Create a new user', - 'requestBody': { - 'required': true, - 'content': { - 'application/json': { - // Reference the generated schema - 'schema': { - '\$ref': '#/schemas/User' - } - } - } - } - } - } - } - }; -} - -// Usage -final fullApiSpec = buildApiSpecification(); -print(JsonEncoder.withIndent(' ').convert(fullApiSpec)); +final apiSpec = { + 'schemas': {'User': userSchema.toJsonSchema()}, +}; +print(JsonEncoder.withIndent(' ').convert(apiSpec)); ``` -This keeps your validation logic and API documentation in one place. - -## Advanced JSON Schema features - -### Schema descriptions and metadata +## Exporting unions -Add descriptions and metadata to your schemas for better documentation: +`Ack.discriminated(...)` exports as an `anyOf` of its object branches: -```dart compile=library -final userSchema = Ack.object({ - 'id': Ack.string().uuid().describe('Unique user identifier'), - 'name': Ack.string().minLength(1).describe('User\'s full name'), - 'email': Ack.string().email().describe('User\'s email address'), - 'age': Ack.integer().min(0).max(150).describe('User\'s age in years').optional(), -}).describe('Represents a user in the system'); +```dart compile=complex-schema +final shapeSchema = Ack.discriminated( + discriminatorKey: 'type', + schemas: { + 'circle': Ack.object({ + 'radius': Ack.double().positive(), + }), + 'rectangle': Ack.object({ + 'width': Ack.double().positive(), + 'height': Ack.double().positive(), + }), + }, +); -final jsonSchema = userSchema.toJsonSchema(); -// Output includes description fields +final shapeJson = shapeSchema.toJsonSchema(); ``` -### Default values in JSON Schema +## Default values in JSON Schema -Schemas with default values include them in the generated JSON Schema: +A schema with a [default](../core-concepts/schemas.mdx#defaults) exports it as `default`: ```dart compile=library enum Theme { light, dark } @@ -654,50 +577,35 @@ enum Theme { light, dark } final configSchema = Ack.object({ 'theme': Ack.enumValues(Theme.values).withDefault(Theme.light), 'notifications': Ack.boolean().withDefault(true), - 'maxItems': Ack.integer().min(1).max(100).withDefault(10), }); final jsonSchema = configSchema.toJsonSchema(); // Output includes "default" properties ``` -### Complex schema patterns - -JSON Schema generation works with all Ack schema types: +## Adapter model -```dart compile=complex-schema -// Union types -final mixedValueSchema = Ack.anyOf([ - Ack.string(), - Ack.integer(), - Ack.boolean(), -]); - -// Discriminated unions -final shapeSchema = Ack.discriminated( - discriminatorKey: 'type', - schemas: { - 'circle': Ack.object({ - 'radius': Ack.double().positive(), - }), - 'rectangle': Ack.object({ - 'width': Ack.double().positive(), - 'height': Ack.double().positive(), - }), - }, -); +Use `toSchemaModel()` for a reusable, target-independent view of an Ack schema. +`AckSchemaModel` describes the boundary values a schema accepts and exports. +Native models render as Draft-7-compatible JSON Schema, imported models +preserve supported Draft 2020-12 resources, and adapter renderers add +provider-specific hints. -// Nested arrays and objects -final complexSchema = Ack.object({ - 'users': Ack.list(userSchema).minItems(1), - 'metadata': Ack.object({ - 'version': Ack.string(), - 'tags': Ack.list(Ack.string()).unique(), - }).optional(), -}); +```dart compile=exported-model +final model = userSchema.toSchemaModel(); +final jsonSchemaMap = model.toJsonSchema(); -// All produce valid JSON Schema -final mixedJson = mixedValueSchema.toJsonSchema(); -final shapeJson = shapeSchema.toJsonSchema(); -final complexJson = complexSchema.toJsonSchema(); +for (final warning in model.allWarnings) { + print('${warning.path} ${warning.code}: ${warning.message}'); +} ``` + +`model.warnings` holds the node's own warnings. `model.allWarnings` yields the +node's warnings first, then its definition warnings, then its descendants' +warnings. It fills null paths with fragment JSON Pointers like `#` and +`#/anyOf/0/properties/a~1b`, using RFC 6901 token escaping without +percent-encoding. It rebases any supplied `#`-prefixed path to the warning's +node and passes other paths through unchanged. + +To build an adapter package, see +[Creating adapter packages](./creating-schema-converter-packages.mdx). diff --git a/docs/guides/schema-converter-quickstart.mdx b/docs/guides/schema-converter-quickstart.mdx index d7ca53a6..16181853 100644 --- a/docs/guides/schema-converter-quickstart.mdx +++ b/docs/guides/schema-converter-quickstart.mdx @@ -2,15 +2,7 @@ title: Adapter Package Quickstart --- -Use an [existing adapter](./ecosystem-integrations.mdx) when it supports your -target. To write a new one, start with -[Creating Adapter Packages](./creating-schema-converter-packages.mdx), which owns -the implementation guidance and a contract-test example. +This page moved. The quick start is now at the top of +[Creating Adapter Packages](./creating-schema-converter-packages.mdx). -- A JSON Schema target can use `schema.toJsonSchema()` directly. -- A non-JSON target translates `schema.toSchemaModel()` and explicitly handles - unsupported semantics, nested resources, and references. -- Test required keys, nullability, constraints, and codec wire shapes against the - target's representation. - -The full guide also covers workspace membership and coordinated publishing. +To use an existing adapter, see [Ecosystem Integrations](./ecosystem-integrations.mdx). diff --git a/docs/index.mdx b/docs/index.mdx index d5845ce0..499c00a3 100644 --- a/docs/index.mdx +++ b/docs/index.mdx @@ -4,7 +4,7 @@ title: Overview External data can't be trusted. APIs change, users mistype, and JSON drifts from what your code expects. Ack is a schema validation library for Dart and Flutter that puts a guardrail at those boundaries: describe the shape you expect once, then check untrusted data against it. You get a clear error when it doesn't match — and your data, validated, when it does. -("Ack" is short for "acknowledgment.") +("Ack" is short for "acknowledge.") ```dart compile=body import 'package:ack/ack.dart'; @@ -39,31 +39,17 @@ On success, `getOrThrow()` returns your **validated data** as a `Map schema = Ack.fromJsonSchema({ - 'type': 'object', - 'properties': {'name': {'type': 'string'}}, - 'required': ['name'], -}); -final value = schema.parse({'name': 'Ada'}); -final jsonSchema = schema.toJsonSchema(); -``` - -The source document is a decoded map or boolean, not a JSON string. -`Ack.fromJsonSchema()` returns an executable validator and rejects unsupported -semantics with `JsonSchemaImportException`; its immutable diagnostics identify -the source keyword and location. Supply reference bundles with `documents` and -`baseUri`; no references are fetched automatically. See -[`example/json_schema_import.dart`](example/json_schema_import.dart). - -Exports preserve supported validation behavior, not textual document identity. -Full A2UI coverage is not supported. MCP registration compatibility remains -separate. See the -[JSON Schema guide](https://concepta.dev/documentation/ack/guides/json-schema-integration) -for the supported subset, recursive bundles, and round-trip guarantees. - -## Documentation +## Learn more +- [Quickstart](https://concepta.dev/documentation/ack/getting-started/quickstart-tutorial) +- [Model code generation](https://concepta.dev/documentation/ack/core-concepts/typesafe-schemas) +- [JSON Schema import and export](https://concepta.dev/documentation/ack/guides/json-schema-integration) +- [Migration guide](https://concepta.dev/documentation/ack/getting-started/migration-guide) - [Full documentation](https://concepta.dev/ack) - [AI agent index (llms.txt)](https://concepta.dev/documentation/ack/reference/llms-txt) ## Related Packages - [ack_generator](https://pub.dev/packages/ack_generator) — Generates models from `@Schemable()` schemas and schemas from `@Schemable()` classes -- [ack_firebase_ai](https://pub.dev/packages/ack_firebase_ai) — Firebase AI (Gemini) schema converter +- [ack_firebase_ai](https://pub.dev/packages/ack_firebase_ai) — Firebase AI (Gemini) adapter - [ack_json_schema_builder](https://pub.dev/packages/ack_json_schema_builder) — bidirectional JSON Schema bridge - [ack_mcp_dart](https://pub.dev/packages/ack_mcp_dart) — MCP tool schemas and typed argument validation diff --git a/packages/ack/lib/src/ack.dart b/packages/ack/lib/src/ack.dart index 34ccd0c6..f8853c87 100644 --- a/packages/ack/lib/src/ack.dart +++ b/packages/ack/lib/src/ack.dart @@ -77,7 +77,19 @@ final class Ack { bool additionalProperties = false, }) => ObjectSchema(properties, additionalProperties: additionalProperties); - /// Creates a discriminated object schema for polymorphic validation. + /// Creates a union of object [schemas] selected by the value at + /// [discriminatorKey]. + /// + /// The union owns the discriminator key: branch schemas omit it, and the + /// union adds the literal for each branch label. A branch may declare the + /// key only if it accepts its own label. + /// + /// ```dart + /// Ack.discriminated( + /// discriminatorKey: 'type', + /// schemas: {'circle': circleSchema, 'square': squareSchema}, + /// ); + /// ``` static DiscriminatedObjectSchema discriminated({ required String discriminatorKey, required Map> schemas, diff --git a/packages/ack/lib/src/constraints/constraint.dart b/packages/ack/lib/src/constraints/constraint.dart index 681bc370..4acffbd9 100644 --- a/packages/ack/lib/src/constraints/constraint.dart +++ b/packages/ack/lib/src/constraints/constraint.dart @@ -2,11 +2,19 @@ import 'package:meta/meta.dart'; /// Base class for all validation constraints. /// -/// A [Constraint] defines a specific rule that a value must adhere to. -/// It holds a unique `constraintKey` for identification and a `description`. +/// A [Constraint] is one rule that a value must satisfy, such as a minimum +/// length. Mix in [Validator] to check values and [JsonSchemaSpec] to export +/// the rule to JSON Schema. @immutable abstract class Constraint { + /// A stable snake_case identifier for the rule, such as + /// `string_min_length`. + /// + /// Use it to recognize a failure in code, because [description] and error + /// messages can change. final String constraintKey; + + /// A short human-readable statement of the rule. final String description; const Constraint({required this.constraintKey, required this.description}); @@ -40,8 +48,13 @@ abstract class Constraint { /// and optional [context] providing more details about the failure. @immutable final class ConstraintError { + /// The constraint that the value violated. final Constraint constraint; + + /// The error message for this violation. final String message; + + /// Extra details about the violation, such as the input value, or `null`. final Map? context; const ConstraintError({ @@ -50,10 +63,10 @@ final class ConstraintError { this.context, }); - /// The unique key of the constraint that failed. + /// The [Constraint.constraintKey] of the constraint that failed. String get constraintKey => constraint.constraintKey; - /// Serializes this error to a map. + /// Serializes this error to a map for logs; [context] can hold input data. Map toMap() { return { 'message': message, @@ -70,8 +83,13 @@ final class ConstraintError { /// Mixin for constraints that can be converted to a JSON Schema representation. /// -/// This mixin defines the contract for converting constraint validation rules -/// into a format compliant with JSON Schema (typically Draft-07 or later). +/// Mix it into a [Constraint] so that `toJsonSchema()` on the schema can +/// export the rule. The keywords export when the constraint applies to the +/// wire value. A constraint added after a normalizer such as `trim()`, or on +/// a codec's runtime side, checks a converted value and is left out of the +/// export, unless the codec maps it to the wire, as `Ack.duration()` does with +/// millisecond bounds. A constraint without this mixin is enforced at runtime +/// only. mixin JsonSchemaSpec on Constraint { /// Converts this constraint to its JSON Schema representation. /// @@ -80,10 +98,11 @@ mixin JsonSchemaSpec on Constraint { Map toJsonSchema(); } -/// Mixin defining the core validation logic for a [Constraint]. +/// Adds validation logic to a [Constraint]. /// -/// It provides a structure for checking if a `value` is valid, building -/// an appropriate error `message`, and constructing a `context` map for failures. +/// Implement [isValid] and [buildMessage]; [validate] then returns a +/// [ConstraintError] for invalid values. Pass a [Validator] constraint to +/// `constrain` to apply it to a schema. mixin Validator on Constraint { /// Checks if the given [value] is valid according to this constraint. @protected diff --git a/packages/ack/lib/src/json_schema/json_schema_compiler.dart b/packages/ack/lib/src/json_schema/json_schema_compiler.dart index 11602bb8..1aa733aa 100644 --- a/packages/ack/lib/src/json_schema/json_schema_compiler.dart +++ b/packages/ack/lib/src/json_schema/json_schema_compiler.dart @@ -842,9 +842,9 @@ final class _JsonSchemaCompiler { JsonSchemaImportDiagnostic _diagnostic( _ImportedNode node, String key, - String message, - String code, - ) => JsonSchemaImportDiagnostic._( + String message, { + required String code, + }) => JsonSchemaImportDiagnostic._( code: code, documentUri: node.documentUri, pointer: _keywordPointer(node, key), @@ -858,7 +858,7 @@ final class _JsonSchemaCompiler { String message, { String code = 'unsupported_keyword', }) { - diagnostics.add(_diagnostic(node, key, message, code)); + diagnostics.add(_diagnostic(node, key, message, code: code)); } Never _fail( @@ -868,7 +868,7 @@ final class _JsonSchemaCompiler { String code = 'invalid_schema', }) => throw JsonSchemaImportException._([ ...diagnostics, - _diagnostic(node, key, message, code), + _diagnostic(node, key, message, code: code), ]); } diff --git a/packages/ack/lib/src/schemas/extensions/object_schema_extensions.dart b/packages/ack/lib/src/schemas/extensions/object_schema_extensions.dart index 54d0a345..6c3be2b9 100644 --- a/packages/ack/lib/src/schemas/extensions/object_schema_extensions.dart +++ b/packages/ack/lib/src/schemas/extensions/object_schema_extensions.dart @@ -13,6 +13,10 @@ extension ObjectSchemaExtensions on ObjectSchema { /// Allows the object schema to have properties that are not /// explicitly defined in the `properties` map. + /// + /// ```dart + /// final schema = Ack.object({'id': Ack.string()}).passthrough(); + /// ``` ObjectSchema passthrough() { return copyWith(additionalProperties: true); } @@ -27,6 +31,10 @@ extension ObjectSchemaExtensions on ObjectSchema { } /// Makes all properties on the schema optional. + /// + /// ```dart + /// final patch = userSchema.partial(); + /// ``` ObjectSchema partial() { _checkUnrefined(); final optionalProperties = properties.map( @@ -54,7 +62,11 @@ extension ObjectSchemaExtensions on ObjectSchema { ); } - /// Creates a new schema with a subset of the original's properties. + /// Creates a new schema that keeps only the properties named in [keysToPick]. + /// + /// ```dart + /// final credentials = userSchema.pick(['email', 'password']); + /// ``` ObjectSchema pick(List keysToPick) { _checkUnrefined(); final pickSet = keysToPick.toSet(); @@ -65,7 +77,11 @@ extension ObjectSchemaExtensions on ObjectSchema { return copyWith(properties: newProperties); } - /// Creates a new schema with a subset of the original's properties removed. + /// Creates a new schema without the properties named in [keysToOmit]. + /// + /// ```dart + /// final publicUser = userSchema.omit(['password']); + /// ``` ObjectSchema omit(List keysToOmit) { _checkUnrefined(); final omitSet = keysToOmit.toSet(); diff --git a/packages/ack/lib/src/schemas/schema.dart b/packages/ack/lib/src/schemas/schema.dart index f12eb825..af8b18e8 100644 --- a/packages/ack/lib/src/schemas/schema.dart +++ b/packages/ack/lib/src/schemas/schema.dart @@ -340,13 +340,19 @@ sealed class AckSchema { List>? refinements, }); - /// Marks the schema as nullable. + /// Returns a copy that accepts `null` as a valid value. + /// + /// The key must still be present in an object. Use [optional] to allow the + /// key to be absent. AckSchema nullable({bool value = true}); - /// Marks the schema as optional so the field can be omitted from an object. + /// Returns a copy whose field may be absent from an object. + /// + /// Unlike [nullable], which accepts an explicit `null`, `optional` allows the + /// key to be missing. AckSchema optional({bool value = true}); - /// Sets the description for the schema. + /// Returns a copy with [description], which is exported to JSON Schema. AckSchema describe(String description); /// Wraps this schema in a [DefaultSchema] that supplies [defaultValue] when @@ -409,7 +415,10 @@ sealed class AckSchema { return result.getOrThrow(); } - /// Parses and validates a value, then maps the validated value to [TOut]. + /// Validates [value] and returns it mapped to [TOut], throwing an + /// [AckException] if validation fails. + /// + /// Use [safeParseAs] to get a [SchemaResult] instead of an exception. TOut parseAs( Object? value, TOut Function(Runtime? validated) map, { @@ -433,7 +442,12 @@ sealed class AckSchema { } } - /// Parses and validates a value, then maps the validated value to [TOut]. + /// Validates [value] and returns the mapped [TOut] in a [SchemaResult], + /// without throwing for invalid input. + /// + /// A [map] callback that throws an [Exception] becomes a + /// [SchemaTransformError]; an [Error] propagates. Use [parseAs] to throw an + /// [AckException] for invalid input instead. SchemaResult safeParseAs( Object? value, TOut? Function(Runtime? validated) map, { diff --git a/packages/ack/lib/src/validation/ack_exception.dart b/packages/ack/lib/src/validation/ack_exception.dart index c869c522..928ba6da 100644 --- a/packages/ack/lib/src/validation/ack_exception.dart +++ b/packages/ack/lib/src/validation/ack_exception.dart @@ -3,17 +3,22 @@ import 'package:meta/meta.dart'; import '../helpers.dart'; import 'schema_error.dart'; -/// An exception thrown when schema validation fails using `parse()`. +/// The exception thrown when `parse()` or `parseAs()` rejects a value. /// -/// It wraps a [SchemaError] instance, providing detailed information -/// about the validation failure. +/// It wraps the [SchemaError]s that describe the failure. Use `safeParse()` +/// to get a result instead of an exception. +/// +/// [toString] adds no input values of its own, although custom messages can +/// contain input. [toMap] and [toJson] include the values, for logs. @immutable final class AckException implements Exception { + /// The validation failures, at least one. final List errors; + /// Creates an exception for the given [errors]. const AckException(this.errors); - /// Converts this exception (specifically its underlying error) to a map. + /// Converts the [errors] to a map for logs, including input values. Map toMap() { return {'validationError': errors.map((e) => e.toMap()).toList()}; } @@ -24,6 +29,11 @@ final class AckException implements Exception { /// cannot be encoded as JSON are represented as strings. String toJson() => prettyJson(toMap()); + /// Returns the failure lines: the single error's line, or a list with one + /// line per error. + /// + /// Ack adds no input values of its own, but a path or a custom message can + /// contain input. @override String toString() { if (errors.length == 1) { diff --git a/packages/ack/lib/src/validation/schema_error.dart b/packages/ack/lib/src/validation/schema_error.dart index e7cd085a..17045ea3 100644 --- a/packages/ack/lib/src/validation/schema_error.dart +++ b/packages/ack/lib/src/validation/schema_error.dart @@ -4,11 +4,32 @@ import '../constraints/constraint.dart'; import '../context.dart'; import '../schemas/schema.dart'; +/// A validation or encoding failure reported at one location in a value. +/// +/// A failed [SchemaResult] carries one [SchemaError]; [AckException] carries a +/// list of them. Match on the subclass to react to a specific kind of failure. +/// +/// [toString] prints one `path: message` line per failure and starts +/// root-level lines with `#: `. Ack never adds the input value or the text of +/// an exception thrown by a callback. Messages you write, such as a custom +/// `buildMessage` or `message:`, and paths built from input keys can still +/// contain input, so review them before you show errors to users. Use [toMap] +/// when you need the value and the [cause], for example in diagnostic logs +/// that you control. @immutable sealed class SchemaError { + /// A human-readable description of the failure. final String message; + + /// The place in the input where the failure happened, including the schema, + /// the value and the path to it. final SchemaContext context; + + /// The exception that triggered this failure, such as one thrown by a + /// `transform`, codec or encoder callback, or `null` when there is none. final Object? cause; + + /// The stack trace of [cause], or `null` when there is none. final StackTrace? stackTrace; const SchemaError( @@ -18,17 +39,29 @@ sealed class SchemaError { this.stackTrace, }); + /// The name of the failing field or element, or the debug name at the root. String get name => context.name; + + /// The schema that rejected the value. AnyAckSchema get schema => context.schema; + + /// The input value that failed. + /// + /// It is omitted from [toString] because it can hold sensitive data. Object? get value => context.value; + + /// The location of the failure, such as `#/user/email`. String get path => context.path; - /// Returns a human-readable error string with path information. + /// Returns the [message] followed by the failing [path]. String toErrorString() { return '$message at path: $path'; } - /// Serializes the error for diagnostics, including the input and cause. + /// Serializes the error for logs, including the input [value] and the + /// [cause]. + /// + /// Do not send the result to users, because it can expose input data. Map toMap() { return { 'message': message, @@ -40,6 +73,11 @@ sealed class SchemaError { }; } + /// Returns a single `path: message` line. + /// + /// Ack adds no input value of its own; a custom [message] can still contain + /// input. The line ends with `(callback threw)` when [cause] is set; the + /// exception text stays out of the output. @override String toString() { final detail = cause == null ? '' : ' (callback threw)'; @@ -125,6 +163,8 @@ SchemaError rebaseSchemaError( return rebase(error); } +/// The value has the wrong JSON type, such as a number where a string is +/// expected. @immutable final class TypeMismatchError extends SchemaError { final SchemaType _expectedJsonType; @@ -141,7 +181,10 @@ final class TypeMismatchError extends SchemaError { context: context, ); + /// The name of the type the schema expects. String get expectedType => _expectedJsonType.typeName; + + /// The name of the type the input had. String get actualType => _actualJsonType.typeName; @override @@ -159,7 +202,11 @@ final class TypeMismatchError extends SchemaError { } } +/// The value has the right type but breaks one or more constraints, such as +/// `minLength`, `min`, an enum's allowed values, or a discriminated union's +/// known labels. final class SchemaConstraintsError extends SchemaError { + /// The violated constraints, one entry per failed rule. final List constraints; SchemaConstraintsError({required this.constraints, required super.context}) @@ -167,6 +214,8 @@ final class SchemaConstraintsError extends SchemaError { 'Constraints not met: ${constraints.map((c) => c.message).join(', ')}', ); + /// Returns the first violation whose constraint is a [S], or `null` when + /// none matches. ConstraintError? getConstraint() { for (final constraintError in constraints) { if (constraintError.constraint is S) { @@ -186,8 +235,13 @@ final class SchemaConstraintsError extends SchemaError { } } +/// A container schema, such as an object or list, groups the failures of its +/// properties or items. +/// +/// [toString] prints the leaf failures only, one line each. @immutable final class SchemaNestedError extends SchemaError { + /// The failures found inside the container. final List errors; const SchemaNestedError({required this.errors, required super.context}) @@ -216,6 +270,10 @@ final class SchemaNestedError extends SchemaError { } } +/// A value fails a rule that is not a type or constraint check. +/// +/// Examples are a failed `refine` and a schema imported with +/// `Ack.fromJsonSchema` rejecting a keyword. @immutable base class SchemaValidationError extends SchemaError { SchemaValidationError({ @@ -226,6 +284,12 @@ base class SchemaValidationError extends SchemaError { }) : super(message); } +/// A `transform`, codec decoder or `parseAs` mapper threw an [Exception] +/// while converting an already validated value. +/// +/// The exception is available as [cause]. A Dart [Error] thrown by the +/// callback is a programming failure and propagates instead. An exception from +/// a codec's encoder becomes a [SchemaEncodeError]. final class SchemaTransformError extends SchemaError { const SchemaTransformError({ required String message, @@ -237,18 +301,33 @@ final class SchemaTransformError extends SchemaError { /// Categorizes encode-side failures so callers can react programmatically. enum SchemaEncodeFailureKind { + /// `null` was encoded with a schema that does not accept `null`. nonNullable, + + /// The runtime value does not have the type the schema encodes. typeMismatch, + + /// The schema has a `transform` without an inverse, so it cannot encode. oneWayTransform, + + /// A codec or encoder callback threw. encoderThrew, + + /// An encoded object lacks a required property. missingRequiredProperty, + + /// An encoded object has a property the schema does not allow. unexpectedProperty, } /// Errors raised during the encode path (Runtime → Boundary). @immutable final class SchemaEncodeError extends SchemaError { + /// The category of the encode failure. final SchemaEncodeFailureKind kind; + + /// The property involved, set for [SchemaEncodeFailureKind.missingRequiredProperty] + /// and [SchemaEncodeFailureKind.unexpectedProperty]; otherwise `null`. final String? propertyKey; const SchemaEncodeError._({ diff --git a/packages/ack/lib/src/validation/schema_result.dart b/packages/ack/lib/src/validation/schema_result.dart index 35756ef9..55dcfebf 100644 --- a/packages/ack/lib/src/validation/schema_result.dart +++ b/packages/ack/lib/src/validation/schema_result.dart @@ -21,10 +21,10 @@ sealed class SchemaResult { return Fail(error); } - /// Indicates whether this result is successful. + /// Whether this result is a success. bool get isOk => this is Ok; - /// Indicates whether this result represents a failure. + /// Whether this result is a failure. bool get isFail => this is Fail; /// Returns the [SchemaError] if this result is a failure. diff --git a/packages/ack/test/documentation/documentation_source_integrity_test.dart b/packages/ack/test/documentation/documentation_source_integrity_test.dart index d911e549..e01ddab4 100644 --- a/packages/ack/test/documentation/documentation_source_integrity_test.dart +++ b/packages/ack/test/documentation/documentation_source_integrity_test.dart @@ -10,19 +10,20 @@ void main() { test( 'full-value regex examples are anchored in their literal snippets', () { - final commonRecipes = _readFromRepo('docs/guides/common-recipes.mdx'); final flutterForms = _readFromRepo( 'docs/guides/flutter-form-validation.mdx', ); final validation = _readFromRepo('docs/core-concepts/validation.mdx'); final schemas = _readFromRepo('docs/core-concepts/schemas.mdx'); - expect(commonRecipes, contains(".matches(r'^\\d{5}(-\\d{4})?\$')")); expect(flutterForms, contains(".matches(r'^[a-zA-Z0-9_]+\$')")); expect(validation, contains(".matches(r'^[a-z0-9_]+\$')")); expect(schemas, contains(".matches(r'^[a-zA-Z0-9_]+\$')")); expect(schemas, contains(".matches(r'^\\d{5}\$')")); - expect(schemas, contains(".matches(r'^\\d{4}-\\d{2}-\\d{2}\$')")); + expect( + _readFromRepo('docs/guides/custom-validation.mdx'), + contains(".matches(r'^\\d{4}-\\d{2}-\\d{2}\$')"), + ); }, ); @@ -94,15 +95,20 @@ void main() { final serializedConfig = jsonEncode(docsConfig); expect( - File('../../docs/guides/schema-converter-quickstart.mdx').existsSync(), - isTrue, + _readFromRepo('docs/guides/schema-converter-quickstart.mdx'), + contains('](./creating-schema-converter-packages.mdx)'), + reason: 'the quickstart page points to the full guide', ); expect( File('../../docs/guides/creating-schema-converter-packages.mdx') .existsSync(), isTrue, ); - expect(serializedConfig, contains('/guides/schema-converter-quickstart')); + expect( + serializedConfig, + isNot(contains('/guides/schema-converter-quickstart')), + reason: 'the quickstart page points to the full guide', + ); expect( serializedConfig, contains('/guides/creating-schema-converter-packages'), @@ -127,15 +133,20 @@ void main() { expect(quickstart, contains('[Error Handling]')); }); - test('configuration documents the main schema-level choices', () { + test('configuration links each schema-level choice to its home', () { final configuration = _readFromRepo( 'docs/core-concepts/configuration.mdx', ); - expect(configuration, contains('### Optional and nullable values')); - expect(configuration, contains('### Default values')); - expect(configuration, contains('### Schema metadata')); - expect(configuration, contains('message:')); + expect(configuration, contains('no global configuration object')); + expect(configuration, contains('./schemas.mdx#optional-vs-nullable')); + expect(configuration, contains('./schemas.mdx#defaults')); + expect( + configuration, + contains('custom-validation.mdx#overriding-error-messages'), + ); + expect(configuration, contains('.describe()')); + expect(configuration, contains('json-schema-integration.mdx')); }); test('API page distinguishes quick reference from exhaustive API docs', () { diff --git a/packages/ack/test/naming_conventions_test.dart b/packages/ack/test/naming_conventions_test.dart new file mode 100644 index 00000000..3e755e6e --- /dev/null +++ b/packages/ack/test/naming_conventions_test.dart @@ -0,0 +1,265 @@ +@TestOn('vm') +library; + +import 'dart:io'; + +import 'package:ack/ack.dart'; +import 'package:test/test.dart'; + +/// Pins the naming rule in ARCHITECTURE.md: identifier values are +/// snake_case; field names in serialized maps are camelCase. +void main() { + final sources = { + for (final file in Directory('lib').listSync(recursive: true)) + if (file is File && file.path.endsWith('.dart')) + file.path: _withoutComments(file.readAsStringSync()), + }; + + test('built-in constraint keys are snake_case', () { + final keys = _identifierValues( + sources, + name: 'constraintKey', + // Forwards another constraint's key, which this test checks at its source. + forwards: {'inner.constraintKey'}, + ); + + expect(keys.length, greaterThan(35), reason: 'the scan found too few keys'); + for (final MapEntry(key: key, value: path) in keys.entries) { + expect(_isSnakeCase(key), isTrue, reason: '$key in $path'); + if (key.contains(r'$')) { + expect( + _interpolatedKeys, + contains(key), + reason: 'unexpected interpolated key $key in $path', + ); + } + } + }); + + test('diagnostic codes are snake_case', () { + final codes = { + for (final name in ['code', 'warningCode']) + ..._identifierValues( + sources, + name: name, + forwards: {'code', 'warning.code', 'warningCode'}, + ), + }; + + expect( + codes.length, + greaterThan(10), + reason: 'the scan found too few codes', + ); + for (final MapEntry(key: code, value: path) in codes.entries) { + expect(_isSnakeCase(code), isTrue, reason: '$code in $path'); + } + }); + + test('emitted errors use camelCase fields and snake_case identifiers', () { + final maps = >[ + Ack.string().safeParse(1).getError().toMap(), + Ack.string().minLength(5).safeParse('a').getError().toMap(), + Ack.enumString(['open']).safeParse('opne').getError().toMap(), + // A snake_case wire key stays in the payload, which the walk skips. + Ack.object({'user_id': Ack.string()}) + .safeParse({'user_id': 1}) + .getError() + .toMap(), + Ack.string().refine((_) => false).safeParse('a').getError().toMap(), + Ack.string() + .transform((_) => throw const FormatException('bad')) + .safeParse('a') + .getError() + .toMap(), + Ack.object({'a': Ack.string()}) + .safeEncode({'a': 'x', 'b': 1}) + .getError() + .toMap(), + Ack.fromJsonSchema({ + 'enum': ['x'], + }).safeParse('y').getError().toMap(), + for (final warning in Ack.object({ + 'x': Ack.any(), + }).toSchemaModel().allWarnings) + warning.toJson(), + ]; + try { + Ack.string().parse(1); + } on AckException catch (exception) { + maps.add(exception.toMap()); + } + + final trimWarnings = Ack.string() + .trim() + .minLength(4) + .toSchemaModel() + .allWarnings + .map((warning) => warning.toJson()) + .toList(); + expect( + trimWarnings, + everyElement(contains('context')), + reason: 'a schema-model warning with context serializes `context`', + ); + maps.addAll(trimWarnings); + + final fields = {}; + final identifiers = {}; + void walk(Object? value) { + if (value is Map) { + for (final MapEntry(:key, value: child) in value.entries) { + fields.add('$key'); + if ((key == 'constraintKey' || key == 'code') && child is String) { + identifiers.add(child); + } + // User input keeps its own spelling. + if (!_payloadFields.contains(key)) walk(child); + } + } else if (value is Iterable) { + value.forEach(walk); + } + } + + maps.forEach(walk); + + expect( + fields, + containsAll([ + 'constraintKey', + 'propertyKey', + 'validationError', + 'keywordLocation', + 'context', + ]), + reason: 'a sample error stopped producing an expected field', + ); + for (final field in fields) { + expect( + RegExp(r'^[a-z][a-zA-Z0-9]*$').hasMatch(field), + isTrue, + reason: field, + ); + } + expect( + identifiers, + containsAll(['string_min_length', 'ack_any_json_boundary']), + ); + for (final identifier in identifiers) { + expect(_isSnakeCase(identifier), isTrue, reason: identifier); + } + + try { + Ack.fromJsonSchema({ + r'$schema': 'http://json-schema.org/draft-07/schema#', + 'dependencies': { + 'a': ['b'], + }, + }); + fail('expected the Draft-7 dependencies import to fail'); + } on JsonSchemaImportException catch (exception) { + for (final diagnostic in exception.diagnostics) { + expect(_isSnakeCase(diagnostic.code), isTrue, reason: diagnostic.code); + } + } + }); +} + +/// The only constraint key built from a value: a user-named pattern. +const _interpolatedKeys = {r'string_pattern_$patternName'}; + +/// Serialized fields whose contents are user input, not Ack field names. +const _payloadFields = {'value', 'inputValue', 'stringValue'}; + +/// The identifier values given to [name] in [sources], keyed to a path. +/// +/// Checks named arguments (`name: value`) and parameter defaults +/// (`name = value`). A value must be one string literal, one of the +/// [forwards], or a ternary whose results are each one of those. Anything +/// else fails, so a computed or transformed value cannot slip past. +Map _identifierValues( + Map sources, { + required String name, + required Set forwards, +}) { + final values = {}; + final literal = RegExp(r'''(['"])((?:(?!\1).)*)\1'''); + for (final MapEntry(key: path, value: source) in sources.entries) { + for (final match in RegExp( + '\\b$name(?::\\s|\\s*=(?![=>])\\s*)', + ).allMatches(source)) { + if (_insideString(source, match.start)) continue; + // The value ends at the next named argument, the end of the argument + // list or statement, or the end of a parameter default. + final rest = source.substring(match.end); + final end = rest.indexOf(RegExp(r'\b\w+:\s|\)\s*[;,{]|;|,\s*\n|\}')); + var expression = (end < 0 ? rest : rest.substring(0, end)) + .trim() + .replaceAll(RegExp(r',$'), '') + .trim(); + // Drop closing parentheses that belong to the enclosing call. + while (expression.endsWith(')') && + ')'.allMatches(expression).length > + '('.allMatches(expression).length) { + expression = expression.substring(0, expression.length - 1).trim(); + } + // Mask literals, then check the expression, or each result of a + // ternary: every one must be a single literal or a listed forward. + final found = []; + final masked = expression.replaceAllMapped(literal, (match) { + found.add(match.group(2)!); + return '\u0000${found.length - 1}\u0000'; + }); + final question = masked.indexOf('?'); + final results = question < 0 + ? [masked] + : masked.substring(question + 1).split(':'); + for (final result in results.map((result) => result.trim())) { + final placeholder = RegExp(r'^\u0000(\d+)\u0000$').firstMatch(result); + if (placeholder != null) { + values[found[int.parse(placeholder.group(1)!)]] = path; + } else { + expect( + forwards, + contains(result), + reason: 'unrecognized $name value `$expression` in $path', + ); + } + } + } + } + return values; +} + +/// [source] with `//` comment lines removed, keeping string contents intact. +String _withoutComments(String source) => source + .split('\n') + .map((line) => line.trimLeft().startsWith('//') ? '' : line) + .join('\n'); + +/// Whether [offset] in [source] falls inside a string literal on its line. +bool _insideString(String source, int offset) { + final lineStart = source.lastIndexOf('\n', offset) + 1; + final before = source.substring(lineStart, offset); + var single = false; + var double = false; + for (final char in before.split('')) { + if (char == "'" && !double) single = !single; + if (char == '"' && !single) double = !double; + } + return single || double; +} + +/// Whether [value] is lowercase snake_case once interpolations are removed. +/// +/// An interpolated suffix such as `string_pattern_$name` leaves a trailing +/// underscore, which is allowed. +bool _isSnakeCase(String value) { + final interpolation = RegExp(r'\$\{[^}]*\}|\$[A-Za-z_]\w*'); + final interpolated = interpolation.hasMatch(value); + final stable = value.replaceAll(interpolation, ''); + final pattern = interpolated + ? RegExp(r'^[a-z][a-z0-9]*(_[a-z0-9]+)*_?$') + : RegExp(r'^[a-z][a-z0-9]*(_[a-z0-9]+)*$'); + return pattern.hasMatch(stable); +} diff --git a/packages/ack_firebase_ai/README.md b/packages/ack_firebase_ai/README.md index 04762b3c..6fb416ce 100644 --- a/packages/ack_firebase_ai/README.md +++ b/packages/ack_firebase_ai/README.md @@ -1,24 +1,9 @@ # ack_firebase_ai -Firebase AI (Gemini) structured-output adapter for the [ACK](https://pub.dev/packages/ack) validation library. +Firebase AI (Gemini) structured-output adapter for [Ack](https://pub.dev/packages/ack): it renders an Ack schema as the map that `GenerationConfig.responseJsonSchema` accepts. [![pub package](https://img.shields.io/pub/v/ack_firebase_ai.svg)](https://pub.dev/packages/ack_firebase_ai) -## Overview - -`ack_firebase_ai` converts ACK schemas to the JSON-compatible map accepted by Firebase AI's `GenerationConfig.responseJsonSchema`. - -The adapter is intentionally thin: - -```text -AckSchema - -> AckSchemaModel - -> JSON Schema map - -> GenerationConfig.responseJsonSchema -``` - -Always validate model output with the same ACK schema after generation. Firebase response schemas guide generation, but ACK remains the runtime validator. - ## Installation ```yaml @@ -32,7 +17,7 @@ This package targets Firebase AI's map-based `responseJsonSchema` API for models ## Usage -In a Flutter app that has initialized Firebase: +Pass `toFirebaseAiResponseJsonSchema()` to `GenerationConfig`, then validate the response with the same schema. In a Flutter app that has initialized Firebase: ```dart import 'dart:convert'; @@ -78,41 +63,18 @@ Future main() async { } ``` -## Schema Mapping +## Schema mapping + +The adapter returns `AckSchema.toJsonSchema()` unchanged. Native Ack schemas use the Draft-7 representation. Imported Draft 2020-12 schemas keep their resources and dialect. The adapter does not lower or filter provider-specific keywords. -The adapter returns `AckSchema.toJsonSchema()` unchanged. Native Ack schemas -use the Draft-7 representation; imported Draft 2020-12 schemas preserve their -resources and dialect. The adapter does not lower or filter provider-specific -keywords. +For how each Ack type and constraint maps to JSON Schema, see [JSON Schema Integration](https://concepta.dev/documentation/ack/guides/json-schema-integration#how-constraints-map-to-json-schema). These two cases need a note: -| ACK schema | JSON Schema output | +| Ack schema | JSON Schema output | | --- | --- | -| `Ack.string()` | `type: string` | -| `Ack.integer()` | `type: integer` | -| `Ack.double()` | `type: number` | -| `Ack.boolean()` | `type: boolean` | -| `Ack.object({...})` | `type: object`, `properties`, `required` | -| `Ack.list(...)` | `type: array`, `items` | -| `Ack.enumString([...])` / `Ack.enumValues(...)` | `enum` | -| `Ack.literal(...)` | `const` | -| `Ack.anyOf([...])` | `anyOf` | | `Ack.discriminated(...)` | `anyOf` with exact discriminator `const` branches | -| `Ack.any()` | JSON-compatible primitive/object/array branches | +| `Ack.any()` | JSON-compatible primitive, object and array branches | -Supported ACK constraints are preserved when they can be represented in JSON -Schema, including string length and pattern keywords, numeric bounds, -`multipleOf`, array length, `uniqueItems`, nullability, defaults, and additional -properties policy. - -Firebase serializes `responseJsonSchema` as a map, but Gemini supports a subset -of JSON Schema and may ignore unsupported keywords. Treat the generated schema -as model guidance and ACK validation as the authoritative runtime check. - -## Discriminated Unions - -`Ack.discriminated(...)` owns the discriminator. Branch schemas may omit the -discriminator property; the schema model injects an exact `const` -discriminator into each branch export. +`Ack.discriminated(...)` owns the discriminator. Branch schemas may omit the discriminator property. The schema model adds an exact `const` discriminator to each branch export. ```dart compile=firebase-shape final shapeSchema = Ack.discriminated>( @@ -126,72 +88,17 @@ final shapeSchema = Ack.discriminated>( final jsonSchema = shapeSchema.toFirebaseAiResponseJsonSchema(); ``` -The generated map contains `anyOf` branches with exact `type` literals. It does -not emit OpenAPI-style `discriminator` metadata. +The generated map contains `anyOf` branches with exact `type` literals. It does not emit OpenAPI-style `discriminator` metadata. ## Limitations -Firebase AI response schemas are generation guidance, not a substitute for validation. Validate generated JSON with ACK before using it. - -Custom refinements and transforms that cannot be represented as JSON Schema are not enforceable by Firebase AI. ACK still enforces them after parsing. - -Schema size counts toward the model input token budget. Keep response schemas focused on the shape you need back. - -## Live Contract Test - -The normal test suite does not call Firebase. To verify the adapter against a real Firebase AI project, run the opt-in live test with Firebase app credentials: +- Firebase serializes `responseJsonSchema` as a map, but Gemini supports a subset of JSON Schema and may ignore unsupported keywords. +- A response schema guides generation. It does not replace validation. Always validate generated JSON with the same Ack schema before you use it. +- Firebase cannot enforce custom refinements and transforms that JSON Schema cannot represent. Ack enforces them when you parse. +- Schema size counts toward the model input token budget. Keep response schemas focused on the shape you need back. -```bash -firebase projects:list -firebase apps:list --project -gcloud services enable firebasevertexai.googleapis.com --project -``` - -Use a Firebase Web app's SDK config for the environment values below. The project also needs Firebase AI Logic configured for the selected backend. - -```bash -ACK_FIREBASE_AI_LIVE=1 \ -ACK_FIREBASE_AI_BACKEND=google_ai \ -ACK_FIREBASE_AI_MODEL=gemini-3.5-flash \ -FIREBASE_API_KEY=... \ -FIREBASE_PROJECT_ID=... \ -FIREBASE_APP_ID=... \ -FIREBASE_MESSAGING_SENDER_ID=... \ -flutter test test/live_firebase_ai_response_json_schema_test.dart -``` - -The test uses `GenerationConfig.responseJsonSchema`, sends real Gemini requests, -decodes each response, and validates it with the same ACK schema. It covers -nested objects/lists, `anyOf`, nullable fields, transformed date output, -union-owned discriminators, and `Ack.any()` payloads. By default it uses -Firebase AI's Gemini Developer API backend with `gemini-3.5-flash`. Set -`ACK_FIREBASE_AI_MODEL` to test a different 3.x model, for example -`gemini-3-flash-preview` when the default model is temporarily high-demand. - -The same values can also be passed with `flutter test --dart-define=...`. Use the Firebase app values from your FlutterFire-generated `DefaultFirebaseOptions.currentPlatform` or Firebase console app settings. To run the live test against the Vertex AI backend, set: - -```bash -ACK_FIREBASE_AI_BACKEND=vertex_ai \ -FIREBASE_AI_LOCATION=global -``` +## Learn more -## Fixture Golden Tests - -The committed fixture tests are the normal adapter contract and do not require -Firebase credentials. They compare ACK conversion output against JSON fixtures -under `test/fixtures/firebase_ai_response_json_schema/`, capture Firebase SDK -`Schema.toJson()` and `JSONSchema.toJson()` native fixture output, and verify -the same maps serialize through Firebase AI's -`GenerationConfig.responseJsonSchema`. - -Regenerate the fixtures after an intentional schema-output change: - -```bash -dart run tool/generate_firebase_ai_response_json_schema_fixtures.dart -``` - -From the workspace root, the same generator is available through Melos: - -```bash -dart run melos run firebase-ai-fixtures -``` +- [Ecosystem Integrations](https://concepta.dev/documentation/ack/guides/ecosystem-integrations) +- [JSON Schema Integration](https://concepta.dev/documentation/ack/guides/json-schema-integration) +- Run the adapter tests: see [test/README.md](test/README.md). diff --git a/packages/ack_firebase_ai/test/README.md b/packages/ack_firebase_ai/test/README.md new file mode 100644 index 00000000..b77e7717 --- /dev/null +++ b/packages/ack_firebase_ai/test/README.md @@ -0,0 +1,62 @@ +# ack_firebase_ai tests + +Contributor instructions for the `ack_firebase_ai` test suite. For usage, see the [package README](../README.md). + +## Live Contract Test + +The normal test suite does not call Firebase. To verify the adapter against a real Firebase AI project, run the opt-in live test with Firebase app credentials: + +```bash +firebase projects:list +firebase apps:list --project +gcloud services enable firebasevertexai.googleapis.com --project +``` + +Use a Firebase Web app's SDK config for the environment values below. The project also needs Firebase AI Logic configured for the selected backend. + +```bash +ACK_FIREBASE_AI_LIVE=1 \ +ACK_FIREBASE_AI_BACKEND=google_ai \ +ACK_FIREBASE_AI_MODEL=gemini-3.5-flash \ +FIREBASE_API_KEY=... \ +FIREBASE_PROJECT_ID=... \ +FIREBASE_APP_ID=... \ +FIREBASE_MESSAGING_SENDER_ID=... \ +flutter test test/live_firebase_ai_response_json_schema_test.dart +``` + +The test uses `GenerationConfig.responseJsonSchema`, sends real Gemini requests, +decodes each response, and validates it with the same Ack schema. It covers +nested objects/lists, `anyOf`, nullable fields, transformed date output, +union-owned discriminators, and `Ack.any()` payloads. By default it uses +Firebase AI's Gemini Developer API backend with `gemini-3.5-flash`. Set +`ACK_FIREBASE_AI_MODEL` to test a different 3.x model, for example +`gemini-3-flash-preview` when the default model is temporarily high-demand. + +The same values can also be passed with `flutter test --dart-define=...`. Use the Firebase app values from your FlutterFire-generated `DefaultFirebaseOptions.currentPlatform` or Firebase console app settings. To run the live test against the Vertex AI backend, set: + +```bash +ACK_FIREBASE_AI_BACKEND=vertex_ai \ +FIREBASE_AI_LOCATION=global +``` + +## Fixture Golden Tests + +The committed fixture tests are the normal adapter contract and do not require +Firebase credentials. They compare Ack conversion output against JSON fixtures +under `test/fixtures/firebase_ai_response_json_schema/`, capture Firebase SDK +`Schema.toJson()` and `JSONSchema.toJson()` native fixture output, and verify +the same maps serialize through Firebase AI's +`GenerationConfig.responseJsonSchema`. + +Regenerate the fixtures after an intentional schema-output change: + +```bash +dart run tool/generate_firebase_ai_response_json_schema_fixtures.dart +``` + +From the workspace root, the same generator is available through Melos: + +```bash +dart run melos run firebase-ai-fixtures +``` diff --git a/packages/ack_generator/README.md b/packages/ack_generator/README.md index 6abc8e60..5244f924 100644 --- a/packages/ack_generator/README.md +++ b/packages/ack_generator/README.md @@ -1,10 +1,10 @@ # Ack Generator -`ack_generator` supports two directions through `@Schemable()`: -it turns a top-level Ack schema into an immutable model and derives an Ack -codec schema from a hand-written class. `@Schemable()`, `@AckKey()`, and the -`Is…`/`Has…` rule annotations (such as `@IsEmail()` and `@HasMinLength(2)`) are -all exported from `package:ack/ack.dart`. +`ack_generator` supports two directions through `@Schemable()`: it turns a +top-level Ack schema into an immutable model, and it derives an Ack codec schema +from a hand-written class. It also compiles `.schema.json` files into models. +`@Schemable()`, `@AckKey()`, and the `Is…`/`Has…` rule annotations (such as +`@IsEmail()` and `@HasMinLength(2)`) come from `package:ack/ack.dart`. The generator supports Analyzer 13.3.0 through 14.x and build 4.x through 5.x. When keeping build_runner 2.16, use a compatible Analyzer 13.x release from @@ -16,94 +16,10 @@ When keeping build_runner 2.16, use a compatible Analyzer 13.x release from dart pub add ack:^2.0.0-beta.3 dev:ack_generator:^2.0.0-beta.3 dev:build_runner ``` -## Generate models from JSON Schema +## Schema-first -The opt-in `ack_json_schema` builder turns a draft 2020-12 JSON Schema into -models. It emits typed `@Schemable` models for shapes it can represent as Ack -fields. For other valid 2020-12 shapes, it emits validated value models backed -by `Ack.fromJsonSchema`, preserving every supported assertion. Name the source -`lib/contract.schema.json`; named `$defs` entries produce models, and a schema -with root assertions also produces `Root` (`DocumentRoot` when `$defs/Root` -already owns that name): - -```json -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$defs": { - "User": { - "type": "object", - "properties": { "name": { "type": "string" } }, - "required": ["name"], - "additionalProperties": false - } - } -} -``` - -Enable the builder in the consuming package's `build.yaml`: - -```yaml -targets: - $default: - builders: - ack_generator:ack_json_schema: - enabled: true - options: - unknown_properties: schema - assert_formats: false - normalize_unicode: false - model_mode: auto # use validated for exact source-schema parity - # Optional offline resources: retrieval URI -> package asset path. - # documents: - # "https://example.test/common.json": "lib/common.json" -``` - -Run `dart run build_runner build`. Import `contract.schema.dart` to use the -generated models. A typed model also writes `contract.schema.g.dart` and offers -typed fields and `copyWith`. A validated value model needs no parts: -`User.parse(value)` returns a wrapper whose immutable `value` is the validated -JSON value; `User.encode(model)`, `User.safeEncode(model)`, and `model.toJson()` -revalidate on output. The `userSchema` declaration and `User.schema` expose the -exact source validator. Do not hand-edit generated files. - -The default `unknown_properties: schema` follows each object's -`additionalProperties`. Choose `preserve` for a forward-compatible client: it -widens `additionalProperties: false` to `true` at every object, records every -widened JSON pointer in the generated header, and captures unknown fields in -`additionalProperties`. The source JSON Schema is never rewritten. This is a -deliberate change to the effective validation contract. - -Typed output covers named non-null objects, references to named definitions, -inline objects, maps, arrays with non-null items, common primitives and bounds, -string enums, and simple unions in fields. Other valid shapes—including named -scalar unions, regex patterns, recursive and dynamic references, composition, -nullable roots and items, `multipleOf`, unevaluated keywords, and format -assertions—use validated value models. Patterns use the source validator to -preserve Unicode regex semantics, including astral characters. Integral decimal -length and item bounds are normalized to integers; bounds outside the Dart -integer range use validated value models. `assert_formats: true` opts into -format assertions under the standard dialect; unknown asserted formats and -unresolved or malformed schemas fail the build with a JSON-pointer diagnostic. -Set `normalize_unicode: true` and add `unorm_dart` to the consuming package's -runtime dependencies to use NFKC for international hostname labels in generated -format assertions. This also applies to the hostname part of email addresses. -External resources are read only from the explicit `documents` mapping; the -builder never fetches URLs. The complete required 2020-12 corpus generates -offline with its supplied resources. Custom vocabulary support is limited to -what `Ack.fromJsonSchema` implements. - -Definitions with non-Dart names receive stable UpperCamelCase wrapper names. -If the entire document uses fallback, all its models are value wrappers so -references and dynamic scope stay bound to the same effective source document. -Validated wrappers do not expose inferred fields or typed `copyWith`. - -An integral JSON number beyond Dart's `int` range is a known edge case: -`Ack.fromJsonSchema` can accept it as an integral `double`, while a typed -`Ack.integer()` model cannot represent it as an `int`. Set -`model_mode: validated` when that numeric edge case matters. String length -bounds count Unicode code points in both typed output and imported schemas. - -## Schema-first usage +Annotate a top-level schema. A declaration ending in `Schema` loses that suffix, +so `userSchema` generates `User`. ```dart compile=model import 'package:ack/ack.dart'; @@ -117,8 +33,7 @@ final userSchema = Ack.object({ }); ``` -Run `dart run build_runner build`. A declaration ending in `Schema` loses that -suffix, so `userSchema` generates `User`: +Run `dart run build_runner build`, then use the typed model: ```dart compile=readme-user-parse void main() { @@ -132,31 +47,12 @@ void main() { } ``` -`User.schema` is the model-valued schema: it parses input into `User` and -encodes a `User` back, so it composes like any other Ack schema: - -```dart compile=readme-user-list -final users = Ack.list(User.schema).parse(json)!; // List -``` +Constructors do not validate. Use `parse` for untrusted input. -It is a shorthand for `User.$ack.modelSchema`. The generator omits it when the -model has a field or union discriminator named `schema`, when the annotated -declaration is itself named `schema`, or when the library imports a prefix -named `schema`; use `$ack.modelSchema` there. +## Class-first -Constructors don't validate immediately. Use `parse` for untrusted input; -`toJson` and `safeToJson` validate a directly constructed model while encoding -it. Generated models don't implement `Map`, and there are no `fromMap` or -`toMap` aliases. - -Omit `name` when the inferred class name is right. Use -`@Schemable(name: 'Member')` only when you need an exact custom name. Custom -names must be unchanged UpperCamelCase identifiers. - -## Class-first usage - -In a class-first library, keep the model in source (using a standard or Dart 3.13+ -primary constructor) and apply the generated mixin: +Keep the model in source and apply the generated mixin. The class may use a +standard or a Dart 3.13+ primary constructor. ```dart compile=model import 'package:ack/ack.dart'; @@ -171,211 +67,53 @@ final class const Account({@HasMinLength(2) required final String name}) } ``` -After generation, `Account.schema`, the public `AccountSchema` facade, and model -JSON methods all use the same Ack codec boundary: - -```dart compile=readme-account -void main() { - final account = Account.fromJson({'name': 'Ada'}); - print(account.toJson()); - print(Account.schema.toJsonSchema()); -} -``` - -### Heterogeneous JSON fields - -A field whose values are native JSON needs no wrapper. `Ack.any()` and an -`Ack.anyOf(...)` whose branches are all native JSON (strings, numbers, -booleans, `Ack.any()`, inline objects, and lists, maps, unions, or lazy schemas -of those) become `Object` fields, including as list items and map values: - -```dart compile=readme-answer -final answerValue = Ack.anyOf([ - Ack.string(), Ack.number(), Ack.list(Ack.string()), -]); - -@Schemable() -final answerSchema = Ack.object({'values': Ack.map(answerValue)}); -// Generates `final Map values;`. -``` - -A union branch must not decode its value. Codec branches such as -`Ack.datetime()`, `Ack.enumValues(...)`, and `.codec(...)`, `Ack.instance()`, -model schemas, and nullable branches are rejected; mark the union itself -`.nullable()` instead. Use `Ack.discriminated(...)` for a union of models. -`Ack.anyOf(...)` model roots remain unsupported. Branches are proven from their -static schema types and statically resolvable initializers. A custom method -whose declared runtime type is `Object` or a JSON collection but that returns a -codec cannot be detected. - -`Ack.preserveBoundary(...)` stores the JSON of a codec-bearing object, map, or -discriminated union. It validates with the full typed schema and keeps the -wire value, so a field over a preserved object is a `Map`, and -a field over a preserved `Ack.map(...)` keeps each value's wire type (a JSON -number is a `num`). A preserved object can also be a union branch. Put -`withDefault(...)` outside the wire view; a default inside it does not apply. - -The constructor snapshots nested JSON collections without validating them. -Parsing and encoding still enforce the original schema. Opaque codec runtime -values retain their identity and runtime container types. Statically -unresolvable or opaque JSON schemas are rejected instead of inferred. - -### Custom schema resolution - -A field of custom type `T` (including inside `List`, `Set`, `Map`, -`JsonMaybe`, or generic type-owned schemas `Box`) resolves in priority order: - -1. **`@Schemable(schemas: [...])`** on the class, enclosing union base, current - `library;` directive, or an imported `library;` directive; -2. **Type-owned schema**: a static `T.schema` or `T.schema(...)` on the type; -3. **Automatic current-library detection**: a unique top-level - `AckSchema` variable, getter, or zero-argument function in the - current library. - -A generic type declares `static AckSchema> schema()`, which is called -with the field's type arguments, for example `Command.schema()` -or `Command.schema()`. A `schema()` that declares one positional -`AckSchema` parameter per type parameter `A` receives each type -argument's inferred schema, as in `Box.schema(RowSchema.schema)`. An enum -with a static `schema` or a `@Schemable(schemas: [...])` entry resolves to it -instead of `Ack.enumValues`. A class may also expose its own generated codec -with `static final schema = AccountSchema.schema;`. +Run `dart run build_runner build`. `Account.schema`, the public `AccountSchema` +facade, and the model JSON methods share one Ack codec boundary. -Use `@Schemable(description: ...)` for class descriptions and a single-line -`@description` tag in a `///` or `/** */` doc comment on a class, field, or -constructor parameter for schema descriptions. Only the text after the tag, on -the same line, is exported. Untagged prose never becomes schema data. Duplicate -or blank tags fail generation. Annotation text on `@Schemable(description: ...)` -takes precedence over a class doc tag. A class description applies to both the -object schema and model codec, including union bases and branches. A field -description applies at its property without changing a nested model. -The generator shares its type and constraint inference through -`package:ack_generator/inference.dart`. A second generator can use -`AckSchemaInference.inferType`, `applyConstraints`, and `applyDescription`. -The caller resolves application model types and import prefixes. For function -parameters, read the documentation comment from the source AST and pass it as -`sourceComment` to `applyDescription`. That method uses the same tag-only rule. - -## Schema support - -The generator supports objects, empty objects, scalar and collection roots, -literals, enums, defaults, additional properties, built-in and custom -bidirectional codecs, two-way string normalizers (`.trim()`, `.toLowerCase()`, -`.toUpperCase()`), `JsonMaybe` PATCH presence fields, named nested models, -aliases, named `Ack.lazy` recursion, and same-library discriminated unions. -Lists, sets, and maps stored by a model generated from a `@Schemable()` schema -are copied recursively into unmodifiable collections. Class-first parsing -provides the same guarantee, including for captured extras. Hand-written -constructors and collection replacements passed to `copyWith` remain responsible -for their own defensive copies; use `deepUnmodifiableJsonMap` for dynamic JSON -maps. Raw `Ack.object(..., additionalProperties: true)` schemas preserve extras, -while a class-first model applies its later `unknownProperties` projection. Use -`discard` only for tolerant, read-only consumers and `capture` for round trips. - -Generation rejects shapes without a useful static, encodable model contract: +## Naming and unions -- one-way `.transform()` calls; use `.codec()` with an encoder; -- nullable roots; -- nullable `Ack.list` item schemas and automatically inferred `List` or - `Set` fields; make the collection or element type non-nullable; -- `Ack.any()` and `Ack.map()` roots (both are supported as fields), - `Ack.anyOf()`, and bare `Ack.instance()`; -- anonymous inline object fields and unresolved dynamic schema factories; -- invalid names, generated-member collisions, and cross-library union branches; -- types the annotated library cannot name, because a generated part cannot add - imports; -- `@Schemable` options set for the other target. +- Schema-first field names are lowerCamelCase: `UserID` becomes `userId`, `URLs` + becomes `urls`, and `address_2` becomes `address2`. Wire keys keep their + original spelling. +- Generation rejects keys that contain non-ASCII letters (punctuation such as + `—` only separates words) and keys that collide after naming. Use a + class-first model with `@AckKey` for those keys. +- Union branches inherit the base `caseStyle`. +- A sealed-union base or branch may declare `static schema` only as a direct + alias of its generated facade's schema. +- Generated `Set` fields reject duplicate JSON values and export + `uniqueItems: true`. -Named model references work through direct imports, prefixes, and re-exports. -Nested conversion uses each model's public `$ack` adapter so codec runtime -values aren't parsed twice. +## `.schema.json` builder options -Schema-first fields retain optional, nullable, and default behavior through -named schema variables and getters. Explicit constant flag overrides such as -`.optional(value: false)` are honored, as is the outermost `.strict()` or -`.passthrough()` object policy. Shape-changing object methods (`extend`, -`partial`, `merge`, `pick`, `omit`, or `copyWith(properties: ...)`) are rejected -when generating an object model; write its final properties in an -`Ack.object({...})` map literal instead. An outer bidirectional codec can still -wrap such a schema as a value model. +Set these under `ack_generator:ack_json_schema` in `build.yaml`. -## Generated part - -Every annotated library declares a single `.g.dart` part: - -```dart compile=part-directive -part 'account.g.dart'; -``` - -`ack_generator` emits both the Ack schema/model facade and the structural JSON -helpers directly into `.g.dart` via `SharedPartBuilder` (without requiring -`json_serializable`), and coexists cleanly with other `SharedPartBuilder` -generators in the same `.g.dart` file. - -`copyWith` is a getter that returns a typed `$AccountCopyWith` -interface. Call it as `account.copyWith(name: 'Grace')`. Omitted arguments keep -their current values, explicit `null` clears nullable fields, and arguments -with incompatible static types fail analysis. - -The generated part starts with `// ignore_for_file: type=lint` and -`// coverage:ignore-file`, so your lint rules and coverage reports apply only to -your own source. - -## Supported declarations - -On a schema, `@Schemable()` annotates top-level schema variables and top-level -schema getters; instance members and local variables are rejected. Only its -`name` option applies there. - -On a `library;` directive, `@Schemable(schemas: [...])` registers custom schemas -shared by all `@Schemable` classes in that library and any library that imports it. - -On a class, `@Schemable()` annotates public, constructable `final class` declarations whose -stored fields are final. Annotated sealed union bases remain supported, and -their concrete branches must also be final. Use `@IsOptional()` or -`@IsRequired()` to override inferred key presence, `@IsNotNull()` -to reject JSON `null` without requiring the key, `JsonMaybe` to distinguish -omitted keys from explicit `null` on both parse and encode, and -`@AckKey('wire_name')` to override a single field's JSON key. Rule -annotations add constraints (such as `@HasMatch(pattern)` for -`Ack.string().matches(pattern)`, which is not anchored). See the -[Model Code Generation guide](https://concepta.dev/documentation/ack/advanced/typesafe-schemas) -for both directions, field inference, sealed unions, passthrough properties, -and build configuration. - - -Open JSON and presence-aware fields are inferred from their Dart types. `Object` -means a JSON-safe value, not an arbitrary Dart instance: - -| Dart field | Inferred schema | +| Option | Purpose | | --- | --- | -| `Object` / `Object?` | `Ack.any()` / `Ack.any().nullable()` | -| `List` | `Ack.list(Ack.any())`; `List` is rejected | -| `Map` | `Ack.map()` | -| `Map` | `Ack.map(Ack.any().nullable())` | -| `JsonMaybe` | Optional-and-nullable ``; omitted when `JsonAbsent`, `null` when `JsonValue(null)` | -| `dynamic` | rejected; use `Object?` | - -For a hand-written `Account`, class-first generation exposes an -`AccountSchema` facade backed by a private codec variable. The facade -provides parsing, safe parsing, encoding, JSON Schema/schema-model export, -typed `schema`, and a `wireSchema` that validates like `schema` but returns the -JSON map. Instantiable models apply the generated -`_$AccountAck` mixin, which supplies `toJson`, `safeToJson`, a typed `copyWith`, -and deep collection-aware equality. Add `static final schema = AccountSchema.schema;` -and `static final fromJson = AccountSchema.fromJson;` when the class should -expose the schema and one-argument JSON constructor directly. Imported nested -models compose as `prefix.AddressSchema.schema` (or `prefix.Address.schema` when -`Address.schema` is declared and `AddressSchema` is hidden by a combinator). -Across all imports and barrel exports, `show`/`hide` combinators must expose the -authored declaration and either `Address.schema` or its generated companion -(`AddressSchema` for class-first, or `Address` for schema-first). Visibility may -be split across multiple imports that use the same prefix. +| `unknown_properties` | `schema` (default) follows each object's `additionalProperties`; `preserve` widens it to `true` and captures unknown fields. | +| `assert_formats` | Asserts `format` under the standard dialect. | +| `normalize_unicode` | Applies NFKC to international hostnames and emails. Needs `unorm_dart`. | +| `model_mode` | `auto` or `validated`. Use `validated` for exact source-schema parity. | +| `documents` | Maps retrieval URIs to package asset paths for offline resources. | + +String length bounds count Unicode code points in both typed output and +imported schemas. One numeric edge case remains: `Ack.fromJsonSchema` can +accept an integral JSON number beyond Dart's `int` range as an integral +`double`, but a typed `Ack.integer()` model cannot store it as an `int`. Set +`model_mode: validated` when that case matters. + +## Inference API for other generators + +`package:ack_generator/inference.dart` shares the generator's type and +constraint inference. A second generator can call +`AckSchemaInference.inferType`, `applyConstraints`, and `applyDescription`. +The caller resolves application model types and import prefixes. For a +function parameter, read the documentation comment from the source AST and +pass it as `sourceComment` to `applyDescription`; only a `@description` tag +becomes schema data. -### Beta.2 defaults and null +## Learn more -Non-nullable fields reject an explicit JSON null even with a constructor -default; `T?` accepts it unless marked `@IsNotNull()`. An omitted key uses its -constructor default, and a null defaulted field encodes as that default. -Regenerate model parts after upgrading `ack` and `ack_generator` to -2.0.0-beta.2; these rules break beta.1 behavior. See the [migration guide](../../docs/getting-started/migration-guide.mdx). +- [Model Code Generation](https://concepta.dev/documentation/ack/core-concepts/typesafe-schemas): both directions, field inference, sealed unions, custom schema resolution, and build configuration. +- [JSON Schema Integration](https://concepta.dev/documentation/ack/guides/json-schema-integration): generating models from `.schema.json` files. +- [Migration guide](https://concepta.dev/documentation/ack/getting-started/migration-guide) diff --git a/packages/ack_json_schema_builder/README.md b/packages/ack_json_schema_builder/README.md index 67e2176d..96422fa2 100644 --- a/packages/ack_json_schema_builder/README.md +++ b/packages/ack_json_schema_builder/README.md @@ -1,54 +1,9 @@ # ack_json_schema_builder -JSON Schema Builder converter for the [ACK](https://pub.dev/packages/ack) validation library. +Adapter between [Ack](https://pub.dev/packages/ack) schemas and [`json_schema_builder`](https://pub.dev/packages/json_schema_builder) schemas, in both directions: `.toJsonSchemaBuilder()` exports an Ack schema, and `.toAckSchema()` imports a builder schema. [![pub package](https://img.shields.io/pub/v/ack_json_schema_builder.svg)](https://pub.dev/packages/ack_json_schema_builder) -## Overview - -Converts ACK schemas to json_schema_builder format via `.toJsonSchemaBuilder()` -and imports builder models via `.toAckSchema()`. - -## Importing a schema - -```dart compile=library -import 'package:ack/ack.dart'; -import 'package:ack_json_schema_builder/ack_json_schema_builder.dart'; -import 'package:json_schema_builder/json_schema_builder.dart' as jsb; - -final AckSchema schema = jsb.Schema.object( - properties: {'name': jsb.Schema.string()}, - required: ['name'], -).toAckSchema(); - -final value = schema.parse({'name': 'Ada'}); -final exported = schema.toJsonSchemaBuilder(); -``` - -Imports use ACK's Draft 2020-12 and Draft-07 importer. Supply -cross-document references through `documents: {...}` and an -optional `baseUri`; no network requests are made. Imports reject -unsupported features with `JsonSchemaImportException`; its diagnostics identify -the source keyword and location. Pass `unicodeNormalizer: nfkc` from -`package:unorm_dart` to `toAckSchema` to normalize international hostname -labels in format assertions. This applies to hostnames and email domains. Exports preserve imported Draft 2020-12 -resources by default (or lower compatible schemas to Draft-07 via -`toJsonSchemaBuilderDraft7()`). - -Supported keywords include objects (`properties`, `required`, -`additionalProperties`, `patternProperties`, `propertyNames`, `minProperties`, -`maxProperties`, `dependentRequired`, `dependentSchemas`, -`unevaluatedProperties`), arrays (`items`, `prefixItems`, `contains`, -`minContains`, `maxContains`, `minItems`, `maxItems`, `uniqueItems`, -`unevaluatedItems`), primitives, `enum`/`const`, numeric bounds and `multipleOf`, -length constraints, ECMA-262 Unicode `pattern`, `anyOf`/`allOf`/exclusive -`oneOf`/`not`, `if`/`then`/`else`, `$ref`/`$defs`/`definitions`, -`$dynamicRef`/`$dynamicAnchor`, offline 2020-12 meta-schemas, `x-*` vendor -extensions, and opt-in `assertFormats: true` for built-in string and numeric -formats. -See the [import guide](https://concepta.dev/documentation/ack/guides/json-schema-integration) -for the complete support matrix and reference/diagnostic behavior. - ## Installation ```yaml @@ -58,106 +13,83 @@ dependencies: json_schema_builder: ^0.1.3 ``` -### Compatibility - -Requires `ack: ^2.0.0-beta.2` and -`json_schema_builder: ^0.1.3` as peer dependencies. Report -[compatibility issues](https://github.com/btwld/ack/issues). - -## Conversion Model - -`ack_json_schema_builder` uses ACK's canonical adapter boundary: - -```text -AckSchema - -> AckSchemaModel - -> JSON Schema map - -> json_schema_builder Schema.fromMap() -``` - -That means defaults, const values, extension keywords, transformed-schema -metadata, composition, and discriminated-union branches follow -`AckSchema.toSchemaModel().toJsonSchema()`. +This package needs `ack: ^2.0.0-beta.2` and `json_schema_builder: ^0.1.3`. Report [compatibility issues](https://github.com/btwld/ack/issues). -## Limitations ⚠️ +## Usage -**Read this first** - json_schema_builder schema conversion has important -constraints: +Export an Ack schema, then validate data with `json_schema_builder`: -### Custom refinements +```dart +import 'package:ack/ack.dart'; +import 'package:ack_json_schema_builder/ack_json_schema_builder.dart'; +import 'package:json_schema_builder/json_schema_builder.dart'; -Conversion succeeds and omits custom refinements from the generated JSON -Schema. Validate data with the original Ack schema when those rules matter. +Future main() async { + const data = {'name': 'Ada', 'email': 'ada@example.com', 'age': 20}; -```dart compile=builder-data -final schema = Ack.string().refine((s) => s.startsWith('ACK_')); -final jsonSchema = schema.toJsonSchemaBuilder(); -final result = schema.safeParse(data); -``` + final userSchema = Ack.object({ + 'name': Ack.string().minLength(2).maxLength(50), + 'email': Ack.string().email(), + 'age': Ack.integer().min(0).max(120).optional(), + }); -### Target Schema Support + final jsonSchema = userSchema.toJsonSchemaBuilder(); -The converter uses `AckSchema.toJsonSchema()` before constructing the -`json_schema_builder` schema, preserving imported Draft 2020-12 resources by -default and emitting Draft-7 for native ACK schemas. To lower an imported -schema into legacy Draft-7 `definitions`, call -`schema.toJsonSchemaBuilderDraft7()`. If a downstream validator or consumer -ignores a JSON Schema keyword, validate with ACK after parsing. - -```dart compile=builder-library -final schema = Ack.date().min(DateTime(2026)); -final jsonSchema = schema.toJsonSchemaBuilder(); // Includes format: date. + final errors = await jsonSchema.validate(data); + if (errors.isEmpty) { + print('Data is valid!'); + } else { + print('Validation errors: $errors'); + } +} ``` -`Ack.date()` uses the local value returned by `DateTime(year, month, day)`. -That value can be later than midnight on a day with a time zone transition. -Use `DateTime.utc(...)` with `Ack.datetime()`, which requires UTC. +Import a builder schema into an executable Ack schema: -## Usage - -```dart compile=builder-validate +```dart compile=library import 'package:ack/ack.dart'; import 'package:ack_json_schema_builder/ack_json_schema_builder.dart'; -import 'package:json_schema_builder/json_schema_builder.dart'; +import 'package:json_schema_builder/json_schema_builder.dart' as jsb; -// 1. Define schema -final userSchema = Ack.object({ - 'name': Ack.string().minLength(2).maxLength(50), - 'email': Ack.string().email(), - 'age': Ack.integer().min(0).max(120).optional(), -}); - -// 2. Convert to json_schema_builder -final jsonSchema = userSchema.toJsonSchemaBuilder(); - -// 3. Use with json_schema_builder for validation -final errors = await jsonSchema.validate(data); -if (errors.isEmpty) { - print('Data is valid!'); -} else { - print('Validation errors: $errors'); -} +final AckSchema schema = jsb.Schema.object( + properties: {'name': jsb.Schema.string()}, + required: ['name'], +).toAckSchema(); + +final value = schema.parse({'name': 'Ada'}); +final exported = schema.toJsonSchemaBuilder(); ``` -## Schema Mapping +Imports use the Ack Draft 2020-12 and Draft-07 importer. Supply cross-document references through `documents: {...}` and an optional `baseUri`. The importer makes no network requests. It rejects unsupported features with `JsonSchemaImportException`, and the diagnostics identify the keyword and location. Pass `unicodeNormalizer: nfkc` from `package:unorm_dart` to normalize international hostname labels in format assertions. Pass `assertFormats: true` to assert built-in string and numeric formats. -### Supported Types +For the supported keywords and the reference and diagnostic behavior, see the [JSON Schema Integration guide](https://concepta.dev/documentation/ack/guides/json-schema-integration). -| ACK Type | json_schema_builder Type | Conversion details | -|----------|--------------------------|-------------------| -| `Ack.string()` | `Schema.string()` | Full support with minLength/maxLength | -| `Ack.integer()` | `Schema.integer()` | Full support | -| `Ack.double()` | `Schema.number()` | Full support | -| `Ack.boolean()` | `Schema.boolean()` | Full support | -| `Ack.object({...})` | `Schema.object()` | Full support | -| `Ack.list(...)` | `Schema.list()` | Full support | -| `Ack.enumString([...])` | `Schema.string()` with `enumValues` | Full support | -| `Ack.anyOf([...])` | `Schema.combined(anyOf: ...)` | Full support | -| `Ack.any()` | `Schema.combined(anyOf: ...)` | Expands to union of all types | +## Schema mapping -### Supported Constraints +The adapter renders `AckSchema.toJsonSchema()` and wraps the map with `Schema.fromMap()`: -| ACK Constraint | json_schema_builder | Notes | +```text +AckSchema + -> AckSchemaModel + -> JSON Schema map + -> json_schema_builder Schema.fromMap() +``` + +Defaults, const values, extension keywords, transformed-schema metadata, composition and discriminated-union branches follow `AckSchema.toSchemaModel().toJsonSchema()`. + +| Ack type | json_schema_builder type | Notes | +|----------|--------------------------|-------| +| `Ack.string()` | `Schema.string()` | `minLength` and `maxLength` | +| `Ack.integer()` | `Schema.integer()` | | +| `Ack.double()` | `Schema.number()` | | +| `Ack.boolean()` | `Schema.boolean()` | | +| `Ack.object({...})` | `Schema.object()` | | +| `Ack.list(...)` | `Schema.list()` | | +| `Ack.enumString([...])` | `Schema.string()` with `enumValues` | | +| `Ack.anyOf([...])` | `Schema.combined(anyOf: ...)` | | +| `Ack.any()` | `Schema.combined(anyOf: ...)` | Expands to a union of all types | + +| Ack constraint | json_schema_builder | Notes | |----------------|---------------------|-------| | `.minLength()` / `.maxLength()` | `minLength` / `maxLength` | Strings | | `.minItems()` / `.maxItems()` | `minItems` / `maxItems` | Arrays | @@ -169,24 +101,26 @@ if (errors.isEmpty) { | `Ack.literal(...)` | `const` | Literal values | | `.unique()` | `uniqueItems` | Array uniqueness | -## Testing - -```bash -cd packages/ack_json_schema_builder -dart test -``` - -## Contributing +## Limitations -For contribution guidelines, see the repository's -[CONTRIBUTING.md](https://github.com/btwld/ack/blob/main/CONTRIBUTING.md). +- Conversion succeeds and omits custom refinements from the generated JSON Schema. Validate data with the original Ack schema when those rules matter. +- A downstream validator can ignore a JSON Schema keyword. Validate with Ack after parsing. +- Native Ack schemas export as Draft-7. Imported Draft 2020-12 resources are preserved by default. To lower an imported schema to Draft-07 `definitions`, call `schema.toJsonSchemaBuilderDraft7()`. +- `Ack.date()` uses the local value from `DateTime(year, month, day)`. On a day with a time zone transition, that value can be later than midnight. See [Codecs](https://concepta.dev/documentation/ack/core-concepts/codecs). Use `DateTime.utc(...)` with `Ack.datetime()`, which requires UTC. -## License +```dart compile=builder-data +final schema = Ack.string().refine((s) => s.startsWith('ACK_')); +final jsonSchema = schema.toJsonSchemaBuilder(); +final result = schema.safeParse(data); +``` -This package is part of the [ACK](https://github.com/btwld/ack) monorepo. +```dart compile=builder-library +final schema = Ack.date().min(DateTime(2026)); +final jsonSchema = schema.toJsonSchemaBuilder(); // Includes format: date. +``` -## Related Packages +## Learn more -- [ack](https://pub.dev/packages/ack) - Core validation library -- [ack_firebase_ai](https://pub.dev/packages/ack_firebase_ai) - Firebase AI converter -- [json_schema_builder](https://pub.dev/packages/json_schema_builder) - JSON Schema builder +- [Ecosystem Integrations](https://concepta.dev/documentation/ack/guides/ecosystem-integrations) +- [Contributing](https://github.com/btwld/ack/blob/main/CONTRIBUTING.md) +- Part of the [Ack](https://github.com/btwld/ack) monorepo. See [LICENSE](LICENSE). diff --git a/packages/ack_mcp_dart/README.md b/packages/ack_mcp_dart/README.md index 90ca8aa8..96ca8579 100644 --- a/packages/ack_mcp_dart/README.md +++ b/packages/ack_mcp_dart/README.md @@ -1,6 +1,6 @@ # ack_mcp_dart -Define an MCP tool's input contract once with ACK. Use it to advertise a +Define an MCP tool's input contract once with Ack. Use it to advertise a `mcp_dart` tool schema and parse incoming arguments into validated Dart values. ```text @@ -62,7 +62,7 @@ asynchronous and receive the original `RequestHandlerExtra`. Pass a model-valued schema such as `Search.schema` (from a `@Schemable()` model or class) to `server.registerAckTool('search', input: Search.schema, callback: (args, extra) { ... })` to receive a typed `Search` instead of a map. -The model is constructed after ACK parses defaults and codecs. +The model is constructed after Ack parses defaults and codecs. ## Bare conversion and parsing @@ -92,57 +92,55 @@ Invalid arguments for tool 'search': #/query: Query must contain non-whitespace characters. ``` +## Error messages and sensitive input + The helpers do not append input values, error causes, or stack traces. Cause-backed messages (for example a codec throwing `FormatException`) become `Argument validation failed.` because exception text can contain input data. -Other messages from ACK and your refinements are preserved verbatim and may +Other messages from Ack and your refinements are preserved verbatim and may contain values; use safe custom messages or `onInvalidArguments` when inputs are sensitive. Pass `onInvalidArguments` -to `registerAckTool` to customize ACK failures. It receives the full +to `registerAckTool` to customize Ack failures. It receives the full `SchemaError` and can inspect its `cause` for the original exception. Its returned `CallToolResult` is used unchanged. ## Advertised schema vs runtime validation -`mcp_dart` validates the advertised schema **before** invoking the ACK wrapper. -ACK then applies defaults, codecs, and refinements. An ACK failure returns +`mcp_dart` validates the advertised schema **before** invoking the Ack wrapper. +Ack then applies defaults, codecs, and refinements. An Ack failure returns `isError: true`, skips the application callback, and leaves the session usable. It does not throw `McpError`. A parsed null is also rejected by the wrapper. | Behavior | Advertised schema | Runtime | | --- | --- | --- | -| Optional default | `default` annotation; field may be omitted | ACK fills the value during parse | -| Refinement | Predicate is not exported | ACK runs the predicate | -| Codec / transform | Boundary shape | ACK produces typed values, e.g. `DateTime` | +| Optional default | `default` annotation; field may be omitted | Ack fills the value during parse | +| Refinement | Predicate is not exported | Ack runs the predicate | +| Codec / transform | Boundary shape | Ack produces typed values, e.g. `DateTime` | | Integer | JSON Schema integer semantics | `2.0` becomes `int 2`; `2.5` fails | -| Structural failure | Rejected by `mcp_dart` | ACK and custom invalid handler are not reached | +| Structural failure | Rejected by `mcp_dart` | Ack and custom invalid handler are not reached | Structural failures produce an error tool result on MCP 2025-11-25 and 2026-07-28. MCP 2025-06-18 reports JSON-RPC `invalidParams` instead. This is -`mcp_dart` behavior; ACK-only failures produce tool results in all tested modes. +`mcp_dart` behavior; Ack-only failures produce tool results in all tested modes. ### JSON Schema dialect -ACK renders Draft-7 keywords without a `$schema` declaration. `mcp_dart` uses +Ack renders Draft-7 keywords without a `$schema` declaration. `mcp_dart` uses 2020-12 when that declaration is absent. The adapter does not stamp `$schema` -or strip extensions: the tested ACK keyword subset works in both dialects. +or strip extensions: the tested Ack keyword subset works in both dialects. Recursive `definitions` and local `$ref` are retained, and annotated references -are wrapped by ACK in `allOf`. Schema maps round-trip exactly; JSON object key +are wrapped by Ack in `allOf`. Schema maps round-trip exactly; JSON object key order may change when `mcp_dart` serializes them. -Tests pin the supported keyword set: `type`, `properties`, `required`, -`additionalProperties`, `minimum`, `maximum`, `exclusiveMinimum`, -`exclusiveMaximum`, `multipleOf`, `minLength`, `maxLength`, `pattern`, `format`, -`enum`, `const`, `items`, `minItems`, `maxItems`, `uniqueItems`, `anyOf`, `oneOf`, -`allOf`, `$ref`, `definitions`, `title`, `description`, `default`, and `x-*`. -New emitted keywords require revisiting this dialect assumption. +Tests pin the supported keyword set: the core type, object, array, string and numeric keywords, `anyOf`/`oneOf`/`allOf`, `$ref`, `definitions`, annotations and `x-*`. New emitted keywords require revisiting this dialect assumption. +For the keyword mapping, see [JSON Schema Integration](https://concepta.dev/documentation/ack/guides/json-schema-integration). ## Supported versions | Component | Supported / exercised | | --- | --- | | Dart | `>=3.13.0 <4.0.0` | -| ACK | `^2.0.0-beta.2` | +| Ack | `^2.0.0-beta.2` | | mcp_dart | `^2.4.2` | | MCP stable discovery | `2026-07-28` | | MCP initialization | `2025-11-25`, `2025-06-18` | @@ -152,7 +150,7 @@ New emitted keywords require revisiting this dialect assumption. | Input / feature | Support | | --- | --- | | Plain object root (`type: object`) | Supported, including empty objects | -| Nullable or discriminated root | Rejected at registration; renders as composition (`anyOf` in ACK) | +| Nullable or discriminated root | Rejected at registration; renders as composition (`anyOf` in Ack) | | Primitive, list, or other composition root | Rejected at registration | | Nullable, union, discriminated, recursive, or codec **fields** | Supported inside an object | | Output schemas | Declare them directly with `mcp_dart` | @@ -168,5 +166,10 @@ dart run packages/ack_mcp_dart/example/example.dart The stdio server provides `search` and an empty-object `validate` tool. Calling `search` with `{"query":"dart"}` returns a limit of `5`. Calling it with -`{"query":" "}` returns an ACK refinement error; a limit of `0` is rejected by +`{"query":" "}` returns an Ack refinement error; a limit of `0` is rejected by MCP's structural validator. `validate` accepts `{}` or omitted arguments. + +## Learn more + +- [Ecosystem Integrations](https://concepta.dev/documentation/ack/guides/ecosystem-integrations) +- [JSON Schema Integration](https://concepta.dev/documentation/ack/guides/json-schema-integration) 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 14dae26a..c8ac8204 100644 --- a/plugins/ack/skills/build-data-classes-with-ack/SKILL.md +++ b/plugins/ack/skills/build-data-classes-with-ack/SKILL.md @@ -56,8 +56,9 @@ The rules that make it build: - **Wire names:** `caseStyle:` for the whole model (`snake`, `kebab`, `pascal`, `screamingSnake`), `@AckKey('wire')` for one field. Use `@AckKey`, not `@JsonKey`. - **Descriptions** are exported only from `@Schemable(description:)` or a one-line `/// @description ...` doc tag. - **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). +- **Inferred field types:** `String`, `bool`, `int`, `double`, `num`, `DateTime` (UTC ISO string), `Uri`, `Duration` (ms), enums, `List`, `Set` (rejects duplicate JSON values and exports `uniqueItems: true`), `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). +- **Class-owned `static schema`:** build it from `XSchema.schema`, as in `XSchema.schema.refine(...)`. Do not call the facade's own `parse` or `encode` inside it; those validate through `X.schema`. - **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 diff --git a/plugins/ack/skills/build-data-classes-with-ack/references/schema-first.md b/plugins/ack/skills/build-data-classes-with-ack/references/schema-first.md index 755bb751..0e33e622 100644 --- a/plugins/ack/skills/build-data-classes-with-ack/references/schema-first.md +++ b/plugins/ack/skills/build-data-classes-with-ack/references/schema-first.md @@ -44,6 +44,8 @@ The generator rejects: Recursion uses named `Ack.lazy('Node', () => nodeSchema)`. +Generated field names come from the schema keys in lowerCamelCase: `UserID` -> `userId`, `URLs` -> `urls`, `address_2` -> `address2`. The same tokenizer names inline type segments and the discriminator getter; branch labels keep their wire spelling. The generator rejects keys that contain non-ASCII letters (punctuation such as `—` only separates words) and keys that collide after conversion; use class-first with `@AckKey` for those wire names. A `Set` field rejects duplicate JSON values and exports `uniqueItems: true`. + Check the union's export: each branch exports its own `const` discriminator (for example, `{"method": {"const": "card"}}`), and `Ack.datetime()` exports `format: date-time`. The `.min(DateTime)` bound is absent from the export. Use `Payment.schema.toSchemaModel().allWarnings` to find `datetime_constraint_not_draft7` and its JSON Pointer path. Put the bound in `.describe(...)` so it appears in the export. The same getter includes warnings for rules inside lazy targets. ## Models from `.schema.json` (opt-in builder) diff --git a/plugins/ack/skills/using-ack/references/migrate-1x.md b/plugins/ack/skills/using-ack/references/migrate-1x.md index a14f41ac..4f7afe6b 100644 --- a/plugins/ack/skills/using-ack/references/migrate-1x.md +++ b/plugins/ack/skills/using-ack/references/migrate-1x.md @@ -24,7 +24,7 @@ Done when `dart pub deps` shows the agreed 2.x release, the build writes one `.g ## Rule annotations (1.x to 2.0) -For the 2.0 beta namespace, use the [validation annotation table](https://concepta.dev/documentation/ack/getting-started/migration-guide#validation-annotations). +For the 2.0 beta namespace, use the [validation annotation table](https://concepta.dev/documentation/ack/getting-started/migration-guide#removed-1x-and-beta-annotations). | Old | New | |---|---| @@ -54,10 +54,16 @@ For the 2.0 beta namespace, use the [validation annotation table](https://concep | `server.registerAckModelTool(...)` | `server.registerAckTool(name, input: Model.schema, callback: ...)` | | `convertAckSchemaModelToBuilder(m)` | `schema.toJsonSchemaBuilder()` with `import 'package:ack_json_schema_builder/ack_json_schema_builder.dart';` | | `.trim()` as a one-way transform | `Ack.string().trim()` is now a two-way normalizer | +| `ListSchema.minLength` / `maxLength` / `exactLength` / `nonEmpty` | `minItems` / `maxItems` / `length` / `notEmpty` | +| `StringSchema.url()` | `uri()` (same validation and export) | +| `StringSchema.contains(regex)` | `matches(regex)`; `contains(substring)` now takes a literal substring | +| Code matching a built-in constraint key `list.unique`, `number.isFinite`, `integer.isSafe`, `string_format_time` | `list_unique_items`, `number_finite`, `number_safe_integer`, `string_time` (also `string.startsWith` / `string.endsWith` / `string.ip` -> `string_starts_with` / `string_ends_with` / `string_ip`) | +| `withConstraint(c)` / `withConstraints([a, b])` | `constrain(c)`; chain `constrain(a).constrain(b)`. Each constraint must mix in `Validator`. | ## Behavior changes to check in tests - `copyWith(field: null)` now **clears** a nullable field. Omitting the argument keeps the value. Code that relied on "null means keep" needs rewriting. -- Since beta.2, `withDefault` fills only an omitted key. A present `null` fails unless the field is `.nullable().withDefault(v)`. +- `withDefault` fills only an omitted key. A present `null` fails unless the field is `.nullable().withDefault(v)`. +- `SchemaError.toString()` prints one `path: message` line per failure (root lines start with `#: `). Ack no longer adds input values or callback exception text, but custom messages can still contain input. Read `value`, `cause` or `toMap()` for those details; tests that match old message text need updating. - `Ack.fromJsonSchema` no longer asserts `format` by default; pass `assertFormats: true`. - `toJsonSchema()` keeps imported 2020-12 documents; call `toJsonSchemaDraft7()` when a consumer needs Draft-7. diff --git a/test/documentation/public_snippet_wrappers.dart b/test/documentation/public_snippet_wrappers.dart index e1a12f79..0b1180cc 100644 --- a/test/documentation/public_snippet_wrappers.dart +++ b/test/documentation/public_snippet_wrappers.dart @@ -16,11 +16,6 @@ const publicSnippetWrappers = { 'expressions': SnippetWrapper.body(expressions: true), 'model': SnippetWrapper.library(generated: true), 'part-directive': SnippetWrapper.library(), - 'reference-user': SnippetWrapper.body(generated: true, splitAt: '// Usage:'), - 'reference-account': SnippetWrapper.body( - generated: true, - splitAt: 'final account =', - ), 'generator-signature': SnippetWrapper.library( imports: ''' import 'package:ack_generator/ack_generator.dart' as ack; @@ -36,11 +31,6 @@ import 'package:pub_semver/pub_semver.dart';''', 'error-data': SnippetWrapper.body( before: 'final schema = Ack.string();\nfinal data = 42;', ), - 'field-validator': SnippetWrapper.body( - imports: "import 'package:flutter/material.dart';", - before: 'final someSchema = Ack.string();\nTextFormField(', - after: ',);', - ), 'serialization': SnippetWrapper.body( stem: 'serialization', splitAt: '// Example Usage', @@ -49,14 +39,7 @@ import 'package:pub_semver/pub_semver.dart';''', imports: "import 'serialization.dart';", before: "const jsonData = {'name': 'Ada', 'age': 20};", ), - 'serialized-model': SnippetWrapper.body( - imports: "import 'package:ack_public_examples/docs/api-reference/index/user.dart';", - ), 'nested-object': SnippetWrapper.library(stem: 'nested_object'), - 'read-nested-object': SnippetWrapper.body( - imports: "import 'nested_object.dart';", - before: "const data = {'name': 'Ada', 'address': {'street': 'Main', 'city': 'A', 'zipCode': '01010'}};", - ), 'model-usage': SnippetWrapper.body(imports: "import 'models.dart';"), 'schema-first-user': SnippetWrapper.library(generated: true, stem: 'user'), 'schema-first-pet': SnippetWrapper.library( @@ -64,21 +47,15 @@ import 'package:pub_semver/pub_semver.dart';''', stem: 'schema_first_pet', ), 'profile': SnippetWrapper.library(generated: true, stem: 'profile'), - 'profile-static-members': SnippetWrapper.library( - generated: true, - stem: 'profile_static_members', - before: '@Schemable()\nfinal class const Profile({required final String displayName}) with _\$ProfileAck {', - after: '}', - ), 'profile-factory': SnippetWrapper.library( generated: true, stem: 'profile_factory', before: '@Schemable()\nfinal class const Profile({required final String displayName}) with _\$ProfileAck {', after: '}', ), - 'profile-typed-member': SnippetWrapper.library( + 'profile-static-members': SnippetWrapper.library( generated: true, - stem: 'profile_typed_member', + stem: 'profile_static_members', before: '@Schemable()\nfinal class const Profile({required final String displayName}) with _\$ProfileAck {', after: '}', ), @@ -125,9 +102,6 @@ import 'package:pub_semver/pub_semver.dart';''', stem: 'validation/constraints', splitAt: 'print(priceSchema', ), - 'custom-constraint-library': SnippetWrapper.library( - stem: 'schemas/user_schema', - ), 'price-message': SnippetWrapper.body( imports: "import 'validation/constraints.dart';\nimport 'package:test/test.dart';", after: 'expect(result.getError().message, documentedMessage);', @@ -146,6 +120,7 @@ class SignUpFormState extends State { final _emailController = TextEditingController(); final _passwordController = TextEditingController(); final _confirmPasswordController = TextEditingController(); + final _formKey = GlobalKey(); @override Widget build(BuildContext context) => const SizedBox.shrink(); @@ -166,21 +141,11 @@ class SignUpFormState extends State { 'readme-user-parse': SnippetWrapper.library( imports: "import 'user_schema.dart';", ), - 'readme-user-list': SnippetWrapper.body( - imports: "import 'user_schema.dart';", - before: "const json = [{'name': 'Ada', 'email': 'ada@example.com'}];", - ), - 'readme-account': SnippetWrapper.library(imports: "import 'account.dart';"), - 'readme-answer': SnippetWrapper.library(generated: true, stem: 'answer'), 'builder-data': SnippetWrapper.body( imports: _builder, before: "const data = 'ACK_1';", ), 'builder-library': SnippetWrapper.library(imports: _builder), - 'builder-validate': SnippetWrapper.body( - before: - "const data = {'name': 'Ada', 'email': 'ada@example.com', 'age': 20};", - ), 'search-tool': SnippetWrapper.library(stem: 'search_tool'), 'raw-search-tool': SnippetWrapper.body( imports: """