# Ack

Documentation for the Ack project

## Docs

### Overview

Source: https://docs.page/btwld/ack

```mdx

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.")

```dart
import 'package:ack/ack.dart';

final userSchema = Ack.object({
  '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',
});

if (result.isOk) {
  print('Welcome, ${result.getOrThrow()!['name']}');
} else {
  print(result.getError()); // tells you exactly which field failed, and why
}
```

On success, `getOrThrow()` returns your **validated data** as a `Map<String, Object?>`. Ack checks and shapes the data — opt into [model code generation](/core-concepts/typesafe-schemas) when you'd rather have typed getters than map access or want a schema generated from an existing class.

## Why Ack?

- **Guard your boundaries.** Catch bad API responses, user input, and config before they reach your logic.
- **Define each shape once.** Reuse one schema for validation, JSON Schema export, and typed models.
- **Errors you can act on.** Every failure points at the exact field and the reason it failed.
- **Just Dart.** A fluent API with no required build step — reach for code generation only when you want it.

## What do you want to do?

- **Validate an API response** — [Quickstart Tutorial](/getting-started/quickstart-tutorial), then [JSON Serialization](/core-concepts/json-serialization)
- **Show field errors in a Flutter form** — [Flutter Form Validation](/guides/flutter-form-validation)
- **Make a field optional or nullable** — [Optional vs nullable](/core-concepts/schemas#optional-vs-nullable)
- **Parse dates, URIs, and durations** — [Codecs](/core-concepts/codecs)
- **Add custom validation logic** — [Custom Validation](/guides/custom-validation)
- **Generate models or schemas** — [Model Code Generation](/core-concepts/typesafe-schemas)
- **Use Ack with MCP, Firebase AI (Gemini), or JSON Schema Builder** — [Ecosystem Integrations](/guides/ecosystem-integrations)
- **Upgrade from Ack 1.x or see what changed** — [What's New & Migration Guide](/getting-started/migration-guide)
- **Reuse and compose schemas** — [Common Recipes](/guides/common-recipes)

## Install

```bash
dart pub add ack:^2.0.0-beta.3
```

New here? The [Quickstart Tutorial](/getting-started/quickstart-tutorial) takes you from install to handling every validation outcome in a few minutes.

## Learn more

- [Schema Types](/core-concepts/schemas) — every schema type and how to compose them
- [Validation Rules](/core-concepts/validation) — built-in constraints
- [Error Handling](/core-concepts/error-handling) — read and display structured errors
- [JSON Serialization](/core-concepts/json-serialization) — validate and encode JSON
- [What's New & Migration Guide](/getting-started/migration-guide) — what exists, what changed & why, and 1.x $\rightarrow$ 2.0 substitutions
- [API Reference](/api-reference/) — a core API quick reference with a link to generated API docs

*Building with an AI agent? Start at [`llms.txt`](https://docs.page/btwld/ack/llms.txt) for a compact, machine-readable index.*
```

### API Reference

Source: https://docs.page/btwld/ack/api-reference

```mdx

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<String, AckSchema> properties)`: Creates an `ObjectSchema` for validating objects.
- `Ack.enumValues(List<T> values)`: Creates an `EnumSchema<T>` 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<String> values)`: Creates a `StringSchema` constrained
  to the given values. For ad-hoc string lists without a backing Dart enum.
- `Ack.anyOf(List<AckSchema> 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<Uri, Object>
  documents = const {}, bool assertFormats = false})`: 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`); 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<T extends Object>()`: 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<T extends Object>(...)`: 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<Boundary, Runtime>` (Base Class)

Base class for all schema types.

### Primary Validation Methods

- `SchemaResult<Runtime> 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<TOut> safeParseAs<TOut extends Object>(Object? data, TOut Function(Runtime?) map, {String? debugName})`: Parses and maps the validated value to `TOut`. Mapper `Exception`s become `SchemaTransformError` failures; mapper `Error` values are rethrown with their original stack trace.
- `TOut parseAs<TOut extends Object>(Object? data, TOut Function(Runtime?) map, {String? debugName})`: Throwing variant of `safeParseAs`.
- `SchemaResult<Boundary> safeEncode(Runtime? value, {String? debugName})`: Encodes a runtime value to the boundary representation.
- `Boundary? encode(Runtime? value, {String? debugName})`: Throwing variant of `safeEncode`.

### Schema Modification Methods

- `AckSchema<Boundary, Runtime> nullable({bool value = true})`: Returns a new schema that also accepts `null`.
- `AckSchema<Boundary, Runtime> optional({bool value = true})`: Returns a new schema marked as optional (for object fields).
- `AckSchema<Boundary, Runtime> describe(String description)`: Attaches a description for documentation and JSON Schema generation.
- `DefaultSchema<Boundary, Runtime> 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<Boundary, Runtime> constrain(Constraint<Runtime> constraint, {String? message})`: Adds a constraint and optionally overrides its message. The constraint must mix in `Validator<Runtime>`, or an `ArgumentError` is thrown.
- `AckSchema<Boundary, Runtime> withConstraint(Constraint<Runtime> constraint)`: Adds a constraint directly (no message override; `constrain` delegates here).
- `AckSchema<Boundary, Runtime> 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<Boundary, R> transform<R>(R Function(Runtime) transformer)`: Transforms validated runtime values to `R` (parse-only; encode fails).

### Utility Methods

- `Map<String, Object?> 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<String, Object?> 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 pattern, {String? example, String? message})`: Must contain the pattern anywhere in the string.
- `startsWith(String value)`: Must start with `value`.
- `endsWith(String value)`: Must end with `value`.

### Format Validation

- `email()`: Must be valid email format
- `url()`: Must be valid URL format (alias for `uri()`)
- `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)

## `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.

## `ListSchema<T>`

Schema for validating arrays. See [List Validation](../core-concepts/validation.mdx#list-constraints).

- `minItems(int min)`: Minimum number of items (alias: `minLength`)
- `maxItems(int max)`: Maximum number of items (alias: `maxLength`)
- `exactLength(int exact)`: Exact number of items (alias: `length`)
- `nonEmpty()`: List must have at least one item (alias: `notEmpty`)
- `unique()`: All items must be unique

## `ObjectSchema`

Schema for validating objects (maps). See [Object Validation](../core-concepts/schemas.mdx#object).

- Constructed using `Ack.object(Map<String, AckSchema> properties, {bool additionalProperties = false})`.
- Use `.pick(List<String> keys)` to create schema with only specified properties.
- Use `.omit(List<String> keys)` to create schema excluding specified properties.
- Use `.extend(Map<String, AckSchema> 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.

## `deepUnmodifiableJsonMap(JsonMap value)`

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<T>`

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<R> map<R>(R Function(T?) transform)`: Maps the successful value to a new result type; propagates failures unchanged.
- `R match<R>({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:**
- `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<T>`

Base class for custom validation rules. See [Custom validation](../guides/custom-validation.mdx).

- `String constraintKey`: Unique identifier for the constraint.
- `String description`: Human-readable description.
- `Map<String, Object?> toMap()`: Serializes the constraint for debugging.

## `Validator<T>` (mixin)

Validation behavior mixin used with `Constraint<T>`.

- `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<Boundary, Runtime>(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 '<file>.g.dart';` directive, run:

```bash
dart run build_runner build
```

### `@Schemable()` on a top-level schema

**Target**: Schema variables and getters

**Generates**: An immutable model class backed by the existing schema

Annotate a top-level schema variable or getter. The schema stays in your source file and remains responsible for validation and codecs.

**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(...)`

**Unsupported:** nullable roots, one-way transforms, `Ack.any()` and
`Ack.map()` roots, `Ack.anyOf()`, bare `Ack.instance<T>()`, and anonymous
inline objects

`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).

**Example:**
```dart
import 'package:ack/ack.dart';

part 'user.g.dart';

@Schemable()
final userSchema = Ack.object({
  'name': Ack.string(),
  'email': Ack.string().email(),
});

// Generated:
// - final class User { ... }
// - The schema variable remains unchanged

// 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());
```

### `@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 `<ClassName>Schema` facade backed by a private typed
codec (`_<className>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<T>`, 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<T>`, 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: `@IsUrl`, `@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<A>(...)` on the type;
3. a unique top-level `AckSchema<Boundary, T>` 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.<policy>` (`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
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());
```

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<T>`

Schema for mapping enum `.name` strings at the boundary to typed enum values at
runtime. Created using `Ack.enumValues(List<T> 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<AckSchema> schemas)`.

### `DiscriminatedObjectSchema`

Schema for polymorphic validation based on a discriminator field.

- Created using `Ack.discriminated<T extends Object>(...)` 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<ValueBoundary, ValueRuntime>`

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<String, ValueBoundary?>` and
  `Map<String, ValueRuntime?>`. 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": <value schema>}`.

### `CodecSchema<Boundary, Runtime>`

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>(R Function(Runtime) transformer)`: one-way transform
  (parse only; `encode` fails with a one-way error).
- `schema.codec<R>({required R Function(Runtime) decode, required Runtime Function(R) encode, AckSchema<dynamic, R>? output})`:
  bidirectional codec; the optional `output` schema validates the runtime value.
- `Ack.codec<Boundary, InputRuntime, Runtime>({required input, required decode, required encode, output})`:
  builds a codec from an `input` schema.

**Built-in codecs:**

- `Ack.date()` → `CodecSchema<String, DateTime>` (ISO `YYYY-MM-DD` ↔ local-midnight `DateTime`)
- `Ack.datetime()` → `CodecSchema<String, DateTime>` (ISO 8601 ↔ UTC
  `DateTime`; leap-second strings are rejected because Dart cannot represent
  them)
- `Ack.uri()` → `CodecSchema<String, Uri>` (absolute URI string ↔ `Uri`)
- `Ack.duration()` → `CodecSchema<int, Duration>` (milliseconds ↔ `Duration`)

### Optional schemas and `JsonMaybe<T>`

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<T>` (`JsonAbsent<T>`, `JsonValue<T>`) when you need to distinguish an omitted JSON property from an explicit `null` on both `parse` and `toJson`:

- `const JsonMaybe<T>.absent()` (`JsonAbsent<T>`) — key omitted from JSON.
- `const JsonMaybe<T>.value(T? value)` (`JsonValue<T>`) — key present in JSON (with non-null or `null` value).
- `const JsonMaybe<T>.nullValue()` — shorthand for `JsonValue<T>(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 `<name>.schema.dart` (with `part '<name>.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
  AckJsonSchemaLibrary generateAckSchemaLibrary({
    required Object? document,
    required Uri documentUri,
    required String partStem,
    AckJsonSchemaLibraryOptions options = const AckJsonSchemaLibraryOptions(),
    Map<Uri, Object> 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.*
```

### Codecs

Source: https://docs.page/btwld/ack/core-concepts/codecs

```mdx

Your API sends a timestamp as an ISO string, but your code wants a `DateTime`. A codec handles that round-trip: it validates the incoming string, decodes it into the Dart type you actually use, and encodes it back when you send data out.

```dart
final when = Ack.datetime(); // CodecSchema<String, DateTime>

final dt = when.parse('2026-01-01T00:00:00Z'); // decode: String -> DateTime
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<R>(fn)` | one-way (parse only) | `CodecSchema<Boundary, R>` |
| `schema.codec<R>(decode: ..., encode: ...)` | bidirectional | `CodecSchema<Boundary, R>` |

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:

| Factory | Boundary ↔ Runtime | Runtime invariant |
| --- | --- | --- |
| `Ack.date()` | ISO `YYYY-MM-DD` `String` ↔ `DateTime` | local midnight (no time-of-day) |
| `Ack.datetime()` | ISO 8601 `String` ↔ `DateTime` | must be UTC; leap-second strings are rejected |
| `Ack.uri()` | `String` ↔ `Uri` | absolute URI (scheme + host) |
| `Ack.duration()` | milliseconds `int` ↔ `Duration` | whole milliseconds |

```dart
final schema = Ack.object({
  'startsAt': Ack.datetime(),
  'website': Ack.uri(),
  'timeout': Ack.duration(),
});

final event = schema.parse({
  'startsAt': '2026-01-01T09:00:00Z',
  'website': 'https://example.com',
  'timeout': 5000,
});

// event['startsAt'] is a DateTime (UTC)
// event['website']  is a Uri
// 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
preserved.

## Custom codecs

Create a codec from any input schema with `Ack.codec(...)`, providing a `decode` function (boundary → runtime) and an `encode` function (runtime → boundary):

```dart
final csv = Ack.codec<String, String, List<String>>(
  input: Ack.string(),
  decode: (s) => s.split(','),
  encode: (list) => list.join(','),
);

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).

Call `.codec<R>(...)` on an existing schema to add a reversible conversion:

```dart
final trimmed = Ack.string().codec<String>(
  decode: (s) => s.trim(),
  encode: (s) => s,
);
```

## Encoding back to the boundary

Use `encode` (throws on failure) or `safeEncode` (returns a `SchemaResult`):

```dart
final result = Ack.datetime().safeEncode(DateTime.utc(2026));
if (result.isOk) {
  print(result.getOrThrow()); // 2026-01-01T00:00:00.000Z
}
```

Errors surface as typed [`SchemaError`](./error-handling.mdx) values:

- `SchemaTransformError` — a `decode` function threw during parsing.
- `SchemaEncodeError` — encoding failed (for example, a one-way `transform`, or a
  runtime invariant violation such as a non-UTC `DateTime` for `Ack.datetime()`).

An `Error` thrown by a `decode` (or `transform`) or `encode` function is a
programming bug, not bad data, so it propagates out of `parse` / `safeParse` and
`encode` / `safeEncode` with its original stack trace at every nesting level —
inside an object, list, map, or union, too. Throw an `Exception` (or express the
rule with an `input:` or `output:` schema) to signal a value the codec cannot
decode or encode.

## Codecs and JSON Schema

A codec exports the JSON Schema of its **boundary** (input) schema — that is the shape that crosses the wire. For example, `Ack.datetime()` exports as `string` with `format: date-time`. The runtime type and decode/encode logic are not part of the exported schema. See [JSON Serialization](./json-serialization.mdx).

Constraints added to a codec validate its **runtime** values, which the encoder
may map to something else entirely, so they are enforced locally but not
published: the export omits the keyword and `toSchemaModel().warnings` reports a
`codec_runtime_constraint_not_exported` warning. Put rules the wire should
advertise on the input schema instead — `Ack.string().minLength(5).codec(...)`
exports `minLength: 5`, while `Ack.string().codec(...).minLength(5)` does not.
`Ack.duration()` is the exception: its boundary is the milliseconds its `min()`
and `max()` already compare, so those constraints do export.

## Next steps

- **[Schema Types](./schemas.mdx)**: Schema types and the `transform` helper
- **[Validation Rules](./validation.mdx)**: Built-in constraints
- **[Error Handling](./error-handling.mdx)**: `SchemaError` and `SchemaResult`
- **[JSON Serialization](./json-serialization.mdx)**: Exporting schemas
```

### Configuration

Source: https://docs.page/btwld/ack/core-concepts/configuration

```mdx

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
Ack.object({
  'id': Ack.integer(),
  'nickname': Ack.string().optional(),
  'middleName': Ack.string().nullable(),
  'avatarUrl': Ack.string().url().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
// 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. The default must satisfy the schema's runtime type and
constraints, and it 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
final settingsSchema = Ack.object({
  'theme': Ack.enumString(['light', 'dark']).withDefault('light'),
  'pageSize': Ack.integer().min(1).max(100).withDefault(20),
});
```

```dart
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.

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
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
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
```

### Error Handling

Source: https://docs.page/btwld/ack/core-concepts/error-handling

```mdx

When validation fails, you want to know what went wrong and where. `safeParse()` hands back a `SchemaResult` holding either the validated value or a `SchemaError`, so you can inspect failures without try/catch.

## The `SchemaResult` object

`safeParse()` returns a `SchemaResult<T>`. 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.

```dart
import 'package:ack/ack.dart';

final schema = Ack.string().minLength(5);
final result = schema.safeParse('abc');

if (result.isFail) {
  final error = result.getError();
  print('Validation failed: $error');

  // Try to get data (will throw)
  try {
    result.getOrThrow();
  } catch (e) {
    print('Caught exception: $e');
  }

  // Get a default value
  final dataOrDefault = result.getOrElse(() => 'default_string');
  print('Data or default: $dataOrDefault'); // Output: default_string
}
```

## Understanding `SchemaError`

`SchemaError` contains details about the validation failure.

- `error.name`: The context name at the failure point (for example, a field name or the `debugName` passed to `safeParse`).
- `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`).

```dart
final userSchema = Ack.object({
  'name': Ack.string(),
  'age': Ack.integer().min(18),
  'address': Ack.object({
    'city': Ack.string()
  })
});

final invalidData = {
  'name': 'Test',
  'age': 15, // Fails min(18)
  'address': {
    'city': 123 // Fails Ack.string
  }
};

final result = userSchema.safeParse(invalidData);

if (result.isFail) {
  final error = result.getError();
  print('Error Name: ${error.name}');         // Example: 'address'
  print('Error Path: ${error.path}');         // Example: '#/address/city'
  print('Failed Value: ${error.value}');      // Example: the invalid data
  print('Full Error: $error');               // Complete error details

  // 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.
}
```

## Error types

Each `SchemaError` subtype carries specific information about why validation failed.

### `TypeMismatchError`

Raised when the input type doesn't match the expected schema type.

```dart
final schema = Ack.string();
final result = schema.safeParse(42); // Number instead of string

if (result.isFail) {
  final error = result.getError() as TypeMismatchError;
  print('Expected: ${error.expectedType}'); // "string"
  print('Actual: ${error.actualType}');     // "integer"
  print('Error: ${error.message}');          // "Expected string, got integer"
}
```

### `SchemaConstraintsError`

Raised when the value violates one or more validation constraints (such as `minLength`, `min`, or `email`).

```dart
final schema = Ack.string().minLength(5).email();
final result = schema.safeParse('abc');

if (result.isFail) {
  final error = result.getError() as SchemaConstraintsError;
  print('Constraint violations: ${error.constraints.length}');

  // Access individual failed constraints
  for (final constraintError in error.constraints) {
    print('- Constraint: ${constraintError.constraint}');
    print('- Message: ${constraintError.message}');
  }
}
```

### `SchemaNestedError`

Raised when validation fails within nested objects or lists. Contains a list of child errors.

```dart
final schema = Ack.object({
  'name': Ack.string().minLength(2),
  'age': Ack.integer().min(0),
});

final result = schema.safeParse({
  'name': 'J',    // Too short
  'age': -5,      // Negative
});

if (result.isFail) {
  final error = result.getError() as SchemaNestedError;
  print('Nested errors: ${error.errors.length}');

  // Recursively inspect nested errors
  for (final nestedError in error.errors) {
    print('- Field: ${nestedError.name}');
    print('- Error: ${nestedError.message}');
  }
}
```

### `SchemaValidationError`

Raised when custom validation logic added via `.refine()` fails.

```dart
final schema = Ack.integer().refine(
  (value) => value % 2 == 0,
  message: 'Must be an even number',
);

final result = schema.safeParse(3);

if (result.isFail) {
  final error = result.getError() as SchemaValidationError;
  print('Validation error: ${error.message}'); // "Must be an even number"
}
```

### `SchemaTransformError`

Raised when a `.transform()` callback throws an exception.

Callbacks receive the non-null validated runtime value; null handling belongs to the surrounding `nullable`/`withDefault` configuration. `SchemaTransformError` fires when the callback itself throws — for example, when the input passes validation but the conversion fails:

```dart
final schema = Ack.string().transform((value) {
  final parsed = int.tryParse(value);
  if (parsed == null) throw FormatException('Not numeric: $value');
  return parsed;
});

final result = schema.safeParse('not-a-number');

if (result.isFail) {
  final error = result.getError() as SchemaTransformError;
  print('Transform error: ${error.message}');
  print('Cause: ${error.cause}'); // Original exception
}
```

### `SchemaEncodeError`

Raised when `encode()` or `safeEncode()` can't turn a runtime value back into its boundary form — for example, encoding a one-way `transform`, or a value that breaks a codec's invariant (such as a non-UTC `DateTime` for `Ack.datetime()`). Its `kind` field says which case occurred.

### Working with error types

`SchemaError` (and `AckSchema`) is a `sealed class`, so you can use exhaustive pattern matching without a wildcard branch:

```dart
final result = schema.safeParse(data);

if (result.isFail) {
  final error = result.getError();

  switch (error) {
    case TypeMismatchError():
      print('Wrong type: expected ${error.expectedType}');
    case SchemaConstraintsError():
      print('Failed ${error.constraints.length} constraints');
    case SchemaNestedError():
      print('Nested validation failed at ${error.errors.length} locations');
    case SchemaValidationError():
      print('Custom or JSON Schema validation failed: ${error.message}');
    case SchemaTransformError():
      print('Transformation failed: ${error.cause}');
    case SchemaEncodeError():
      print('Could not encode value: ${error.message}');
  }
}
```

## Displaying errors in UI (Flutter example)

In a `TextFormField` validator, return the error string directly:

```dart
// Inside TextFormField validator
validator: (value) {
  final result = someSchema.safeParse(value);
  if (result.isFail) {
    return result.getError().toString();
  }
  return null;
}
```

*See the [Form Validation Guide](../guides/flutter-form-validation.mdx) for details.*

## 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
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_
}
```

## Next steps

- **[Custom Validation](/guides/custom-validation)**: Create constraints with custom error messages
- **[Flutter Forms](/guides/flutter-form-validation)**: Display validation errors in Flutter form widgets
- **[Validation Rules](/core-concepts/validation)**: All built-in validation constraints
- **[Schema Types](/core-concepts/schemas)**: Schema types and their behavior
- **[Common Recipes](/guides/common-recipes)**: Practical error handling patterns
```

### JSON Serialization

Source: https://docs.page/btwld/ack/core-concepts/json-serialization

```mdx

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.

## 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<String, dynamic>` or `List`).
2.  **Validate:** Pass the decoded object to your [Ack schema](./schemas.mdx)'s `safeParse()` method.

```dart
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),
  'email': Ack.string().email().nullable(),
});

void processApiResponse(String jsonString) {
  // 1. Decode JSON string into a Dart object.
  // jsonDecode returns an unknown structure until the schema validates it.
  Object? jsonData;
  try {
    jsonData = jsonDecode(jsonString);
  } 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).
  } else {
    // Handle validation errors (see the Error Handling guide).
    print('Invalid JSON data: ${result.getError()}');
  }
}

// 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<String, Object?>` 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
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<String, dynamic>.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
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?
}
```

## 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`:

```dart
final result = userSchema.safeParse({
  'name': 'Alice',
  'age': 30,
  'email': 'alice@example.com',
});

if (result.isOk) {
  final validData = result.getOrThrow()!;
  final jsonString = jsonEncode(validData);
  print(jsonString);
}
```

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
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<String, Object?>`.
- **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.
```

### Schemas

Source: https://docs.page/btwld/ack/core-concepts/schemas

```mdx

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.

```dart
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()}');
}
```

## Schema types

### String

```dart
// Basic string — primitives are strict by default and reject non-string values
final nameSchema = Ack.string();

// With constraints
final usernameSchema = Ack.string()
  .minLength(3)
  .maxLength(20)
  .matches(r'^[a-zA-Z0-9_]+$');

// Email validation
final emailSchema = Ack.string().email();

// URL validation
final websiteSchema = Ack.string().url();

// Date/datetime strings
final dateSchema = Ack.string().date(); // YYYY-MM-DD
final datetimeSchema = Ack.string().datetime(); // ISO 8601

// Enum values
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`.

### Number

Numeric schemas follow JSON Schema value semantics so native and web builds
agree. `Ack.integer()` accepts finite numbers with no fractional part and
losslessly normalizes them to `int`. `Ack.double()` accepts finite numbers that
can be represented exactly as `double` and normalizes them to `double`.
`Ack.number()` accepts either representation and preserves it. Add `.safe()` to
an integer schema when values must remain exact in JavaScript's portable integer
range. All numeric schemas reject `NaN` and infinities.

```dart
// Integer validation (42 and 42.0 both parse to int)
final ageSchema = Ack.integer()
  .min(0)
  .max(120);

// Double validation (42 and 42.0 both parse to double when lossless)
final priceSchema = Ack.double()
  .positive()
  .multipleOf(0.5); // Use factors that avoid floating point rounding issues

// Preserve an input that is already int or double
final amountSchema = Ack.number().positive();

final temperatureSchema = Ack.integer(); // Any integer
final scoreSchema = Ack.double().positive(); // > 0
final debtSchema = Ack.double().negative(); // < 0
```

### Boolean

```dart
final isActiveSchema = Ack.boolean();
```

### List

```dart
// List of strings
final tagsSchema = Ack.list(Ack.string());

// With constraints
final itemsSchema = Ack.list(Ack.string())
  .minLength(1)
  .maxLength(10)
  .unique();

// List of objects
final usersSchema = Ack.list(Ack.object({
  'id': Ack.integer(),
  'name': Ack.string(),
}));
```

### Object

The most common schema type for structured data:

```dart
final userSchema = Ack.object({
  'name': Ack.string(),
  'age': Ack.integer().min(0),
  'email': Ack.string().email(),
});
```

**Nested objects:**

```dart
final userSchema = Ack.object({
  'name': Ack.string(),
  'address': Ack.object({
    'street': Ack.string(),
    'city': Ack.string(),
    'zipCode': Ack.string().matches(r'^\d{5}$'),
  }),
});
```

**Working with validated data:**

```dart
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<String, Object?>;
  final city = address['city'] as String;
}
```

### Union types

Validate against multiple possible schemas:

```dart
// String or integer — primitive branches are strict, so the union won't
// silently coerce one into the other.
final idSchema = Ack.anyOf([
  Ack.string(),
  Ack.integer(),
]);

// Discriminated union (polymorphic data)
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(),
    }),
  },
);
```

The union owns the discriminator and injects the exact branch literal at
parse/export boundaries. Branch schemas usually omit the discriminator field.

### Recursive schemas

Use `Ack.lazy(...)` when a schema needs to refer to itself:

```dart
late final ObjectSchema categorySchema;

categorySchema = Ack.object({
  'name': Ack.string(),
  'children': Ack.list(
    Ack.lazy<JsonMap, JsonMap>('Category', () => categorySchema),
  ),
});
```

The lazy builder is resolved once and memoized. JSON Schema export renders the
reference through Draft-7 `definitions` / `$ref`, so recursive children are
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.

### Any

Accepts any non-null JSON-safe value without validation (use sparingly):

```dart
final flexibleSchema = Ack.object({
  'id': Ack.string(),
  'metadata': Ack.any(), // Any non-null JSON-safe value accepted
});
```

Use `Ack.any().nullable()` to also accept `null`.

### Maps

Use `Ack.map(...)` for a JSON object with arbitrary string keys whose values
all share one schema:

```dart
final settingsSchema = Ack.object({
  'scores': Ack.map(Ack.integer().min(0)), // string keys, int values
  'metadata': Ack.map(Ack.any().nullable()), // a JsonMap
});
```

Map values may be `null` only when the value schema is nullable. Use
`Ack.object(...)` when the object has declared properties.

## Optional vs nullable

**`.nullable()`** — Field must be present but can be `null`:

```dart
final userSchema = Ack.object({
  'name': Ack.string(),
  'middleName': Ack.string().nullable(),
});

// ✅ Valid
{'name': 'John', 'middleName': null}
{'name': 'John', 'middleName': 'Robert'}

// ❌ Invalid - middleName missing
{'name': 'John'}
```

**`.optional()`** — Field can be omitted (but is still validated when present):

```dart
final userSchema = Ack.object({
  'name': Ack.string(),
  'age': Ack.integer().optional(),
});

// ✅ Valid
{'name': 'John'} // age omitted
{'name': 'John', 'age': 30}

// ❌ Invalid
{'name': 'John', 'age': null} // Use .nullable() if null should be allowed
```

**Combining both** — Field can be missing or `null`:

```dart
final userSchema = Ack.object({
  'name': Ack.string(),
  'bio': Ack.string().optional().nullable(),
});

// All valid:
{'name': 'John'}
{'name': 'John', 'bio': null}
{'name': 'John', 'bio': 'Developer'}
```

**`.withDefault(value)`** — A missing field parses as `value`. A present `null`
still fails unless the field is nullable:

```dart
final userSchema = Ack.object({
  'role': Ack.string().withDefault('member'),
  'theme': Ack.string().nullable().withDefault('light'),
});

userSchema.parse({});              // {'role': 'member', 'theme': 'light'}
userSchema.parse({'theme': null}); // {'role': 'member', 'theme': 'light'}
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.

> **Distinguishing omitted vs. `null` in generated models (`JsonMaybe<T>`):** 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<String>` (`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).

## Object schema operations

### Extension

Add or override properties:

```dart
final baseSchema = Ack.object({
  'id': Ack.string(),
  'name': Ack.string(),
});

// Add properties
final extendedSchema = baseSchema.extend({
  'email': Ack.string().email(),
  'role': Ack.literal('admin'),
});

// Override properties
final modifiedSchema = baseSchema.extend({
  'name': Ack.string().optional(), // Make name optional
});
```

### Pick and omit

Select or exclude properties:

```dart
final fullSchema = Ack.object({
  'id': Ack.string(),
  'name': Ack.string(),
  'email': Ack.string().email(),
  'password': Ack.string(),
  'createdAt': Ack.string().datetime(),
});

// Pick specific fields
final publicSchema = fullSchema.pick(['id', 'name', 'email']);

// Omit sensitive fields
final safeSchema = fullSchema.omit(['password']);
```

### Partial

Make all properties optional:

```dart
final userSchema = Ack.object({
  'name': Ack.string(),
  'email': Ack.string().email(),
  'age': Ack.integer(),
});

// All fields become optional
final partialSchema = userSchema.partial();

// All valid:
partialSchema.safeParse({});
partialSchema.safeParse({'name': 'John'});
partialSchema.safeParse({'email': 'john@example.com', 'age': 30});
```

### Additional properties

By default, objects are **strict** and reject additional properties.

#### Using the constructor parameter

```dart
// Strict mode (default) - rejects additional properties
final strictSchema = Ack.object({
  'id': Ack.string(),
  'name': Ack.string(),
}); // additionalProperties: false is the default

strictSchema.safeParse({'id': '1', 'name': 'John', 'extra': 'value'}); // ❌ Fails

// Passthrough mode - allows additional properties
final flexibleSchema = Ack.object({
  'id': Ack.string(),
  'name': Ack.string(),
}, additionalProperties: true);

flexibleSchema.safeParse({'id': '1', 'name': 'John', 'extra': 'allowed'}); // ✅ Passes
```

#### Using extension methods

```dart
final baseSchema = Ack.object({
  'id': Ack.string(),
  'name': Ack.string(),
});

// Make strict (reject extra properties)
final strict = baseSchema.strict();
strict.safeParse({'id': '1', 'name': 'John', 'role': 'admin'}); // ❌ Fails

// Allow passthrough (accept extra properties)
final passthrough = baseSchema.passthrough();
passthrough.safeParse({'id': '1', 'name': 'John', 'role': 'admin'}); // ✅ Passes
```

**Common use cases:**

- **Strict mode**: API request validation and form validation where only known fields are allowed
- **Passthrough mode**: Dynamic data or cases where extra metadata is acceptable

## Custom validation

### Refinements

Add custom validation logic:

```dart
// 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<double>(0, (sum, item) {
      final itemMap = item as Map<String, Object?>;
      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
// 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<DateTime>((s) => DateTime.parse(s));
```

## 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.

## 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
```

### Model Code Generation

Source: https://docs.page/btwld/ack/core-concepts/typesafe-schemas

```mdx

Ack supports code generation in three workflows: start from an Ack schema, start
from a Dart class, or start from a `.schema.json` document.

| Starting point | Trigger | Generated output |
| --- | --- | --- |
| A top-level Ack schema (`final userSchema = ...`) | `@Schemable()` | Immutable `User` class, `User.schema`, `parse`/`safeParse`, `fromJson`/`toJson`, `copyWith` in `<file>.g.dart` |
| A Dart class or sealed union (`final class Account`) | `@Schemable()` | `_accountSchema` codec, `AccountSchema` facade, and `_$AccountAck` mixin in `<file>.g.dart` |
| A JSON Schema asset (`lib/**/*.schema.json`) | `ack_generator:ack_json_schema` in `build.yaml` | `<name>.schema.dart` + `<name>.schema.g.dart` with typed `@Schemable()` models or validated value models |

`@Schemable()`, `@AckKey`, and the `Is…`/`Has…` rule annotations (such as
`@IsRequired()` and `@HasMinLength(2)`) all come from `package:ack/ack.dart`
(and `package:ack/annotations.dart`).
There is no `@AckSchema()` annotation; `AckSchema<Boundary, Runtime>` is the
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.

## Install the generator

```bash
dart pub add ack:^2.0.0-beta.3 dev:ack_generator:^2.0.0-beta.3 dev:build_runner
```

Every annotated library needs the generated part:

```dart
part 'models.g.dart';
```

Run the generator after adding or changing a model:

```bash
dart run build_runner build
```

## A working example of both directions

This file contains one schema-first model and one class-first model. Both use
the same builder and generated part.

```dart title="lib/models.dart"
import 'package:ack/ack.dart';

part 'models.g.dart';

// Schema-first: write the schema; Ack generates Order.
@Schemable()
final orderSchema = Ack.object({
  'id': Ack.string(),
  'total': Ack.double().positive(),
});

// Class-first: write Account; Ack generates AccountSchema.
@Schemable(caseStyle: AckCaseStyle.snake)
final class const Account({
  @HasMinLength(2) required final String displayName,
  @IsEmail() required final String email,
  required final String? middleName,
  final Uri? website,
  final String role = 'member',
}) with _$AccountAck {
  static final schema = AccountSchema.schema;
  static final fromJson = AccountSchema.fromJson;
}
```

After generation, both directions have a typed parsing and JSON boundary:

```dart
final order = Order.parse({'id': 'o1', 'total': 12.5});
print(order.total); // double

final account = Account.fromJson({
  'display_name': 'Ada',
  'email': 'ada@example.com',
  'middle_name': null,
});
print(account.role);     // member
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.

## Schema-first: `@Schemable()` on a top-level schema

Use schema-first generation when the wire contract is the primary artifact.
The source schema owns validation, defaults, codecs, and JSON Schema export;
Ack generates the stored Dart type around it.

```dart
@Schemable()
final userSchema = Ack.object({
  'id': Ack.string().uuid(),
  'email': Ack.string().email().nullable(),
  'tags': Ack.list(Ack.string()).optional(),
});
```

`userSchema` generates `User`: a trailing `Schema` is removed and no suffix is
added. Use `@Schemable(name: 'AppUser')` when you need an exact class name.

Generated models provide:

- an unchecked constructor with stored typed fields;
- `User.parse` and `User.safeParse` for validated input;
- `User.fromJson`, `toJson`, and `safeToJson` for the JSON boundary;
- generated `copyWith`, deep collection-aware `==`/`hashCode`, and `toString`;
- `User.schema`, the model-valued schema for composition such as
  `Ack.list(User.schema)`; it is a shorthand for `User.$ack.modelSchema` and
  is omitted when the model has a field or discriminator named `schema`, the
  annotated declaration is named `schema`, or the library imports a prefix
  named `schema`;
- a public `User.$ack` adapter used by nested generated models.

The generator supports object and value roots, literals, enums, lists, sets,
string-keyed maps, built-in and custom bidirectional codecs, named nested
models, aliases, defaults, additional properties, named lazy recursion, and
same-library discriminated unions. Stored collections are copied recursively
into unmodifiable collections.

Fields may use `Ack.any()` for JSON-safe `Object` values and `Ack.map(...)` for
string-keyed `Map<String, T>` values. `Ack.any().nullable()` infers `Object?`,
and `Ack.map(Ack.any().nullable())` infers `Map<String, Object?>`.

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<T>()`, anonymous inline object fields,
unresolved dynamic schema factories, and cross-library union branches.

### Schema-first unions

Each branch must be a named `@Schemable()` object schema in the same library:

```dart
@Schemable()
final catSchema = Ack.object({'lives': Ack.integer()});

@Schemable()
final dogSchema = Ack.object({'breed': Ack.string()});

@Schemable()
final petSchema = Ack.discriminated(
  discriminatorKey: 'type',
  schemas: {'cat': catSchema, 'dog': dogSchema},
);
```

This generates a sealed `Pet` base plus `Cat` and `Dog` branches.

## Class-first: `@Schemable()` on a class

Use class-first generation when the Dart class is the primary artifact. Ack
reads the fields that the class's constructor declares and generates a codec
schema whose runtime value is your class. The examples use Dart 3.13 primary
constructors, so each declaring parameter carries its own annotations:

```dart
@Schemable(caseStyle: AckCaseStyle.snake)
final class Profile({
  @HasMinLength(2) required final String displayName,
  @IsEmail() required final String email,
  final String role = 'member',
}) with _$ProfileAck {
  static final schema = ProfileSchema.schema;
  static final fromJson = ProfileSchema.fromJson;
}
```

Ack generates a public `ProfileSchema` facade backed by a library-private codec
variable:

- `ProfileSchema.parse` and `safeParse` validate input;
- `ProfileSchema.fromJson` is the one-argument map convenience;
- `ProfileSchema.encode` and `safeEncode` validate while encoding;
- `ProfileSchema.toJsonSchema()` exports the boundary JSON Schema;
- `ProfileSchema.toSchemaModel()` exports Ack's canonical schema model;
- `ProfileSchema.schema` is the typed model codec used for composition;
- `ProfileSchema.wireSchema` validates like `schema` and returns the JSON map
  instead of the model.

Every instantiable `@Schemable` class and implicit sealed-union branch must
be declared `final class`, initialize its fields through an unnamed generative
or primary constructor, contain only final stored fields, and apply its
generated `_$ClassAck` mixin. The mixin supplies `toJson()`, `safeToJson()`, a
typed `copyWith` where omission keeps the current value, explicit `null`
clears a nullable field, and a wrongly typed argument is a compile-time error,
and deep collection-aware `==`, `hashCode`, and
`toString`. A sealed abstract base receives union serialization only.

Values created by `ProfileSchema.parse` or `Profile.fromJson` receive recursive
unmodifiable copies of list, set, map, and captured-extra values. Ack cannot
rewrite a hand-written constructor, so direct construction and collection
replacements passed to `copyWith` must defensively copy mutable inputs in the
source class when that guarantee is required.

Generated `toJson()` and `safeToJson()` methods delegate through that same
facade. Ack cannot inject static members or constructors into a hand-written
class, so the recommended conventions are one-line static tear-offs/fields:

```dart
static final schema = ProfileSchema.schema;
static final fromJson = ProfileSchema.fromJson;
```

`static final schema = ProfileSchema.schema;` attaches the generated codec
directly to `Profile.schema` so callers can write
`Profile.schema.parse(...)`, `Profile.schema.toJsonSchema()`, or
`Ack.list(Profile.schema)`, and other libraries only need to import `Profile`.
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:

```dart
factory Profile.fromJson(Map<String, dynamic> json) =>
    ProfileSchema.fromJson(json);
```

An explicit function-field type is also valid but normally unnecessary:

```dart
static final Profile Function(Map<String, dynamic>) 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
exported. Untagged prose does not become schema data. Explicit annotation text
on `@Schemable(description: ...)` takes precedence over a class doc tag. Blank
or duplicate tags fail generation. `@description` is an Ack convention, not a
Dart annotation.

A class description applies to its object schema and model codec. This includes
sealed union bases and branches. A field description applies at its property.
It does not change a nested model's own description.

```dart
/// Tracks one unit of work. This prose is not exported.
@Schemable(description: 'A task the person can complete.')
final class const Task({
  required final String id,

  /// @description What to do.
  required final String title,
}) with _$TaskAck;

TaskSchema.toJsonSchema()['description']; // 'A task the person can complete.'
```

Use `@Schemable(schemaName: 'WireProfileSchema')` to override the exact public
facade name. It must be a public UpperCamel identifier. The private backing
name remains derived from the model class, and no public lower-camel alias is
generated.

### Classic constructors

A classic constructor works the same and generates identical code. Put the
annotations on the fields it initializes:

```dart
@Schemable(caseStyle: AckCaseStyle.snake)
final class Profile with _$ProfileAck {
  Profile({
    required this.displayName,
    required this.email,
    this.role = 'member',
  });

  @HasMinLength(2)
  final String displayName;

  @IsEmail()
  final String email;

  final String role;

  static final schema = ProfileSchema.schema;
  static final fromJson = ProfileSchema.fromJson;
}
```

### Presence comes from the constructor

| Declaration | Generated field schema | Input behavior | Encoding behavior |
| --- | --- | --- | --- |
| `required T` | `<schema>` | Required, non-null | Always present |
| `required T?` | `<schema>.nullable()` | Required, may be null | Present even when null |
| Optional `T?` | `<schema>.optional().nullable()` | May be omitted | Omitted when null |
| Constructor default, such as `this.tools = const []` | `<schema>.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.

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
field default: required fields and optional fields export no inherited
`default`. Only the field's default policy supplies an exported `default`.
Custom codecs keep their value validation and encoding; their wrapper flags cannot make a required field optional or a
non-nullable field accept null.

Three annotations control presence and null acceptance. They change the JSON
contract only; Dart nullability and the constructor stay as written, and
unannotated fields keep constructor inference.

| Annotation | Effect |
| --- | --- |
| `@IsOptional()` | The key may be omitted. Valid when the constructor can accept a missing value: an optional or defaulted parameter, or `required T?` (a missing key then parses as `null` and encoding omits a null value). On `required T` generation fails. |
| `@IsRequired()` | The key must be present. On an optional `T?` field JSON `null` is still accepted and encoding writes the key even when the value is null. On a defaulted field, input no longer falls back to the default. |
| `@IsNotNull()` | A present JSON `null` is rejected; key presence is unchanged. Use it on `T?` and `JsonMaybe<T>` fields; non-nullable fields such as `Map<String, V>` already reject JSON `null`. A missing optional key still parses as `null`. Encoding uses a non-null constructor default when one is inferred; otherwise it omits a null Dart value. |

`@IsOptional()` is not a no-op on a defaulted field. Without it,
`this.tools = const []` generates `.withDefault(const [])`. With it, the field
generates `.optional()`: a missing key still gets the constructor default, but
JSON `null` is rejected for a non-nullable type and the exported JSON Schema
carries no `default`.

`@IsOptional()` alone on `String?` still accepts JSON `null`. Add
`@IsNotNull()` when a present value must not be `null`:

```dart
@Schemable()
final class const Example({@IsOptional() @IsNotNull() final String? label})
    with _$ExampleAck;
```

`ExampleSchema.parse({})` yields `label: null`, `{"label": "hello"}` succeeds,
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.

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:

| Dart field | Inferred schema |
| --- | --- |
| `Object` | `Ack.any()` |
| `Object?` | `Ack.any().nullable()`; presence rules match `String?` |
| `List<Object>` | `Ack.list(Ack.any())` |
| `Map<String, T>` | `Ack.map(<schema for T>)` |
| `Map<String, Object?>` | `Ack.map(Ack.any().nullable())` |
| `JsonMaybe<T>` | Optional-and-nullable `<schema for T>`; omitted when `JsonAbsent`, `null` when `JsonValue(null)` |

Use `JsonMaybe<T>` when a `PATCH` request needs to distinguish an omitted field
(`JsonAbsent`) from an explicit `null` (`JsonValue(null)`):

```dart
@Schemable()
final class const ProfilePatch({
  final JsonMaybe<String> bio = const JsonMaybe.absent(),
}) with _$ProfilePatchAck {
  static final schema = ProfilePatchSchema.schema;
  static final fromJson = ProfilePatchSchema.fromJson;
}

// Omitted key -> JsonAbsent(); toJson() returns {}
final unchanged = ProfilePatch.fromJson({});

// Explicit null -> JsonValue(null); toJson() returns {'bio': null}
final cleared = ProfilePatch.fromJson({'bio': null});
```

`Object` means a JSON-safe value (a finite number, string, boolean, list, or
string-keyed map of those values), not an arbitrary Dart instance, so a
`DateTime` inside an `Object` or `Map<String, Object?>` field fails validation.
Map values may be `null` only when the value type is nullable. `List<Object?>`
stays rejected because `Ack.list` has no nullable-item contract. Parsed
`Object` values are recursively unmodifiable, like other stored collections.

Rule annotations follow the field type. `Is…` names what the value is, and
`Has…` names a bound or property it has:

- presence & nullability: `@IsRequired`, `@IsOptional`, `@IsNotNull`;
- numeric: `@HasMin`, `@HasMax`, `@IsMultipleOf`, `@IsPositive`, `@IsNegative`;
- strings: `@HasMinLength`, `@HasMaxLength`, `@HasMatch`, `@IsEmail`, `@IsNotEmpty`;
- string formats: `@IsUrl`, `@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<Set<T>>` field the collection
constraints apply to the outer set.

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
a single wire-name override. Ack resolves each wire key once and uses it for both
validation and JSON mapping. `JsonConverter` annotations are rejected so the Ack
schema and generated JSON mapping cannot diverge.

### Custom schemas and types that own their schema

When a class-first field has a custom type `T` (including inside `List<T>`,
`Set<T>`, `Map<String, T>`, `JsonMaybe<T>`, or generic `Box<T>`), Ack resolves
its schema in the following priority order:

1. **`@Schemable(schemas: [...])`** on the class, enclosing union base, current
   `library;` directive, or an imported `library;` directive;
2. **Type-owned schema (`T.schema` / `T.schema<A>(...)`)** on the type itself;
3. **Automatic current-library detection**: a unique top-level
   `AckSchema<Boundary, T>` 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
the field, also as a `List` or `Set` item and as a `Map` value:

```dart
final class Slot {
  const Slot(this.id);
  final String id;

  static final schema = Ack.string().codec<Slot>(
    decode: Slot.new,
    encode: (slot) => slot.id,
  );
}

@Schemable()
final class const Section({
  required final Slot header,          // Slot.schema
  final Slot? footer,                  // Slot.schema, optional and nullable
  required final List<Slot> children,  // Ack.list(Slot.schema)
}) with _$SectionAck;
```

The static can be a field or a getter typed `AckSchema<Boundary, Slot>`. It
works the same on an extension type; declare it `implements Object` so it
satisfies the codec's `Object` bound:

```dart
extension type const WidgetId(String value) implements Object {
  static final schema = Ack.string().codec<WidgetId>(
    decode: WidgetId.new,
    encode: (id) => id.value,
  );
}
```

An enum that declares a static `schema` resolves to it as well, instead of
the default `Ack.enumValues`, so it can map custom wire values.

A static field cannot mention a class's type parameters, so a generic type
declares a static generic method instead. It takes one of two forms. With no
parameters, the generator calls it with the field's type arguments, written as
they are, including `void` and `Object?`:

```dart
final class Command<A> {
  const Command(this.name);
  final String name;

  static AckSchema<String, Command<A>> schema<A>() =>
      Ack.string().codec<Command<A>>(
        decode: Command<A>.new,
        encode: (command) => command.name,
      );
}

// final Command<CompletionAction> open;  ->  Command.schema<CompletionAction>()
// final Command<void> close;             ->  Command.schema<void>()
```

When the schema needs to validate the type argument itself, declare one
positional parameter per type parameter, each typed `AckSchema<Object, A>` for
its type parameter `A`. The generator passes the
schema it infers for each type argument: a facade for a `@Schemable` class, a
built-in schema for a primitive, and the collection schema for a `List`:

```dart
final class Box<A extends Object> {
  const Box(this.value);
  final A value;

  static AckSchema<Object, Box<A>> schema<A extends Object>(
    AckSchema<Object, A> value,
  ) => value.codec<Box<A>>(decode: Box<A>.new, encode: (box) => box.value);
}

// final Box<Row> row;          ->  Box.schema<Row>(RowSchema.schema)
// final Box<String> title;     ->  Box.schema<String>(Ack.string())
// final Box<List<Row>> rows;   ->  Box.schema<List<Row>>(Ack.list(RowSchema.schema))
```

Generation checks the parameter count and that each parameter is a schema of
its type argument. A type argument without an inferable schema fails with the
usual unsupported-type message.

The schema must produce the field's type; generation fails otherwise,
for example when `Slot.schema` produces a `String` or when a generic type
offers a static field instead of a `schema<A>()` method. Schema-first objects
can reference the same members, such as `'header': Slot.schema` or
`'open': Command.schema<void>()`.

### External types and library registries

For a third-party type you cannot edit:

- **In the same library**: declare a unique top-level `AckSchema<Boundary, T>`
  variable, getter, or zero-argument function — Ack detects it automatically.
- **Across a class, union, or library**: pass top-level schema function tear-offs
  in `@Schemable(schemas: [colorSchema])` on the class, union base, or `library;`
  directive (including an imported shared `library;` directive).

```dart
@Schemable(schemas: [colorSchema])
library;

import 'package:ack/ack.dart';
import 'package:color_library/color.dart';

part 'theme.g.dart';

AckSchema<String, Color> colorSchema() => Ack.string().codec<Color>(
  decode: Color.parse,
  encode: (color) => color.hex,
);

@Schemable()
final class const Theme({required final Color primary}) with _$ThemeAck;
```

Non-String map keys and `dynamic` are rejected because they do not provide a
static schema; use `Object?` for an open JSON value.
Automatic `List<T>` and `Set<T>` inference also requires non-nullable element
types because `Ack.list` has no nullable-item contract.

### Class-first unions

Annotate a sealed base with a discriminator key. Concrete branches in the same
library are included automatically, and inherited constructor fields may use
super parameters:

```dart
@Schemable(discriminatorKey: 'type')
sealed class const Pet({required final String id}) with _$PetAck;

@Schemable(discriminatorValue: 'cat')
final class const Cat({required super.id, required final int lives})
    extends Pet
    with _$CatAck;

final class const Dog({required super.id, required final String breed})
    extends Pet
    with _$DogAck;
```

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.

### Additional properties

Raw object validation and class projection are separate decisions.
`Ack.object(..., additionalProperties: true)` accepts unknown keys and preserves
them in the returned `JsonMap`. A later class-first projection then decides
whether the Dart class rejects, discards, or captures those keys.

`@Schemable` uses `AckUnknownPropertyPolicy` through `unknownProperties`:

- `reject` (default) fails validation on unknown properties;
- `discard` accepts unknown properties but does not store them. Use it only for
  tolerant, read-only consumers;
- `capture` stores them in `captureField`, which defaults to
  `additionalProperties` and may be `args`.

Capture requires a declared `Map<String, Object?>` field initialized by the
constructor. Encoding writes extras first, so a declared field or
discriminator cannot be replaced by an extra value. Models that must round-trip
unknown keys must use `capture`, not `discard`. Hand-written constructors can
call `deepUnmodifiableJsonMap` to detach and recursively freeze direct map
inputs without validating them.

### Reusing generated schemas

Nested class-first fields compose through the target facade (or `Address.schema`
when declared on the class) automatically:

```dart
import 'address.dart' as address;

@Schemable()
final class const Order({required final address.Address shipping})
    with _$OrderAck;

// Generated field schema: address.AddressSchema.schema
```

Schema-first declarations can use `Address.schema` or the facade explicitly:

```dart
@Schemable()
final envelopeSchema = Ack.object({
  'address': address.AddressSchema.schema,
  'history': Ack.list(address.AddressSchema.schema),
});
```

Class-first fields may also use a model generated from a `@Schemable()`
top-level schema; Ack composes through the generated `Address.$ack.schema`.
Both directions work on the first clean build, including nullable values,
lists, nested lists, and sets. A model generated in the same build cannot yet
be a `Map` value; generation reports that case.

A generated part cannot add imports, so every type a field names must be
visible in the annotated library itself. A type reached only through a
`typedef` from another library, or a codec's runtime type from a library you
did not import, fails generation with the library to import.

When importing with `show` / `hide` combinators, if a class-first model declares
`static final schema = AddressSchema.schema;`, importing libraries only need to expose
`Address`:

```dart
import 'address.dart' show Address;
```

If `Address` does not declare a static `schema`, expose both the hand-written
model and its generated facade:

```dart
import 'address.dart' show Address, AddressSchema;
```

For schema-first composition it means the annotated schema and generated model
(`addressSchema` plus `Address`). Visibility may be split across multiple
imports using the same prefix, but every barrel export layer must expose the
generated companion. Prefixed imports avoid ambiguity when two libraries
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.

## Which direction should you choose?

Put `@Schemable()` on a top-level schema when you want to design the boundary
schema first, generate the whole model, or model a scalar or collection root.
Put it on a class when you already own the class, want to keep methods and constructors in source,
or prefer field annotations over a separate object schema.

This choice is per model, not per project. A migration can keep existing
schema-first types while new domain-owned types use class-first generation.

## Limit generation in larger projects

Scope `ack_generator` to your model files with `generate_for`:

```yaml title="build.yaml"
targets:
  $default:
    builders:
      ack_generator:ack_generator:
        generate_for: [lib/models/**.dart]
```

## Build checklist

1. Add `ack` to dependencies and import `package:ack/ack.dart`.
2. Add `ack_generator` and `build_runner` to dev dependencies.
3. Declare `part '<file>.g.dart';` in each annotated library.
4. Put `@Schemable()` on a top-level schema or on a class.
5. Run `dart run build_runner build`.

## Migrating from 1.x

- 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 '<file>.ack.dart';` + `part '<file>.ack.g.dart';` with a single `part '<file>.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('...')`.

See the [What's New & Migration Guide](../getting-started/migration-guide.mdx) for the complete substitution tables and side-by-side before/after examples.
```

### Validation Rules

Source: https://docs.page/btwld/ack/core-concepts/validation

```mdx

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()` 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).

### `constrain(Constraint<T> constraint, {String? message})`

Applies a custom `Constraint<T>` that also implements `Validator<T>`. See the [Custom Validation](../guides/custom-validation.mdx) guide.

## String constraints

Apply these to [`Ack.string()`](./schemas.mdx#string) schemas.

### `minLength(int min)`
Requires at least `min` characters.
```dart
Ack.string().minLength(5)
```

### `maxLength(int max)`
Requires at most `max` characters.
```dart
Ack.string().maxLength(100)
```

### `length(int n)`
Requires exactly `n` characters.
```dart
Ack.string().length(10)
```

### `notEmpty()`
Requires a non-empty string. Equivalent to `minLength(1)`.
```dart
Ack.string().notEmpty()
```

### `matches(String pattern, {String? example, String? message})`
Requires the string to match a regular expression `pattern`.

Patterns are **not** automatically anchored. The pattern matches if found anywhere in the string. To require a full-string match, add anchors: `^...$`

```dart
// Simple alphanumeric pattern (full-string match with anchors)
Ack.string().matches(r'^[a-zA-Z0-9]+$')

// UUID pattern (full-string match with anchors)
Ack.string()
    .matches(r'^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$')

// Without anchors - matches substring (usually not what you want!)
Ack.string().matches(r'[0-9]+')  // Matches "abc123xyz" ⚠️
```

### `contains(String pattern, {String? example, String? message})`
Requires `pattern` to appear somewhere in the string.
```dart
// Password must contain at least one uppercase letter
Ack.string().contains(r'[A-Z]')

// Password must contain at least one digit
Ack.string().contains(r'[0-9]')
```

### `email()`
Requires a valid email address format.
```dart
Ack.string().email()
```

### `date()`
Requires a valid date string in `YYYY-MM-DD` format.
```dart
Ack.string().date()
```

### `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
`DateTime` cannot represent them without normalization.
```dart
Ack.string().datetime()
```

### `time()`
Requires a valid time string in `HH:MM:SS` format.
```dart
Ack.string().time()
```

### `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.
```dart
Ack.string().uri()
```

### `uuid()`
Requires a valid UUID per RFC 4122.
```dart
Ack.string().uuid()
```

### `ipv4()`
Requires a valid IPv4 address.
```dart
Ack.string().ipv4()
```

### `ipv6()`
Requires a valid IPv6 address.
```dart
Ack.string().ipv6()
```



### `Ack.enumString(List<String> 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
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
Ack.literal('admin')
```

### `startsWith(String prefix)`
Requires the string to start with `prefix`.
```dart
Ack.string().startsWith('https://')
```

### `endsWith(String suffix)`
Requires the string to end with `suffix`.
```dart
Ack.string().endsWith('.dart')
```

### `url()`
Alias for `uri()`. Requires a valid URL.
```dart
Ack.string().url()
```

### `ip({int? version})`
Requires a valid IP address. Set `version` to `4` or `6` to restrict the version.
```dart
Ack.string().ip()           // Any IP (v4 or v6)
Ack.string().ip(version: 4) // IPv4 only
Ack.string().ip(version: 6) // IPv6 only
```

## 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 them to JSON Schema as `type: 'string'` without
`'x-transformed': true`.

### `trim()`
Removes leading and trailing whitespace on parse and encode.
```dart
Ack.string().trim().minLength(2)
// "  hello  " → "hello"
```

### `toLowerCase()`
Converts the string to lowercase on parse and encode.
```dart
Ack.string().toLowerCase()
// "HELLO" → "hello"
```

### `toUpperCase()`
Converts the string to uppercase on parse and encode.
```dart
Ack.string().toUpperCase()
// "hello" → "HELLO"
```

## Number constraints

Apply these to [`Ack.integer()`](./schemas.mdx#number), [`Ack.double()`](./schemas.mdx#number), or [`Ack.number()`](./schemas.mdx#number) schemas.

### `min(num limit)`
Requires a value `>= limit` (inclusive).
```dart
Ack.integer().min(0) // >= 0
Ack.double().min(0.0) // >= 0.0
Ack.number().min(0) // >= 0
```

### `max(num limit)`
Requires a value `<= limit` (inclusive).
```dart
Ack.integer().max(100) // <= 100
Ack.double().max(100.0) // <= 100.0
Ack.number().max(100) // <= 100
```

### `greaterThan(num limit)`
Requires a value strictly `> limit` (exclusive).
```dart
Ack.integer().greaterThan(0) // > 0
Ack.double().greaterThan(0.0) // > 0.0
Ack.number().greaterThan(0) // > 0
```

### `lessThan(num limit)`
Requires a value strictly `< limit` (exclusive).
```dart
Ack.integer().lessThan(100) // < 100
Ack.double().lessThan(100.0) // < 100.0
Ack.number().lessThan(100) // < 100
```

### `multipleOf(num factor)`
Requires a value that is a multiple of `factor`. Integer checks are exact; doubles use a small scale-relative tolerance, so round accumulated floating-point sums (or validate integer units such as cents) before parsing.
```dart
Ack.integer().multipleOf(5) // Must be divisible by 5
Ack.double().multipleOf(0.5) // Use factors that avoid floating point rounding issues
Ack.number().multipleOf(0.5)
```

### `positive()`
Requires a value greater than 0.
```dart
Ack.integer().positive() // > 0
Ack.double().positive() // > 0.0
Ack.number().positive() // > 0
```

### `negative()`
Requires a value less than 0.
```dart
Ack.integer().negative() // < 0
Ack.double().negative() // < 0.0
Ack.number().negative() // < 0
```

### `safe()` (integer only)
Requires an integer within JavaScript's safe range (`-2^53+1` to `2^53-1`).
```dart
Ack.integer().safe()
```

### `finite()`
Requires a finite number (rejects `infinity` and `NaN`). `Ack.double()` and
`Ack.number()` enforce this by default; `finite()` is available for
explicitness and API symmetry.
```dart
Ack.double().finite()
Ack.number().finite()
```

## List constraints

Apply these to [`Ack.list()`](./schemas.mdx#list) schemas.

### `minLength(int min)`
Requires at least `min` items.
```dart
Ack.list(Ack.string()).minLength(1)
```

### `maxLength(int max)`
Requires at most `max` items.
```dart
Ack.list(Ack.integer()).maxLength(10)
```

### `length(int count)`
Requires exactly `count` items.
```dart
Ack.list(Ack.boolean()).length(5)
```

### `notEmpty()`
Requires a non-empty list. Equivalent to `minLength(1)`.
```dart
Ack.list(Ack.object({})).notEmpty()
```

### `unique()`
Requires all items to be unique. Uses deep structural equality, so nested maps and lists are compared by value.
```dart
Ack.list(Ack.string()).unique()
```

## Primitive inputs and numeric normalization

String and boolean schemas require the expected Dart runtime type. Numeric
schemas require a `num`, but normalize by mathematical value so native and web
builds behave identically. Non-numeric inputs surface as a `TypeMismatchError`
rather than being silently coerced.

| Schema          | Accepted boundary value                         | Runtime value                        |
| --------------- | ----------------------------------------------- | ------------------------------------ |
| `Ack.string()`  | `String`                                        | unchanged `String`                   |
| `Ack.integer()` | finite `num` with no fractional part, lossless  | normalized `int`                     |
| `Ack.double()`  | finite `num`, exactly representable as `double` | normalized `double`                  |
| `Ack.number()`  | finite `num`                                    | original `int` or `double`           |
| `Ack.boolean()` | `bool`                                          | unchanged `bool`                     |

```dart
final stringSchema = Ack.string();
stringSchema.safeParse('hello');  // ✅ OK
stringSchema.safeParse(123);      // ❌ FAIL: TypeMismatchError
stringSchema.safeParse(true);     // ❌ FAIL: TypeMismatchError

final intSchema = Ack.integer();
intSchema.parse(42);       // => 42 (int)
intSchema.parse(42.0);     // => 42 (int)
intSchema.safeParse(42.5); // ❌ FAIL: not a mathematical integer
intSchema.safeParse('42'); // ❌ FAIL: TypeMismatchError

final doubleSchema = Ack.double();
doubleSchema.parse(3.14); // => 3.14 (double)
doubleSchema.parse(42);   // => 42.0 (double)

final numberSchema = Ack.number();
numberSchema.safeParse(42);    // ✅ OK (int is num)
numberSchema.safeParse(3.14);  // ✅ OK (double is num)
numberSchema.safeParse('42');  // ❌ FAIL: TypeMismatchError
```

`Ack.integer()` and `Ack.double()` overlap for integral values. `Ack.anyOf`
returns the first successful branch, so order numeric branches according to the
runtime representation you want. Use `Ack.number()` when validation should
preserve an input that is already an `int` or `double`. Use `transform`/`codec`
when the boundary value is not already a `num` (for example, a numeric string).

Primitive type checking still lets unions distinguish the string `"42"` from
the numeric value `42` without configuration:

```dart
final stringOrNumber = Ack.anyOf([
  Ack.string(),
  Ack.integer(),
]);

stringOrNumber.safeParse('42');  // ✅ Matches string branch
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
// 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<R>(decode: ..., encode: ...)` when you also need a reversible encode path back to the boundary type.

## Combining constraints

You can chain multiple constraints. Ack evaluates them in the order you apply them.

```dart
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)
```

## Next steps

- **[Error handling](/core-concepts/error-handling)**: Handle and display validation errors
- **[Custom validation](/guides/custom-validation)**: Create custom constraints and refinement logic
- **[Schema types](/core-concepts/schemas)**: All available schema types and their operations
- **[Common recipes](/guides/common-recipes)**: Practical validation patterns and solutions
- **[Flutter forms](/guides/flutter-form-validation)**: Integrate validation with Flutter form widgets
```

### Installing Ack

Source: https://docs.page/btwld/ack/getting-started/installation

```mdx

Ack is a pure-Dart package with no required build step. Add the core library — and, optionally, the code generator for immutable models.

## Add to your project

Add Ack to your project using the Dart CLI:

```bash
# For Dart projects
dart pub add ack:^2.0.0-beta.3

# For Flutter projects
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
```

## Optional code generator

To generate models from Ack schemas or Ack schemas from hand-written models,
add `ack` and the generator package:

```bash
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 `<ClassName>Schema` facade and JSON helpers. There is no `@AckSchema()` annotation; `AckSchema` is the runtime
schema type.

```dart
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:

```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.

## 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`.
```

### What's New & Migration Guide

Source: https://docs.page/btwld/ack/getting-started/migration-guide

```mdx

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**.

---

## Beta.2 to beta.3: `Is…`/`Has…` rule annotations

2.0.0-beta.3 replaces the `Validate` namespace with top-level rule
annotations. `Is…` names what a value is; `Has…` names a bound or property it
has:

```dart
@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;
}
```

Each old constructor still works and generates the same code, but it is
deprecated and its warning names the replacement. `Validate` is removed
before Ack 2.0.0. 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). Apps on Flutter 3.41 to 3.46 must upgrade
Flutter to use 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:

- `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<Boundary, Runtime>`):

| 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()`<br/>• Bidirectional `CodecSchema<Boundary, Runtime>`: `Ack.date()`, `Ack.datetime()`, `Ack.uri()`, `Ack.duration()`, `.codec()`, `.transform()`<br/>• Two-way string normalizers: `.trim()`, `.toLowerCase()`, `.toUpperCase()`<br/>• `JsonMaybe<T>` (`JsonAbsent<T>` / `JsonValue<T>`) for tri-state `PATCH` payloads<br/>• 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)<br/>• Sealed `SchemaResult<T>` (`Ok` / `Fail`) and sealed `SchemaError` hierarchy<br/>• 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 `<file>.g.dart`<br/>• **Class-first (`@Schemable()` on a `final class` or `sealed class`)**: Supports standard and Dart 3.13+ primary constructors; generates the `<Name>Schema` facade and the `_$<Name>Ack` mixin in `<file>.g.dart`<br/>• **`.schema.json` codegen (`ack_generator:ack_json_schema`)**: Compiles `lib/**/*.schema.json` assets into `<name>.schema.dart` + `<name>.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. 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`. The 2.0 beta `Validate` namespace is deprecated and is removed before Ack 2.0.0. | 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 `<file>.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 '<file>.g.dart';`, and coexists with Freezed or Riverpod in the same file. |
| **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<A>()` factories, or automatic detection of a unique top-level `AckSchema<Boundary, T>` 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<Class>` 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<T>` (`JsonAbsent` / `JsonValue<T>`)** | `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. |

---

## 3. What Doesn't Exist Anymore & Exact Substitutions

### Packages & Imports

| Removed Item | Removed In | Exact Substitution |
| --- | --- | --- |
| `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';` |
| `import 'package:ack_annotations/format_annotations.dart';` | `1.7.0` | `import 'package:ack/ack.dart';` (use the rule annotations) |
| `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 Symbol | Removed In | Exact Substitution |
| --- | --- | --- |
| `@AckType()` | `2.0.0` | `@Schemable()` on the top-level schema |
| `@AckInfer(...)` | `2.0.0` | `@Schemable(...)` on the top-level schema |
| `@AckModel(...)` | `2.0.0` | `@Schemable(...)` on the class |
| `@Optional()` / `@AckField(presence: AckFieldPresence.optional)` | `2.0.0` | `@IsOptional()` (add `@IsNotNull()` if present JSON value must not be `null`) |
| `@Required()` / `@AckField(presence: AckFieldPresence.required)` | `2.0.0` | `@IsRequired()` |
| `@NotNull()` | `2.0.0` | `@IsNotNull()` (rejects explicit `null` without requiring an optional key) |
| `@JsonKey(name: 'wire_name')` on `@Schemable` fields | `2.0.0` | `@AckKey('wire_name')` |
| `@AckField(schema: ...)` | `2.0.0` | `@Schemable(schemas: [...])`, `T.schema`, or top-level library schema |
| `@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: [...])` |

### Validation Annotations

The top-level 1.x validation and presence classes were removed in `2.0.0`.
The 2.0 beta `Validate` namespace is deprecated in `2.0.0-beta.3` and is
removed before Ack 2.0.0. Replace both with the rule annotations from
`package:ack/ack.dart`. Each rule keeps the same field types, generated schema,
and errors:

| Removed `1.x` annotation | Deprecated 2.0 beta annotation | Rule annotation (`2.0.0-beta.3`) |
| --- | --- | --- |
| `@Optional()` | `@Validate.optional()` | `@IsOptional()` |
| `@Required()` | `@Validate.required()` | `@IsRequired()` |
| `@NotNull()` | `@Validate.notNull()` | `@IsNotNull()` |
| `@Min(value)` | `@Validate.min(value)` | `@HasMin(value)` |
| `@Max(value)` | `@Validate.max(value)` | `@HasMax(value)` |
| `@MultipleOf(value)` | `@Validate.multipleOf(value)` | `@IsMultipleOf(value)` |
| `@Positive()` | `@Validate.positive()` | `@IsPositive()` |
| `@Negative()` | `@Validate.negative()` | `@IsNegative()` |
| `@MinLength(n)` | `@Validate.minLength(n)` | `@HasMinLength(n)` |
| `@MaxLength(n)` | `@Validate.maxLength(n)` | `@HasMaxLength(n)` |
| `@Pattern(r'...')` / `@Matches(r'...')` | `@Validate.matches(r'...')` | `@HasMatch(r'...')` (not anchored; use `^...$` for a full-string match) |
| `@NotEmpty()` | `@Validate.notEmpty()` | `@IsNotEmpty()` (works on `String`, `List`, and `Set`) |
| `@Email()` | `@Validate.email()` | `@IsEmail()` |
| `@Url()` | `@Validate.url()` | `@IsUrl()` |
| `@Uri()` | `@Validate.uri()` | `@IsUri()` |
| `@Uuid()` | `@Validate.uuid()` | `@IsUuid()` |
| `@Date()` | `@Validate.date()` | `@IsDate()` |
| `@DateTime()` | `@Validate.dateTime()` | `@IsDateTime()` |
| `@Ip()` | `@Validate.ip()` / `@Validate.ip(version: v)` | `@IsIp()` / `@IsIp(version: v)` |
| `@Ipv4()` | `@Validate.ipv4()` | `@IsIp(version: 4)` |
| `@Ipv6()` | `@Validate.ipv6()` | `@IsIp(version: 6)` |
| `@MinItems(n)` | `@Validate.minItems(n)` | `@HasMinItems(n)` |
| `@MaxItems(n)` | `@Validate.maxItems(n)` | `@HasMaxItems(n)` |
| `@UniqueItems()` | `@Validate.uniqueItems()` | `@HasUniqueItems()` |


### Generated Files, Builders & Runtime APIs

| Removed `1.x` Item | Removed In | Exact `2.0` Substitution |
| --- | --- | --- |
| `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.enumCodec(MyEnum.values)` | `2.0.0` | `Ack.enumValues(MyEnum.values)` |
| `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 |

---

## 4. Before & After Migration Examples

### Class-First Model Migration

```dart
// ❌ BEFORE (Ack 1.6)
import 'package:ack/ack.dart';
import 'package:ack_annotations/ack_annotations.dart' as ack;
import 'package:ack_annotations/format_annotations.dart' as formats;
import 'package:json_annotation/json_annotation.dart';

part 'account.ack.dart';
part 'account.ack.g.dart';

@ack.AckModel(caseStyle: ack.AckCaseStyle.snake)
final class Account with _$AccountAck {
  const Account({required this.userName, required this.createdAt});

  @JsonKey(name: 'username')
  @ack.MinLength(3)
  @ack.Pattern(r'^[a-z0-9_]+$')
  final String userName;

  @formats.DateTime()
  final String createdAt;
}
```

```dart
// ✅ AFTER (Ack 2.0)
import 'package:ack/ack.dart';

part 'account.g.dart';

@Schemable(caseStyle: AckCaseStyle.snake)
final class const Account({
  @AckKey('username')
  @HasMinLength(3)
  @HasMatch(r'^[a-z0-9_]+$')
  required final String userName,
  @IsDateTime() required final String createdAt,
}) with _$AccountAck {
  static final schema = AccountSchema.schema;
  static final fromJson = AccountSchema.fromJson;
}
```

### Schema-First Model Migration

```dart
// ❌ BEFORE (Ack 1.6, @AckInfer)
import 'package:ack/ack.dart';
import 'package:ack_annotations/ack_annotations.dart';

part 'user.ack.dart';
part 'user.ack.g.dart';

@AckInfer()
final userSchema = Ack.object({
  'name': Ack.string().minLength(2),
  'email': Ack.string().email(),
});
```

```dart
// ✅ AFTER (Ack 2.0)
import 'package:ack/ack.dart';

part 'user.g.dart';

@Schemable()
final userSchema = Ack.object({
  'name': Ack.string().minLength(2),
  'email': Ack.string().email(),
});

// Generated class User provides:
// - User.schema (AckSchema<Map<String, Object?>, User>)
// - User.parse(...) / User.safeParse(...)
// - User.fromJson(...) / user.toJson() / user.safeToJson()
// - user.copyWith(...) / deep == and hashCode
```
```

### Quickstart Tutorial

Source: https://docs.page/btwld/ack/getting-started/quickstart-tutorial

```mdx

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.

## 1. Define a schema

Describe the shape you expect. Fields are required unless you mark them `.optional()`.

```dart
import 'package:ack/ack.dart';

final userSchema = Ack.object({
  'name': Ack.string().minLength(2),      // required, min 2 chars
  'age': Ack.integer().min(0).optional(), // optional, non-negative
});
```

See [Schema Types](../core-concepts/schemas.mdx) and [Validation Rules](../core-concepts/validation.mdx) for everything you can express.

## 2. Validate data

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).

```dart
final result = userSchema.safeParse({'name': 'Alice', 'age': 30});

if (result.isOk) {
  final user = result.getOrThrow();       // validated Map<String, Object?>
  print('Valid: $user');
} else {
  print('Invalid: ${result.getError()}'); // structured error with a path
}
```

Prefer exceptions? Use `parse()` instead — it returns the value or throws `AckException`.

## 3. Handle every outcome

A schema accepts valid data and rejects each way it can be wrong. This runnable example checks four inputs:

```dart
import 'package:ack/ack.dart';

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
}

void checkResult(SchemaResult result) {
  if (result.isOk) {
    print('OK:     ${result.getOrThrow()}');
  } else {
    final error = result.getError();
    print('FAILED at ${error.path}: ${error.message}'); // path is a JSON Pointer
  }
}
```

See [Error Handling](../core-concepts/error-handling.mdx) to read and display errors.

## Next steps

- [Schema Types](../core-concepts/schemas.mdx) — all available schema types
- [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
```

### Common Recipes

Source: https://docs.page/btwld/ack/guides/common-recipes

```mdx

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.

## Email and password validation

Validate user credentials with proper constraints:

```dart
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
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
// 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(),
  })).minLength(1).maxLength(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()).maxLength(5),
});
```

## Enum validation

Validate values against a set of allowed options using Dart enums:

```dart
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
import 'package:ack/ack.dart';

// Custom phone number constraint
class PhoneNumberConstraint extends Constraint<String> with Validator<String> {
  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)';
}

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',
);
```

## API response validation

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.

Add the HTTP client first with `dart pub add http`.

```dart
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(),
  'avatar_url': Ack.string().url(),
  'name': Ack.string().nullable(),
  'email': Ack.string().email().nullable(),
  'bio': Ack.string().nullable(),
  'public_repos': Ack.integer(),
  'followers': Ack.integer(),
  'following': Ack.integer(),
  'created_at': Ack.string().datetime(),
}, additionalProperties: true);

// Usage in API call
Future<void> fetchUser(String username) async {
  final response = await http.get(
    Uri.parse('https://api.github.com/users/$username'),
  );

  if (response.statusCode != 200) {
    throw StateError('GitHub request failed: ${response.statusCode}');
  }

  final json = jsonDecode(response.body);
  final result = githubUserSchema.safeParse(json);

  if (result.isOk) {
    final user = result.getOrThrow()!;
    print('User: ${user['login']}');
  } else {
    print('Invalid API response: ${result.getError()}');
  }
}
```

## 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
```

### Creating Adapter Packages

Source: https://docs.page/btwld/ack/guides/creating-schema-converter-packages

```mdx

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.

## Choose the export surface

| Target | Starting point | Responsibility |
|---|---|---|
| Accepts JSON Schema maps | `schema.toJsonSchema()` | Preserve the rendered document and check target dialect support. |
| 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
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.

## JSON-map adapters

If the target accepts Ack's rendered JSON Schema, the conversion can be small:

```dart
import 'package:ack/ack.dart';

extension TargetJsonSchemaExtension on AckSchema {
  Map<String, Object?> toTargetJsonSchema() => toJsonSchema();
}
```

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.

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.

## 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 `warnings` on model nodes, including nested nodes. 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

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:

```dart
import 'package:ack/ack.dart';
import 'package:test/test.dart';

// Import the adapter library defining TargetJsonSchemaExtension here.

void main() {
  test('exports the wire contract', () {
    final schema = Ack.object({
      'name': Ack.string().minLength(2),
      'when': Ack.datetime(),
      'nickname': Ack.string().optional().nullable(),
    });

    final json = schema.toTargetJsonSchema();
    final properties = json['properties'] as Map<String, Object?>;

    expect(properties['name'], containsPair('minLength', 2));
    expect(properties['when'], containsPair('type', 'string'));
    expect(properties['when'], containsPair('format', 'date-time'));
    expect(json['required'], containsAll(['name', 'when']));
    expect(json['required'], isNot(contains('nickname')));
    expect(json, containsPair('additionalProperties', false));
  });
}
```

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.

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.

## Add an adapter to this repository

Use an `ack_<target>` 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.

Follow [CONTRIBUTING.md](https://github.com/btwld/ack/blob/release/2.0/CONTRIBUTING.md)
for checks, and [PUBLISHING.md](https://github.com/btwld/ack/blob/release/2.0/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.
```

### Custom Validation Rules

Source: https://docs.page/btwld/ack/guides/custom-validation

```mdx

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<T>` that mixes in `Validator<T>`.

```dart
import 'package:ack/ack.dart';

class IsPositiveConstraint extends Constraint<double> with Validator<double> {
  IsPositiveConstraint()
      : super(
          constraintKey: 'is_positive',
          description: 'Number must be positive',
        );

  @override
  bool isValid(double value) => value > 0;

  @override
  String buildMessage(double value) => 'Number must be positive';
}

final priceSchema = Ack.double().constrain(IsPositiveConstraint());

print(priceSchema.safeParse(10.5).isOk); // true
print(priceSchema.safeParse(-5.0).isFail); // true
```

## Cross-field rules with `.refine()`

When validation depends on multiple fields, use `.refine()` on the parent object schema.

```dart
final signUpSchema = Ack.object({
  'password': Ack.string().minLength(8),
  'confirmPassword': Ack.string().minLength(8),
}).refine(
  (data) => data['password'] == data['confirmPassword'],
  message: 'Passwords do not match',
);

final result = signUpSchema.safeParse({
  'password': 'pass1234',
  'confirmPassword': 'different',
});
print(result.isFail); // true
```

## Overriding error messages

The optional `message` parameter on `.constrain()` lets you customize the failure message.

```dart
final schema = Ack.double()
    .constrain(IsPositiveConstraint(), message: 'Price must be greater than zero.');

final result = schema.safeParse(-10.0);
if (result.isFail) {
  print(result.getError().message); // Price must be greater than zero.
}
```

## Organizing reusable constraints

Place frequently used constraints in utility files so they can be shared across schemas.

```dart
// file: validation/constraints.dart
import 'package:ack/ack.dart';

class IsPositiveConstraint extends Constraint<double> with Validator<double> {
  // ...
}

// 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()),
});
```

## When to use custom logic

- **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).

Chaining built-in constraints is often enough for simple cases. Use custom constraints or refinements when you need extra flexibility.

## Next steps

- [Common Recipes](./common-recipes.mdx) — custom constraints in real-world schemas
- [Flutter Form Validation](./flutter-form-validation.mdx) — surface custom messages in forms
- [Error Handling](../core-concepts/error-handling.mdx) — read `SchemaConstraintsError`
```

### Ecosystem Integrations

Source: https://docs.page/btwld/ack/guides/ecosystem-integrations

```mdx

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.

| Adapter Package | Target Ecosystem | Primary Entry Point |
| --- | --- | --- |
| **`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()` |

---

## 1. Define a Model or Schema Once

```dart title="lib/weather_models.dart"
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
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<WeatherQuery>(
    '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
import 'dart:convert';

import 'package:ack_firebase_ai/ack_firebase_ai.dart';
import 'package:firebase_ai/firebase_ai.dart';

import 'weather_models.dart';

Future<WeatherReport> 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<Object, Object>
  final AckSchema<Object, Object> 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);
}
```

---

## 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)
```

### Form Validation in Flutter with Ack

Source: https://docs.page/btwld/ack/guides/flutter-form-validation

```mdx

This guide shows how to use Ack for validating forms in Flutter applications.

## 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))

Install Ack in your Flutter project:

```bash
flutter pub add ack:^2.0.0-beta.3
```

## Basic form validation with `TextFormField`

Ack works with Flutter form APIs by running `safeParse` inside
`TextFormField.validator` and returning a `String?` error message
(`null` when valid).

```dart
import 'package:ack/ack.dart';
import 'package:flutter/material.dart';

class SignUpForm extends StatefulWidget {
  const SignUpForm({super.key});

  @override
  State<SignUpForm> createState() => _SignUpFormState();
}

class _SignUpFormState extends State<SignUpForm> {
  // GlobalKey to manage Form state
  final _formKey = GlobalKey<FormState>();

  // Controllers for input fields
  final _usernameController = TextEditingController();
  final _emailController = TextEditingController();
  final _passwordController = 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();

  final _emailSchema = Ack.string()
    .email()
    .notEmpty();

  final _passwordSchema = Ack.string()
    .minLength(8)
    .matches(r'.*[A-Z].*')
    .matches(r'.*[a-z].*')
    .matches(r'.*[0-9].*')
    .notEmpty();

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey, // Associate the key with the Form
      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().toString() : null;
            },
            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().toString() : null;
            },
            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().toString() : null;
            },
            autovalidateMode: AutovalidateMode.onUserInteraction,
          ),
          const SizedBox(height: 24),

          // Submit Button
          ElevatedButton(
            onPressed: _submitForm,
            child: const Text('Sign Up'),
          ),
        ],
      ),
    );
  }

  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();
    super.dispose();
  }
}
```

Key steps: define an `AckSchema` per field; in `TextFormField.validator`, call `schema.safeParse(value)` and return `result.getError().toString()` 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).

## Real-time validation with `TextField`

Without a `Form` widget, listen to controller changes and update the error state directly.

```dart
import 'package:ack/ack.dart';
import 'package:flutter/material.dart';

class RealtimeValidationField extends StatefulWidget {
  const RealtimeValidationField({super.key});

  @override
  State<RealtimeValidationField> createState() => _RealtimeValidationFieldState();
}

class _RealtimeValidationFieldState extends State<RealtimeValidationField> {
  final _emailController = TextEditingController();
  String? _emailErrorText; // State variable to hold the error message

  // Define the schema
  final _emailSchema = Ack.string()
      .email()
      .notEmpty();

  @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().toString() : null;
      });
    } else {
      // Clear error if field becomes empty
      setState(() {
         _emailErrorText = null;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: TextField(
        controller: _emailController,
        decoration: InputDecoration(
          labelText: 'Email',
          // Display the error text from the state variable
          errorText: _emailErrorText,
        ),
        keyboardType: TextInputType.emailAddress,
      ),
    );
  }

  @override
  void dispose() {
    _emailController.removeListener(_validateEmail);
    _emailController.dispose();
    super.dispose();
  }
}
```

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
// Define a schema for the whole form data
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('Form submission error: $error');
    // You might need to map the error path back to specific fields
    // to display errors if not using TextFormField validators.
  }
}
```

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.
```

### JSON Schema Integration

Source: https://docs.page/btwld/ack/guides/json-schema-integration

```mdx

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.

## Importing published schemas

Use strict `Ack.fromJsonSchema()` to turn a decoded JSON Schema document
(a map or boolean, not a JSON string) into an
`AckSchema<Object, Object>`. The input dialect is draft 2020-12 or Draft-7
(`http(s)://json-schema.org/draft-07/schema(#)`), including when `$schema` is
absent. Other explicitly declared dialects are rejected.

Only the declared `$schema` string is checked — a document is never matched
against a dialect by shape. Draft-7 documents are evaluated under the same
supported subset: tuple-form `items` (a Draft-7 array) is rejected, and `$ref`
siblings are applied as in draft 2020-12. Draft-4 boolean `exclusiveMinimum`
and `exclusiveMaximum` values are rejected, and Draft-4 `integer` rejects `1.0`
where this importer accepts it.

```dart
import 'package:ack/ack.dart';

final AckSchema<Object, Object> schema = Ack.fromJsonSchema({
  'type': 'object',
  'properties': {
    'name': {'type': 'string'},
    'age': {'type': 'integer', 'minimum': 0},
  },
  'required': ['name'],
  'additionalProperties': false,
});

final user = schema.parse({'name': 'Ada', 'age': 36});
final exported = schema.toJsonSchema();
```

The returned abstract `AckSchema<Object, Object>` composes with native
Ack schemas; its runtime implementation is internal. It validates JSON values
without injecting defaults or applying coercions. Parsing returns a detached,
recursively unmodifiable value.
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

`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.

You can import an existing export directly:

```dart
final document = Ack.object({'name': Ack.string()}).toJsonSchema();
final AckSchema<Object, Object> 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
types, custom callbacks, or refinements that were absent from the export.
Exports containing unsupported keywords are rejected.

### Importing `format`

By default, `Ack.fromJsonSchema()` treats `format` as an annotation (matching
JSON Schema Draft 2020-12's default Core/Applicator/Validation vocabularies).
Pass `assertFormats: true` (or declare the Draft 2020-12 `format-assertion`
vocabulary in `$vocabulary`) to enable runtime format assertions for the full
Draft 2020-12 format suite (`date-time`, `date`, `time`, `duration`, `email`,
`idn-email`, `hostname`, `idn-hostname`, `ipv4`, `ipv6`, `uri`, `uri-reference`,
`iri`, `iri-reference`, `uuid`, `uri-template`, `json-pointer`,
`relative-json-pointer`, `regex`) as well as standard numeric format bounds
(`int32`, `int64`, `uint32`, `uint64`, `float`, `double`):

```dart
final timestamp = Ack.fromJsonSchema(
  {'type': 'string', 'format': 'date-time'},
  assertFormats: true,
);
timestamp.parse('2024-02-29T12:34:56.123456789+02:00');
```

Date-time validation uses RFC 3339 syntax, calendar dates, offsets, and the
bundled list of announced positive leap-second dates. The list is updated in
Ack releases when IERS announces new leap seconds; validation never fetches
data at runtime. Parsing preserves the original string, including its
fractional precision and offset. It does not convert it to a Dart `DateTime`.

Hostname and email domain assertions use the complete IANA IDNA2008
derived-property registry pinned to Unicode 12.0.0, with contextual and Bidi
checks using matching Unicode data. Disallowed and unassigned code points,
including characters assigned after Unicode 12, are rejected after hostname
input mapping. The data is bundled; validation does not fetch it at runtime.

Export retains `format` in imported schemas. External JSON Schema validators may
treat `format` as an annotation unless configured to assert it.

### Supported import subset

| Area | Keywords |
| --- | --- |
| Schemas and types | Boolean schemas, `type` (including lists and `null`) |
| Equality | `enum`, `const`, including nested JSON values and empty enums |
| Objects | `properties`, `required`, boolean/schema `additionalProperties`, `patternProperties`, `propertyNames`, `minProperties`, `maxProperties`, `dependentRequired`, `dependentSchemas`, `unevaluatedProperties` |
| Arrays | Single-schema `items`, `prefixItems`, `contains`, `minContains`, `maxContains`, `minItems`, `maxItems`, `uniqueItems`, `unevaluatedItems` |
| Strings | `minLength`, `maxLength` (Unicode code points), `pattern` (unanchored ECMA-262 search in Unicode mode) |
| Numbers | `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf` (exact decimal division) |
| Composition | `anyOf`, `allOf`, exclusive `oneOf`, `not`, `if`/`then`/`else`; sibling assertions are intersected |
| References | `$ref`, `$id`, `$anchor`, `$defs`, `definitions`, `$dynamicRef`, `$dynamicAnchor`, bundled offline 2020-12 meta-schemas; local/cross-document JSON Pointers and structural recursion |
| 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.

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.

Unknown keywords, including non-`x-*` keywords, are accepted as annotations.
An unsupported vocabulary marked as required (`true`) in `$vocabulary` fails
import with `unsupported_vocabulary`; unsupported optional vocabularies do not.

### References, default Draft 2020-12 export, and Draft-7 lowering

Supply decoded documents by retrieval URI. Relative keys and references resolve
against `baseUri`; nested `$id` values establish new resource scopes. When no
base is provided, the importer uses `ack-import:///root.json`. The importer
never reads files or fetches URLs (standard `https://json-schema.org/draft/2020-12/...`
meta-schemas are bundled offline).

```dart
final AckSchema<Object, Object> schema = Ack.fromJsonSchema(
  {r'$ref': r'types.json#/$defs/message'},
  baseUri: Uri.parse('https://example.com/protocol/root.json'),
  documents: {
    Uri.parse('types.json'): {
      r'$defs': {
        'message': {
          'type': 'object',
          'properties': {'text': {'type': 'string'}},
          'required': ['text'],
        },
      },
    },
  },
);
```

In Ack 2.0, `schema.toJsonSchema()` and `schema.toSchemaModel()` **preserve
imported Draft 2020-12 resources by default** (`$defs`, `$dynamicRef`,
`unevaluatedProperties`, `prefixItems`, etc.). When you need a legacy
self-contained Draft-7 document with root-scoped `definitions` and rewritten
references, call `schema.toJsonSchemaDraft7()` or `schema.toSchemaModelDraft7()`
(which throws `UnsupportedError` if the imported schema relies on 2020-12-only
semantics).

### Generating Dart models from `.schema.json` files

With `ack_generator`, enable the opt-in `ack_generator:ack_json_schema` builder
in `build.yaml` to compile any `lib/**/*.schema.json` Draft 2020-12 asset into
Dart models:

```yaml title="build.yaml"
targets:
  $default:
    builders:
      ack_generator:ack_json_schema:
        enabled: true
        generate_for:
          - lib/**/*.schema.json
        options:
          assert_formats: false
```

`ack_generator:ack_json_schema` emits `<name>.schema.dart` (declaring
`part '<name>.schema.g.dart';`), which `ack_generator:ack_generator` compiles
in the same `dart run build_runner build` pass:

```dart
import 'person.schema.dart';

final person = Person.parse({'name': 'Ada', 'age': 36});
print(person.name);     // String
print(person.toJson()); // {'name': 'Ada', 'age': 36}
```

- **Typed `@Schemable()` models** are emitted for named non-null objects,
  `$ref` definitions, inline objects, string-keyed maps, arrays with non-null
  items, primitives/bounds, string enums, and simple field unions.
- **Validated value models** (wrapping `Ack.fromJsonSchema(...)`) are emitted
  automatically for shapes that Dart classes cannot represent faithfully
  without changing validation semantics (such as regex `pattern` assertions,
  named scalar unions, recursive/dynamic `$dynamicRef` references, `oneOf`/`allOf`/`not`
  composition, `multipleOf`, `unevaluatedProperties`, or `assert_formats: true`).
- For programmatic code generation outside `build_runner`, call
  `generateAckSchemaLibrary()` from `package:ack_generator/ack_generator.dart`.

### Validation errors

When a value fails a keyword of an imported schema, the error is a
`JsonSchemaValidationError`. It names the failing keyword and locates it in the
source schema, so callers do not parse the message:

```dart
final schema = Ack.fromJsonSchema({
  'properties': {
    'tags': {
      'items': {'enum': ['x', 'y']},
    },
  },
});
final error = schema.safeParse({'tags': ['x', 'z']}).getError();
if (error is JsonSchemaValidationError) {
  print(error.keyword); // enum
  print(error.documentUri); // ack-import:///root.json
  print(error.pointer); // #/properties/tags/items/enum
  print(error.keywordLocation); // /properties/tags/items/enum
  print(error.path); // #/tags/1
}
```

`documentUri` and `pointer` follow `$ref` into the referenced document, and
use the same form as `JsonSchemaImportDiagnostic`. The pointer starts at the
document root, also inside a subschema that declares its own `$id`. `keyword`
is empty when the failing subschema is `false`. Only the first failure is
reported. A root `null` that the source schema rejects returns the standard
`SchemaConstraintsError` for a missing value, as other non-nullable Ack schemas
do.

`keywordLocation` is the evaluation path from the root schema to the failing
keyword. It includes each `$ref` it passed through, so two applicators that
share a definition report different locations, while their `pointer` is the
same. It uses the plain JSON Pointer form of the Draft 2020-12
`keywordLocation` output field, with no `#` and no percent-encoding. It is
empty when the root schema is `false`.

### Importing json_schema_builder models

The existing bridge works 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;

final AckSchema<Object, Object> ackSchema =
    jsb.Schema.string(minLength: 2).toAckSchema();
final builderSchema = ackSchema.toJsonSchemaBuilder();
```

`toAckSchema({baseUri, documents, assertFormats})` returns the validator
directly and accepts `Map<Uri, jsb.Schema>` bundles. `toJsonSchemaBuilder()`
preserves imported Draft 2020-12 resources by default; use
`toJsonSchemaBuilderDraft7()` when Draft-7 lowering is required.

### A2UI compatibility and verification

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.

## Generating JSON schemas

Call `toJsonSchema()` on any `AckSchema` instance. This is the same generic Draft-7 renderer used by `schema.toSchemaModel().toJsonSchema()`.

```dart
import 'dart:convert';

import 'package:ack/ack.dart';

enum UserRole { admin, user, guest }

final userSchema = Ack.object({
  'id': Ack.integer().positive().describe('Unique user identifier'),
  'name': Ack.string()
      .minLength(2)
      .maxLength(50)
      .describe("User's full name"),
  'email': Ack.string().email().describe("User's email address"),
  'role': Ack.enumValues(UserRole.values).withDefault(UserRole.user),
  'isActive': Ack.boolean().withDefault(true),
  'tags': Ack.list(Ack.string()).unique().describe('List of user tags').nullable(),
  'age': Ack.integer().min(0).max(120).nullable().describe("User's age"),
}).describe('Represents a user in the system');

void main() {
  // Convert the AckSchema to a JSON Schema Object Map
  final jsonSchemaMap = userSchema.toJsonSchema();

  // Pretty print the JSON representation of the JSON Schema
  final jsonEncoder = JsonEncoder.withIndent('  ');
  print(jsonEncoder.convert(jsonSchemaMap));
}
```

> **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
final model = userSchema.toSchemaModel();
final jsonSchemaMap = model.toJsonSchema();

for (final warning in model.warnings) {
  print('${warning.code}: ${warning.message}');
}
```

`AckSchemaModel` describes the boundary values a schema accepts and exports, keeping adapter metadata such as property ordering and discriminator info. Its JSON Schema renderer emits only generic Draft-7-compatible output; provider-specific hints belong in adapter renderers.

**Output JSON (JSON Schema Object):**

```json
{
  "type": "object",
  "description": "Represents a user in the system",
  "properties": {
    "id": {
      "type": "integer",
      "description": "Unique user identifier",
      "exclusiveMinimum": 0
    },
    "name": {
      "type": "string",
      "description": "User's full name",
      "minLength": 2,
      "maxLength": 50
    },
    "email": {
      "type": "string",
      "format": "email",
      "description": "User's email address"
    },
    "role": {
      "type": "string",
      "enum": [
        "admin",
        "user",
        "guest"
      ],
      "default": "user"
    },
    "isActive": {
      "type": "boolean",
      "default": true
    },
    "tags": {
      "anyOf": [
        {
          "type": "array",
          "description": "List of user tags",
          "items": {
            "type": "string"
          },
          "uniqueItems": true
        },
        {
          "type": "null"
        }
      ]
    },
    "age": {
      "anyOf": [
        {
          "type": "integer",
          "description": "User's age",
          "minimum": 0,
          "maximum": 120
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "required": [
    "id",
    "name",
    "email",
    "role",
    "isActive",
    "tags",
    "age"
  ],
  "additionalProperties": false
}
```

## How constraints map to JSON Schema

Ack maps its [built-in constraints](../core-concepts/validation.mdx) to corresponding JSON Schema keywords:

| 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) | `format: time` | 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)`](../core-concepts/validation.mdx#list-constraints) | `minItems: n` | List (array) |
| [`maxLength(n)`](../core-concepts/validation.mdx#list-constraints) | `maxItems: n` | List (array) |
| [`unique()`](../core-concepts/validation.mdx#list-constraints) | `uniqueItems: true` | List (array) |
| [`nullable()`](../core-concepts/schemas.mdx#optional-vs-nullable) | `anyOf: [<schema>, {type: null}]` | Any schema |
| `withDefault(v)` | `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 |
| [`Ack.string()`](../core-concepts/schemas.mdx#string) | `type: string` | Type |
| [`Ack.boolean()`](../core-concepts/schemas.mdx#boolean) | `type: boolean` | Type |
| [`Ack.list(...)`](../core-concepts/schemas.mdx#list) | `type: array`, `items: {...}` | Type |
| [`Ack.object(...)`](../core-concepts/schemas.mdx#object) | `type: object`, `properties: {...}`, `required: [...]` | Type |
| [`Ack.lazy(...)`](../core-concepts/schemas.mdx#recursive-schemas) | `definitions`, `$ref` | Recursive type |

## 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: [<base-schema>, { "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.

**Limitations:**

-   **Custom Constraints:** [`Constraint<T>` + `Validator<T>`](./custom-validation.mdx)
    instances added via `.constrain()` are **not** translated to JSON Schema
    because there is no standard way to represent arbitrary logic.
-   **`additionalProperties`:** `Ack.object(..., additionalProperties: false)`
    becomes `additionalProperties: false`; `additionalProperties: true` is
    emitted as the boolean `true`.
-   **`Ack.map(valueSchema)`:** Exported as
    `{"type": "object", "additionalProperties": <value schema>}`. Map keys are
    always strings, so no `propertyNames` keyword is emitted.
-   **`Ack.any()`:** Runtime validation accepts non-null JSON-safe values.
    JSON-like adapter exports represent those JSON-compatible values and attach
    an `ack_any_json_boundary` warning to the `AckSchemaModel`.
-   **`Ack.lazy()` runtime checks:** Recursive structure is exported with
    Draft-7 `definitions` / `$ref`. Constraints and refinements added directly
    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
    records schema-model warnings instead of rendering non-standard keywords.
-   **List item nullability:** `Ack.list(...)` does not support nullable item
    schemas yet. Make the list itself nullable with `Ack.list(item).nullable()`
    when the whole field may be null.
-   **Discriminated branches:** `Ack.discriminated(...)` owns the discriminator.
    Branches may omit the discriminator field; compatible `Ack.literal(...)` or
    `Ack.enumString(...)` fields are accepted; generated branches expose the
    exact branch value as `const`.

## Integrating into API documentation

Use the generated JSON Schema map within a larger API documentation structure.

```dart
// Assume you have a function to build the full API spec
Map<String, dynamic> 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));
```

This keeps your validation logic and API documentation in one place.

## Advanced JSON Schema features

### Schema descriptions and metadata

Add descriptions and metadata to your schemas for better documentation:

```dart
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');

final jsonSchema = userSchema.toJsonSchema();
// Output includes description fields
```

### Default values in JSON Schema

Schemas with default values include them in the generated JSON Schema:

```dart
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:

```dart
// 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(),
    }),
  },
);

// Nested arrays and objects
final complexSchema = Ack.object({
  'users': Ack.list(userSchema).minLength(1),
  'metadata': Ack.object({
    'version': Ack.string(),
    'tags': Ack.list(Ack.string()).unique(),
  }).optional(),
});

// All produce valid JSON Schema
final mixedJson = mixedValueSchema.toJsonSchema();
final shapeJson = shapeSchema.toJsonSchema();
final complexJson = complexSchema.toJsonSchema();
```
```

### Adapter Package Quickstart

Source: https://docs.page/btwld/ack/guides/schema-converter-quickstart

```mdx

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.

- 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.
```
