diff --git a/CHANGELOG.md b/CHANGELOG.md index 711b2f07..2a2c2a7c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ See [Conventional Commits](https://conventionalcommits.org) for commit guideline * **Breaking:** Remove the deprecated beta validation annotation aliases and their generic `kind` and `value` getters. Use the Is/Has rule annotations. +* Add the Ack skills plugin for Claude, Codex, and Cursor (#264). + ## 2.0.0-beta.3 * **Breaking:** Require Dart `>=3.13.0` and Flutter `>=3.47.0`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9b24b02c..d98cd5c3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,9 +27,17 @@ dart run melos run analyze dart run melos run test ``` -The full test flow checks the agent skill manifests and compiles the Dart -snippets from Markdown. To run just those checks with Flutter on `PATH`, use -`dart test test/documentation` after bootstrap. +The full test flow checks the agent skill manifests and compiles and exercises +their Dart examples. It also checks every Dart fence in `docs/**/*.mdx` and +`packages/*/README.md`. Public examples compile together, including generated +model parts. The compilation check also runs selected offline assertions. + +Public Dart fences must contain a standalone `main()`, declare a wrapper with +`compile=` after the `dart` fence language, or have a visible +`**Compile check skipped:**` reason immediately before the fence. See +`test/documentation/public_snippet_wrappers.dart` for wrappers and their fixture +context. Run `dart test test/documentation` after bootstrap with Flutter on +`PATH`. For code generation changes, also run: diff --git a/docs/api-reference/index.mdx b/docs/api-reference/index.mdx index 0b0a2545..eea44bfc 100644 --- a/docs/api-reference/index.mdx +++ b/docs/api-reference/index.mdx @@ -88,7 +88,7 @@ Base class for all schema types. `SchemaTransformError` / `SchemaEncodeError`), while programmer `Error` values are rethrown with their original stack trace. - `Runtime? parse(Object? data, {String? debugName})`: Validates `data` and returns the value; throws `AckException` on failure. -- `SchemaResult safeParseAs(Object? data, TOut Function(Runtime?) map, {String? debugName})`: Parses and maps the validated value to `TOut`. Mapper `Exception`s become `SchemaTransformError` failures; mapper `Error` values are rethrown with their original stack trace. +- `SchemaResult safeParseAs(Object? data, TOut? Function(Runtime?) map, {String? debugName})`: Parses and maps the validated value. A mapper that returns `null` produces a successful result with that value. Mapper `Exception`s become `SchemaTransformError` failures. Mapper `Error` values are rethrown with their original stack trace. - `TOut parseAs(Object? data, TOut Function(Runtime?) map, {String? debugName})`: Throwing variant of `safeParseAs`. - `SchemaResult safeEncode(Runtime? value, {String? debugName})`: Encodes a runtime value to the boundary representation, validating nested collection contents. - `Boundary? encode(Runtime? value, {String? debugName})`: Throwing variant of `safeEncode`. @@ -156,7 +156,6 @@ Schema for validating strings. See [String Validation](../core-concepts/validati ### 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) @@ -354,7 +353,7 @@ here. For `Ack.discriminated(...)` constraints, see [Model Code Generation](../core-concepts/typesafe-schemas.mdx#schema-first-unions). **Example:** -```dart +```dart compile=reference-user import 'package:ack/ack.dart'; part 'user.g.dart'; @@ -425,7 +424,7 @@ 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 +```dart compile=reference-account import 'package:ack/ack.dart'; part 'account.g.dart'; @@ -534,7 +533,7 @@ reverse direction. See [Codecs](../core-concepts/codecs.mdx). **Built-in codecs:** -- `Ack.date()` → `CodecSchema` (ISO `YYYY-MM-DD` ↔ local-midnight `DateTime`) +- `Ack.date()` → `CodecSchema` (ISO `YYYY-MM-DD` ↔ local `DateTime(year, month, day)`) - `Ack.datetime()` → `CodecSchema` (ISO 8601 ↔ UTC `DateTime`; leap-second strings are rejected because Dart cannot represent them) @@ -563,7 +562,7 @@ In class-first `@Schemable()` models, use `sealed class JsonMaybe` (`JsonAbse `generateAckSchemaLibrary` returns an `AckJsonSchemaLibrary` containing `source`, `effectiveDocument`, and `widenedPointers`. All parameters are named: - ```dart + ```dart compile=generator-signature AckJsonSchemaLibrary generateAckSchemaLibrary({ required Object? document, required Uri documentUri, diff --git a/docs/core-concepts/codecs.mdx b/docs/core-concepts/codecs.mdx index b9657f4d..605f7b95 100644 --- a/docs/core-concepts/codecs.mdx +++ b/docs/core-concepts/codecs.mdx @@ -4,7 +4,7 @@ title: Codecs 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 +```dart compile=body final when = Ack.datetime(); // CodecSchema final dt = when.parse('2026-01-01T00:00:00Z'); // decode: String -> DateTime @@ -35,7 +35,7 @@ Ack ships codecs for the most common boundary conversions: | `Ack.uri()` | `String` ↔ `Uri` | absolute URI (scheme + host) | | `Ack.duration()` | milliseconds `int` ↔ `Duration` | whole milliseconds | -```dart +```dart compile=body final schema = Ack.object({ 'startsAt': Ack.datetime(), 'website': Ack.uri(), @@ -63,7 +63,7 @@ preserved. Create a codec from any input schema with `Ack.codec(...)`, providing a `decode` function (boundary → runtime) and an `encode` function (runtime → boundary): -```dart +```dart compile=body final csv = Ack.codec>( input: Ack.string(), decode: (s) => s.split(','), @@ -78,7 +78,7 @@ The three type arguments are the boundary type, the input schema's runtime type, Call `.codec(...)` on an existing schema to add a reversible conversion: -```dart +```dart compile=body final trimmed = Ack.string().codec( decode: (s) => s.trim(), encode: (s) => s, @@ -93,14 +93,14 @@ midnight, Dart may construct this value with a later time of day. Use `encode` (throws on failure) or `safeEncode` (returns a `SchemaResult`): -```dart +```dart compile=body final result = Ack.datetime().safeEncode(DateTime.utc(2026)); if (result.isOk) { print(result.getOrThrow()); // 2026-01-01T00:00:00.000Z } ``` -Both methods take a value of the schema's runtime type. During encoding, +Both methods take `Runtime?`. The schema determines whether it accepts `null`. During encoding, schemas validate untyped nested lists and maps, including those produced by `jsonDecode`, and apply the numeric coercions of the relevant schemas. Parse values first when they need a codec's decoder, such as a date-time string that @@ -109,8 +109,10 @@ must become a `DateTime`. 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()`). +- `SchemaEncodeError` — encoding failed, for example through a one-way + `transform`. +- `SchemaValidationError` — a codec runtime rule failed, such as passing a + non-UTC `DateTime` to `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 @@ -127,8 +129,15 @@ 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. +advertise on the input schema. This codec exports `minLength: 5`. + +```dart compile=body +final wireMinimumLength = Ack.string().minLength(5).codec( + decode: (value) => value, + encode: (value) => value, +); +print(wireMinimumLength.toJsonSchema()); +``` `Ack.duration()` is the exception: its boundary is the milliseconds its `min()` and `max()` already compare, so those constraints do export. diff --git a/docs/core-concepts/configuration.mdx b/docs/core-concepts/configuration.mdx index d8d55fe1..4fd1936c 100644 --- a/docs/core-concepts/configuration.mdx +++ b/docs/core-concepts/configuration.mdx @@ -14,7 +14,7 @@ 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 +```dart compile=body Ack.object({ 'id': Ack.integer(), 'nickname': Ack.string().optional(), @@ -30,7 +30,7 @@ presence and nullability matrix. Control how extra fields are handled with the `additionalProperties` parameter in [`Ack.object`](./schemas.mdx#object). -```dart +```dart compile=body // Reject extra properties (default) Ack.object({'id': Ack.integer()}); // or explicitly: @@ -55,14 +55,14 @@ 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 +```dart compile=settings final settingsSchema = Ack.object({ 'theme': Ack.enumString(['light', 'dark']).withDefault('light'), 'pageSize': Ack.integer().min(1).max(100).withDefault(20), }); ``` -```dart +```dart compile=use-settings settingsSchema.parse({}); // {'theme': 'light', 'pageSize': 20} settingsSchema.safeParse({'theme': null}); // fails: theme is not nullable ``` @@ -103,7 +103,7 @@ field is required. Attach a description with `.describe()` when the schema is also used for JSON Schema export or adapter packages. -```dart +```dart compile=library final userIdSchema = Ack.string() .uuid() .describe('Stable identifier for a user account'); @@ -116,7 +116,7 @@ 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 +```dart compile=library final usernameSchema = Ack.string().matches( r'^[a-z0-9_]+$', message: 'Use lowercase letters, numbers, and underscores only.', diff --git a/docs/core-concepts/error-handling.mdx b/docs/core-concepts/error-handling.mdx index 44bc3df7..3300f906 100644 --- a/docs/core-concepts/error-handling.mdx +++ b/docs/core-concepts/error-handling.mdx @@ -18,7 +18,7 @@ When validation fails, you want to know what went wrong and where. `safeParse()` - `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 +```dart compile=body import 'package:ack/ack.dart'; final schema = Ack.string().minLength(5); @@ -60,7 +60,7 @@ the error structure and represents unsupported diagnostic values as strings. A `SchemaContext.operation` is either `SchemaOperation.parse` or `SchemaOperation.encode`. Both values are available from `package:ack/ack.dart`. -```dart +```dart compile=body final userSchema = Ack.object({ 'name': Ack.string(), 'age': Ack.integer().min(18), @@ -100,7 +100,7 @@ Each `SchemaError` subtype carries specific information about why validation fai Raised when the input type doesn't match the expected schema type. -```dart +```dart compile=body final schema = Ack.string(); final result = schema.safeParse(42); // Number instead of string @@ -116,7 +116,7 @@ if (result.isFail) { Raised when the value violates one or more validation constraints (such as `minLength`, `min`, or `email`). -```dart +```dart compile=body final schema = Ack.string().minLength(5).email(); final result = schema.safeParse('abc'); @@ -136,7 +136,7 @@ if (result.isFail) { Raised when validation fails within nested objects or lists. Contains a list of child errors. -```dart +```dart compile=body final schema = Ack.object({ 'name': Ack.string().minLength(2), 'age': Ack.integer().min(0), @@ -163,7 +163,7 @@ if (result.isFail) { Raised when custom validation logic added via `.refine()` fails. -```dart +```dart compile=body final schema = Ack.integer().refine( (value) => value % 2 == 0, message: 'Must be an even number', @@ -183,7 +183,7 @@ 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 +```dart compile=body final schema = Ack.string().transform((value) { final parsed = int.tryParse(value); if (parsed == null) throw FormatException('Not numeric: $value'); @@ -201,7 +201,10 @@ if (result.isFail) { ### `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. +Raised when an encoder cannot turn a runtime value into its boundary form, +such as encoding through a one-way `transform`. Its `kind` identifies the +failure. A codec runtime validation rule produces `SchemaValidationError`. +For example, `Ack.datetime()` rejects a non-UTC `DateTime` with that type. ### Working with error types @@ -209,7 +212,7 @@ Switch exhaustively on `SchemaError` by covering the error types below. When listing the public concrete `AckSchema` types in a switch, include a fallback branch for other implementations, including imported schemas. -```dart +```dart compile=error-data final result = schema.safeParse(data); if (result.isFail) { @@ -236,12 +239,12 @@ if (result.isFail) { In a `TextFormField` validator, return the error string directly: -```dart +```dart compile=field-validator // Inside TextFormField validator validator: (value) { final result = someSchema.safeParse(value); if (result.isFail) { - return result.getError().toString(); + return result.getError().message; } return null; } @@ -253,7 +256,7 @@ validator: (value) { 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 +```dart compile=body final schema = Ack.string().refine( (value) => value.startsWith('ACK_'), message: 'Value must start with ACK_', diff --git a/docs/core-concepts/json-serialization.mdx b/docs/core-concepts/json-serialization.mdx index a50d3c4c..f02273d3 100644 --- a/docs/core-concepts/json-serialization.mdx +++ b/docs/core-concepts/json-serialization.mdx @@ -14,7 +14,7 @@ Validating incoming JSON data involves two steps: 1. **Decode JSON:** Use `dart:convert` to parse the JSON string into a Dart object (usually `Map` or `List`). 2. **Validate:** Pass the decoded object to your [Ack schema](./schemas.mdx)'s `safeParse()` method. -```dart +```dart compile=serialization import 'dart:convert'; import 'package:ack/ack.dart'; @@ -41,7 +41,7 @@ void processApiResponse(String jsonString) { if (result.isOk) { // Structure and types are valid. - final validDataMap = result.getOrThrow(); + final validDataMap = result.getOrThrow()!; print('Valid JSON received: $validDataMap'); // Pass the validated map to your own model layer, @@ -65,11 +65,11 @@ processApiResponse('not valid json'); // Decoding error After successful validation, `result.getOrThrow()` returns a `Map` whose structure and types match your schema. You can work with it directly, pass it into your own model class, or parse it into a generated immutable model: -```dart +```dart compile=serialized-map final result = userSchema.safeParse(jsonData); if (result.isOk) { - final validData = result.getOrThrow(); + final validData = result.getOrThrow()!; // Option 1: Work directly with the validated Map final name = validData['name'] as String; @@ -88,14 +88,14 @@ if (result.isOk) { 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 +```dart compile=serialized-model import 'dart:convert'; final jsonData = jsonDecode('{"name": "Alice", "email": "alice@example.com"}'); final result = User.safeParse(jsonData); if (result.isOk) { - final user = result.getOrThrow(); + final user = result.getOrThrow()!; print(user.name); // typed String print(user.email); // typed String? } @@ -106,7 +106,9 @@ if (result.isOk) { For schemas whose runtime values are already JSON-native (`String`, `num`, `bool`, `List`, `Map`, and `null`), pass the validated value to `jsonEncode`: -```dart +```dart compile=serialized-map +import 'dart:convert'; + final result = userSchema.safeParse({ 'name': 'Alice', 'age': 30, @@ -124,7 +126,9 @@ 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 +```dart compile=body +import 'dart:convert'; + final eventSchema = Ack.object({ 'name': Ack.string(), 'startsAt': Ack.datetime(), diff --git a/docs/core-concepts/schemas.mdx b/docs/core-concepts/schemas.mdx index d6a14991..2bd3a270 100644 --- a/docs/core-concepts/schemas.mdx +++ b/docs/core-concepts/schemas.mdx @@ -4,7 +4,7 @@ title: Schemas A schema describes the shape your data should have. You build one with the `Ack` factory, then validate input against it. This page tours every schema type and how to compose them. -```dart +```dart compile=body import 'package:ack/ack.dart'; // Define schema @@ -22,7 +22,7 @@ final result = userSchema.safeParse({ }); if (result.isOk) { - final validData = result.getOrThrow(); + final validData = result.getOrThrow()!; print('Valid: ${validData['name']}'); } else { print('Error: ${result.getError()}'); @@ -41,7 +41,7 @@ stack can overflow before either configured limit is reached. ### String -```dart +```dart compile=library // Basic string — primitives are strict by default and reject non-string values final nameSchema = Ack.string(); @@ -83,7 +83,7 @@ can be represented exactly as `double` and normalizes them to `double`. an integer schema when values must remain exact in JavaScript's portable integer range. All numeric schemas reject `NaN` and infinities. -```dart +```dart compile=library // Integer validation (42 and 42.0 both parse to int) final ageSchema = Ack.integer() .min(0) @@ -104,13 +104,13 @@ final debtSchema = Ack.double().negative(); // < 0 ### Boolean -```dart +```dart compile=library final isActiveSchema = Ack.boolean(); ``` ### List -```dart +```dart compile=library // List of strings final tagsSchema = Ack.list(Ack.string()); @@ -131,7 +131,7 @@ final usersSchema = Ack.list(Ack.object({ The most common schema type for structured data: -```dart +```dart compile=library final userSchema = Ack.object({ 'name': Ack.string(), 'age': Ack.integer().min(0), @@ -141,7 +141,7 @@ final userSchema = Ack.object({ **Nested objects:** -```dart +```dart compile=nested-object final userSchema = Ack.object({ 'name': Ack.string(), 'address': Ack.object({ @@ -154,11 +154,11 @@ final userSchema = Ack.object({ **Working with validated data:** -```dart +```dart compile=read-nested-object final result = userSchema.safeParse(data); if (result.isOk) { - final validData = result.getOrThrow(); + final validData = result.getOrThrow()!; // Type cast when accessing final name = validData['name'] as String; @@ -171,7 +171,7 @@ if (result.isOk) { Validate against multiple possible schemas: -```dart +```dart compile=library // String or integer — primitive branches are strict, so the union won't // silently coerce one into the other. final idSchema = Ack.anyOf([ @@ -201,7 +201,7 @@ parse/export boundaries. Branch schemas usually omit the discriminator field. Use `Ack.lazy(...)` when a schema needs to refer to itself: -```dart +```dart compile=body late final ObjectSchema categorySchema; categorySchema = Ack.object({ @@ -223,7 +223,7 @@ represented by `$ref`, exported schema models warn that it was omitted. Accepts any non-null JSON-safe value without validation (use sparingly): -```dart +```dart compile=library final flexibleSchema = Ack.object({ 'id': Ack.string(), 'metadata': Ack.any(), // Any non-null JSON-safe value accepted @@ -237,7 +237,7 @@ Use `Ack.any().nullable()` to also accept `null`. Use `Ack.map(...)` for a JSON object with arbitrary string keys whose values all share one schema: -```dart +```dart compile=library final settingsSchema = Ack.object({ 'scores': Ack.map(Ack.integer().min(0)), // string keys, int values 'metadata': Ack.map(Ack.any().nullable()), // a JsonMap @@ -251,54 +251,54 @@ Map values may be `null` only when the value schema is nullable. Use **`.nullable()`** — Field must be present but can be `null`: -```dart +```dart compile=body final userSchema = Ack.object({ 'name': Ack.string(), 'middleName': Ack.string().nullable(), }); // ✅ Valid -{'name': 'John', 'middleName': null} -{'name': 'John', 'middleName': 'Robert'} +userSchema.safeParse({'name': 'John', 'middleName': null}); +userSchema.safeParse({'name': 'John', 'middleName': 'Robert'}); // ❌ Invalid - middleName missing -{'name': 'John'} +userSchema.safeParse({'name': 'John'}); ``` **`.optional()`** — Field can be omitted (but is still validated when present): -```dart +```dart compile=body final userSchema = Ack.object({ 'name': Ack.string(), 'age': Ack.integer().optional(), }); // ✅ Valid -{'name': 'John'} // age omitted -{'name': 'John', 'age': 30} +userSchema.safeParse({'name': 'John'}); // age omitted +userSchema.safeParse({'name': 'John', 'age': 30}); // ❌ Invalid -{'name': 'John', 'age': null} // Use .nullable() if null should be allowed +userSchema.safeParse({'name': 'John', 'age': null}); // Use .nullable() if null should be allowed ``` **Combining both** — Field can be missing or `null`: -```dart +```dart compile=body final userSchema = Ack.object({ 'name': Ack.string(), 'bio': Ack.string().optional().nullable(), }); // All valid: -{'name': 'John'} -{'name': 'John', 'bio': null} -{'name': 'John', 'bio': 'Developer'} +userSchema.safeParse({'name': 'John'}); +userSchema.safeParse({'name': 'John', 'bio': null}); +userSchema.safeParse({'name': 'John', 'bio': 'Developer'}); ``` **`.withDefault(value)`** — A missing field parses as `value`. A present `null` still fails unless the field is nullable: -```dart +```dart compile=body final userSchema = Ack.object({ 'role': Ack.string().withDefault('member'), 'theme': Ack.string().nullable().withDefault('light'), @@ -327,7 +327,7 @@ result to set it explicitly. Add or override properties: -```dart +```dart compile=library final baseSchema = Ack.object({ 'id': Ack.string(), 'name': Ack.string(), @@ -349,7 +349,7 @@ final modifiedSchema = baseSchema.extend({ Select or exclude properties: -```dart +```dart compile=library final fullSchema = Ack.object({ 'id': Ack.string(), 'name': Ack.string(), @@ -369,7 +369,7 @@ final safeSchema = fullSchema.omit(['password']); Make all properties optional: -```dart +```dart compile=body final userSchema = Ack.object({ 'name': Ack.string(), 'email': Ack.string().email(), @@ -391,7 +391,7 @@ By default, objects are **strict** and reject additional properties. #### Using the constructor parameter -```dart +```dart compile=body // Strict mode (default) - rejects additional properties final strictSchema = Ack.object({ 'id': Ack.string(), @@ -411,7 +411,7 @@ flexibleSchema.safeParse({'id': '1', 'name': 'John', 'extra': 'allowed'}); // #### Using extension methods -```dart +```dart compile=body final baseSchema = Ack.object({ 'id': Ack.string(), 'name': Ack.string(), @@ -437,7 +437,7 @@ passthrough.safeParse({'id': '1', 'name': 'John', 'role': 'admin'}); // ✅ Pass Add custom validation logic: -```dart +```dart compile=body // Password confirmation final passwordSchema = Ack.object({ 'password': Ack.string().minLength(8), @@ -474,7 +474,7 @@ final orderSchema = Ack.object({ Transform validated data after parsing: -```dart +```dart compile=body // Transform to uppercase. The callback receives the non-null validated // runtime value; nullable handling happens on the surrounding schema. final upperSchema = Ack.string().transform((s) => s.toUpperCase()); diff --git a/docs/core-concepts/typesafe-schemas.mdx b/docs/core-concepts/typesafe-schemas.mdx index 3e8da1a9..ee38fe3d 100644 --- a/docs/core-concepts/typesafe-schemas.mdx +++ b/docs/core-concepts/typesafe-schemas.mdx @@ -27,7 +27,7 @@ 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 +```dart compile=part-directive part 'models.g.dart'; ``` @@ -42,7 +42,7 @@ dart run build_runner build 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" +```dart title="lib/models.dart" compile=model import 'package:ack/ack.dart'; part 'models.g.dart'; @@ -70,7 +70,7 @@ final class const Account({ After generation, both directions have a typed parsing and JSON boundary: -```dart +```dart compile=model-usage final order = Order.parse({'id': 'o1', 'total': 12.5}); print(order.total); // double @@ -98,7 +98,7 @@ 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 +```dart compile=schema-first-user @Schemable() final userSchema = Ack.object({ 'id': Ack.string().uuid(), @@ -168,7 +168,7 @@ the wire key and choose a different Dart field name. Each branch must be a named `@Schemable()` object schema in the same library: -```dart +```dart compile=schema-first-pet @Schemable() final catSchema = Ack.object({'lives': Ack.integer()}); @@ -191,7 +191,7 @@ 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 +```dart compile=profile @Schemable(caseStyle: AckCaseStyle.snake) final class Profile({ @HasMinLength(2) required final String displayName, @@ -234,7 +234,7 @@ 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 +```dart compile=profile-static-members static final schema = ProfileSchema.schema; static final fromJson = ProfileSchema.fromJson; ``` @@ -249,14 +249,14 @@ Generation rejects a `schema` static whose type produces another class. If a framework specifically requires a factory constructor for `fromJson`, use: -```dart +```dart compile=profile-factory factory Profile.fromJson(Map json) => ProfileSchema.fromJson(json); ``` An explicit function-field type is also valid but normally unnecessary: -```dart +```dart compile=profile-typed-member static final Profile Function(Map) fromJson = ProfileSchema.fromJson; ``` @@ -273,7 +273,7 @@ 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 +```dart compile=task /// Tracks one unit of work. This prose is not exported. @Schemable(description: 'A task the person can complete.') final class const Task({ @@ -296,7 +296,7 @@ generated. A classic constructor works the same and generates identical code. Put the annotations on the fields it initializes: -```dart +```dart compile=classic-profile @Schemable(caseStyle: AckCaseStyle.snake) final class Profile with _$ProfileAck { Profile({ @@ -362,7 +362,7 @@ carries no `default`. `@IsOptional()` alone on `String?` still accepts JSON `null`. Add `@IsNotNull()` when a present value must not be `null`: -```dart +```dart compile=optional-example @Schemable() final class const Example({@IsOptional() @IsNotNull() final String? label}) with _$ExampleAck; @@ -389,7 +389,7 @@ values use the Dart types you already write: Use `JsonMaybe` when a `PATCH` request needs to distinguish an omitted field (`JsonAbsent`) from an explicit `null` (`JsonValue(null)`): -```dart +```dart compile=profile-patch @Schemable() final class const ProfilePatch({ final JsonMaybe bio = const JsonMaybe.absent(), @@ -452,7 +452,7 @@ 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 +```dart compile=section final class Slot { const Slot(this.id); final String id; @@ -475,7 +475,7 @@ The static can be a field or a getter typed `AckSchema`. It works the same on an extension type; declare it `implements Object` so it satisfies the codec's `Object` bound: -```dart +```dart compile=library extension type const WidgetId(String value) implements Object { static final schema = Ack.string().codec( decode: WidgetId.new, @@ -492,7 +492,7 @@ 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 +```dart compile=library final class Command { const Command(this.name); final String name; @@ -514,7 +514,7 @@ 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 +```dart compile=library final class Box { const Box(this.value); final A value; @@ -549,6 +549,8 @@ For a third-party type you cannot edit: in `@Schemable(schemas: [colorSchema])` on the class, union base, or `library;` directive (including an imported shared `library;` directive). +**Compile check skipped:** This example uses an application-specific `Color` library. + ```dart @Schemable(schemas: [colorSchema]) library; @@ -597,7 +599,7 @@ 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 +```dart compile=class-first-pet @Schemable(discriminatorKey: 'type') sealed class const Pet({required final String id}) with _$PetAck; @@ -646,7 +648,7 @@ inputs without validating them. Nested class-first fields compose through the target facade (or `Address.schema` when declared on the class) automatically: -```dart +```dart compile=other-file-order import 'address.dart' as address; @Schemable() @@ -658,11 +660,13 @@ final class const Order({required final address.Address shipping}) Schema-first declarations can use `Address.schema` or the facade explicitly: -```dart +```dart compile=envelope +import 'address.dart' as models; + @Schemable() final envelopeSchema = Ack.object({ - 'address': address.AddressSchema.schema, - 'history': Ack.list(address.AddressSchema.schema), + 'address': models.AddressSchema.schema, + 'history': Ack.list(models.AddressSchema.schema), }); ``` @@ -681,14 +685,14 @@ 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 +```dart compile=library import 'address.dart' show Address; ``` If `Address` does not declare a static `schema`, expose both the hand-written model and its generated facade: -```dart +```dart compile=library import 'address.dart' show Address, AddressSchema; ``` @@ -706,7 +710,7 @@ mutually recursive contracts, use schema-first named `Ack.lazy` schemas. When a `@JsonSerializable()` class holds an Ack model, specify the converters on that field. For an Ack class with an `AccountSchema` facade, use -```dart +```dart compile=json-key-field @JsonKey(fromJson: AccountSchema.fromJson, toJson: AccountSchema.encode) final Account account; ``` diff --git a/docs/core-concepts/validation.mdx b/docs/core-concepts/validation.mdx index 3154e584..e3f81bf0 100644 --- a/docs/core-concepts/validation.mdx +++ b/docs/core-concepts/validation.mdx @@ -22,25 +22,25 @@ and a base letter followed by a combining mark counts as two. ### `minLength(int min)` Requires at least `min` characters. -```dart +```dart compile=expressions Ack.string().minLength(5) ``` ### `maxLength(int max)` Requires at most `max` characters. -```dart +```dart compile=expressions Ack.string().maxLength(100) ``` ### `length(int n)` Requires exactly `n` characters. -```dart +```dart compile=expressions Ack.string().length(10) ``` ### `notEmpty()` Requires a non-empty string. Equivalent to `minLength(1)`. -```dart +```dart compile=expressions Ack.string().notEmpty() ``` @@ -49,7 +49,7 @@ 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 +```dart compile=expressions // Simple alphanumeric pattern (full-string match with anchors) Ack.string().matches(r'^[a-zA-Z0-9]+$') @@ -64,20 +64,20 @@ Ack.string().matches(r'[0-9]+') // Matches "abc123xyz" ⚠️ ### `contains(String substring, {String? example, String? message})` Requires a literal substring. Use `matches` for regular expressions. -```dart +```dart compile=expressions Ack.string().contains('.') // Matches "a.b" Ack.string().matches(r'[A-Z]') // Matches "Password" ``` ### `email()` Requires a valid email address format. -```dart +```dart compile=expressions Ack.string().email() ``` ### `date()` Requires a valid date string in `YYYY-MM-DD` format. -```dart +```dart compile=expressions Ack.string().date() ``` @@ -86,14 +86,15 @@ 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 +```dart compile=expressions Ack.string().datetime() ``` ### `time()` Requires a 24-hour time string in `HH:MM:SS` format with no offset or fractional seconds. JSON Schema export uses a `pattern` for this same rule. -```dart +The constraint key is `string_time`. +```dart compile=expressions Ack.string().time() ``` @@ -101,25 +102,25 @@ Ack.string().time() 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 +```dart compile=expressions Ack.string().uri() ``` ### `uuid()` Requires a valid UUID per RFC 4122. -```dart +```dart compile=expressions Ack.string().uuid() ``` ### `ipv4()` Requires a valid IPv4 address. -```dart +```dart compile=expressions Ack.string().ipv4() ``` ### `ipv6()` Requires a valid IPv6 address. -```dart +```dart compile=expressions Ack.string().ipv6() ``` @@ -127,31 +128,31 @@ Ack.string().ipv6() ### `Ack.enumString(List allowedValues)` An `Ack` factory (not a fluent method) that creates a `StringSchema` accepting only values in `allowedValues`. Use for ad-hoc string lists; prefer `Ack.enumValues(MyEnum.values)` when a Dart enum exists. -```dart +```dart compile=expressions Ack.enumString(['active', 'inactive', 'pending']) ``` ### `Ack.literal(String value)` An `Ack` factory (not a fluent method) that creates a `StringSchema` requiring an exact string match. -```dart +```dart compile=expressions Ack.literal('admin') ``` ### `startsWith(String prefix)` Requires the string to start with `prefix`. -```dart +```dart compile=expressions Ack.string().startsWith('https://') ``` ### `endsWith(String suffix)` Requires the string to end with `suffix`. -```dart +```dart compile=expressions Ack.string().endsWith('.dart') ``` ### `ip({int? version})` Requires a valid IP address. Set `version` to `4` or `6` to restrict the version. -```dart +```dart compile=expressions Ack.string().ip() // Any IP (v4 or v6) Ack.string().ip(version: 4) // IPv4 only Ack.string().ip(version: 6) // IPv6 only @@ -169,21 +170,21 @@ applies to the trimmed text. Keep the native schema for that validation. ### `trim()` Removes leading and trailing whitespace on parse and encode. -```dart +```dart compile=expressions Ack.string().trim().minLength(2) // " hello " → "hello" ``` ### `toLowerCase()` Converts the string to lowercase on parse and encode. -```dart +```dart compile=expressions Ack.string().toLowerCase() // "HELLO" → "hello" ``` ### `toUpperCase()` Converts the string to uppercase on parse and encode. -```dart +```dart compile=expressions Ack.string().toUpperCase() // "hello" → "HELLO" ``` @@ -194,7 +195,7 @@ Apply these to [`Ack.integer()`](./schemas.mdx#number), [`Ack.double()`](./schem ### `min(num limit)` Requires a value `>= limit` (inclusive). -```dart +```dart compile=expressions Ack.integer().min(0) // >= 0 Ack.double().min(0.0) // >= 0.0 Ack.number().min(0) // >= 0 @@ -202,7 +203,7 @@ Ack.number().min(0) // >= 0 ### `max(num limit)` Requires a value `<= limit` (inclusive). -```dart +```dart compile=expressions Ack.integer().max(100) // <= 100 Ack.double().max(100.0) // <= 100.0 Ack.number().max(100) // <= 100 @@ -210,7 +211,7 @@ Ack.number().max(100) // <= 100 ### `greaterThan(num limit)` Requires a value strictly `> limit` (exclusive). -```dart +```dart compile=expressions Ack.integer().greaterThan(0) // > 0 Ack.double().greaterThan(0.0) // > 0.0 Ack.number().greaterThan(0) // > 0 @@ -218,7 +219,7 @@ Ack.number().greaterThan(0) // > 0 ### `lessThan(num limit)` Requires a value strictly `< limit` (exclusive). -```dart +```dart compile=expressions Ack.integer().lessThan(100) // < 100 Ack.double().lessThan(100.0) // < 100.0 Ack.number().lessThan(100) // < 100 @@ -226,7 +227,7 @@ Ack.number().lessThan(100) // < 100 ### `multipleOf(num factor)` Requires a value that is a multiple of `factor`. The check uses exact arithmetic on the decimal representation. Round accumulated floating-point sums or validate integer units such as cents. -```dart +```dart compile=expressions 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) @@ -234,7 +235,7 @@ Ack.number().multipleOf(0.5) ### `positive()` Requires a value greater than 0. -```dart +```dart compile=expressions Ack.integer().positive() // > 0 Ack.double().positive() // > 0.0 Ack.number().positive() // > 0 @@ -242,7 +243,7 @@ Ack.number().positive() // > 0 ### `negative()` Requires a value less than 0. -```dart +```dart compile=expressions Ack.integer().negative() // < 0 Ack.double().negative() // < 0.0 Ack.number().negative() // < 0 @@ -250,15 +251,16 @@ Ack.number().negative() // < 0 ### `safe()` (integer only) Requires an integer within JavaScript's safe range (`-2^53+1` to `2^53-1`). -```dart +The constraint key is `number_safe_integer`. +```dart compile=expressions 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 +explicitness and API symmetry. The constraint key is `number_finite`. +```dart compile=expressions Ack.double().finite() Ack.number().finite() ``` @@ -269,31 +271,32 @@ Apply these to [`Ack.list()`](./schemas.mdx#list) schemas. ### `minItems(int min)` Requires at least `min` items. -```dart +```dart compile=expressions Ack.list(Ack.string()).minItems(1) ``` ### `maxItems(int max)` Requires at most `max` items. -```dart +```dart compile=expressions Ack.list(Ack.integer()).maxItems(10) ``` ### `length(int count)` Requires exactly `count` items. -```dart +```dart compile=expressions Ack.list(Ack.boolean()).length(5) ``` ### `notEmpty()` Requires a non-empty list. Equivalent to `minItems(1)`. -```dart +```dart compile=expressions 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 +The constraint key is `list_unique_items`. +```dart compile=expressions Ack.list(Ack.string()).unique() ``` @@ -312,7 +315,7 @@ rather than being silently coerced. | `Ack.number()` | finite `num` | original `int` or `double` | | `Ack.boolean()` | `bool` | unchanged `bool` | -```dart +```dart compile=body final stringSchema = Ack.string(); stringSchema.safeParse('hello'); // ✅ OK stringSchema.safeParse(123); // ❌ FAIL: TypeMismatchError @@ -343,7 +346,7 @@ 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 +```dart compile=body final stringOrNumber = Ack.anyOf([ Ack.string(), Ack.integer(), @@ -357,7 +360,7 @@ stringOrNumber.safeParse(42); // ✅ Matches integer branch 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 +```dart compile=body // Boundary "true"/"false" string → runtime bool final boolFromString = Ack.enumString(['true', 'false']) .transform((s) => s == 'true'); @@ -373,7 +376,7 @@ Use `schema.codec(decode: ..., encode: ...)` when you also need a reversible You can chain multiple constraints. Ack evaluates them in the order you apply them. -```dart +```dart compile=body final usernameSchema = Ack.string() .minLength(3) // First: check min length .maxLength(20) // Second: check max length diff --git a/docs/getting-started/installation.mdx b/docs/getting-started/installation.mdx index 2d66efc5..76061efc 100644 --- a/docs/getting-started/installation.mdx +++ b/docs/getting-started/installation.mdx @@ -52,7 +52,7 @@ generates an immutable model. `@Schemable()` on a hand-written class generates a public `Schema` facade and JSON helpers. There is no `@AckSchema()` annotation; `AckSchema` is the runtime schema type. -```dart +```dart compile=model import 'package:ack/ack.dart'; part 'user.g.dart'; diff --git a/docs/getting-started/migration-guide.mdx b/docs/getting-started/migration-guide.mdx index b4146ba8..fafbc9cf 100644 --- a/docs/getting-started/migration-guide.mdx +++ b/docs/getting-started/migration-guide.mdx @@ -30,7 +30,7 @@ This guide summarizes **what exists in Ack today**, **what changed in 1.7 and 2. Ack 2.0 uses top-level rule annotations. `Is…` names what a value is; `Has…` names a bound or property it has: -```dart +```dart compile=migration-account @Schemable() final class const Account({ @HasMinLength(2) required final String name, @@ -55,8 +55,8 @@ 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 +release that bundles Dart 3.13.0). Ack 1.7.1 supported Dart 3.9 and +Flutter 3.35. Upgrade to the new floors before moving to Ack 2.0. Class-first examples now use Dart 3.13 primary constructors, with the rule annotations and `@AckKey` on the declaring parameters, as in the `Account` example above. A classic constructor with annotated fields still works and generates identical code, so existing models @@ -111,6 +111,7 @@ Ack is organized into five coordinated packages that share one version number an | **Sealed `SchemaError` & `AckSchema` hierarchies + decoder `Error` propagation** | `2.0.0` | `SchemaError` and `AckSchema` are `sealed class`es. `CodecSchema` rethrows programmer `Error`s (`TypeError`, `StateError`) on `parse`/`safeParse` and catches only `Exception`s as `SchemaTransformError`. | Enables exhaustive `switch (error)` pattern matching without a wildcard branch, and prevents programming bugs inside `decode` callbacks from being masked as user input errors. | | **JSON Schema Draft 2020-12 default + `.schema.json` codegen** | `2.0.0` | `Ack.fromJsonSchema()` supports the full required Draft 2020-12 keyword suite (`$dynamicRef`, `unevaluatedProperties`, `prefixItems`, `minContains`/`maxContains`, `dependentSchemas`, `patternProperties`, and all 19 formats when `assertFormats: true`). `toJsonSchema()` preserves 2020-12 resources by default (`toJsonSchemaDraft7()` lowers to Draft-7). | Enables lossless round-tripping of modern protocol schemas (MCP, A2UI v0.9, OpenAPI 3.1) and compile-time Dart codegen from `.schema.json` files. | | **ECMA-262 Unicode mode (`u`) for imported `pattern`** | `1.7.0` | Imported JSON Schema `pattern` expressions compile with ECMA-262 Unicode semantics. | Required by the JSON Schema specification so `.` matches full Unicode code points (including emoji) and `\p{...}` property escapes work identically to Ajv. | +| **NFKC normalization for international formats** | `2.0.0` | Imported JSON Schema checks for international hostnames and email addresses validate labels as supplied by default. | To restore the earlier behavior, import `nfkc` from `package:unorm_dart` and pass `unicodeNormalizer: nfkc` to `Ack.fromJsonSchema()`. | --- @@ -123,6 +124,7 @@ Ack is organized into five coordinated packages that share one version number an | `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/ack_generator_support.dart';` | `2.0.0` | Use the public APIs in `package:ack/ack.dart` and regenerate model parts. | | `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. | @@ -187,6 +189,9 @@ annotations from `package:ack/ack.dart`. Code that reads a rule’s former | `part 'model.ack.dart';` + `part 'model.ack.g.dart';` | `2.0.0` | Single `part 'model.g.dart';` | | `ack_generator\|ack_models` & `ack_generator\|ack_model_json` in `build.yaml` | `2.0.0` | `ack_generator:ack_generator` (plus optional `ack_generator:ack_json_schema` for `.schema.json` files) | | `@AckType()` `*Type` extension type, `.args`, `ModelType.parse(...)` | `2.0.0` | Generated `Model` class with typed fields, `Model.parse(...)`, `Model.safeParse(...)`, `Model.fromJson(...)`, `model.toJson()` | +| `Ack.preserveBoundary` over other value shapes, or `BoundarySchema` | `2.0.0` | Use `Ack.preserveBoundary` with a JSON object schema. Use the nongeneric `BoundarySchema` type. | +| Subclasses of `Ok`, `Fail`, `AckException`, `ConstraintError`, or `DurationConstraint` | `2.0.0` | These classes are `final`. Compose them or use their public constructors and factories. | +| Implicit defaults for a present null object field | `2.0.0` | Defaults fill omitted keys. Declare `.nullable().withDefault(value)` to accept an explicit null and apply the default on parse. Object encoding uses the default for missing or null defaulted fields. | | `Ack.enumCodec(MyEnum.values)` | `2.0.0` | `Ack.enumValues(MyEnum.values)` | | Draft-7 `dependencies` passed to `Ack.fromJsonSchema` | `2.0.0` | Convert the resource to Draft 2020-12. Use `dependentRequired` for property lists and `dependentSchemas` for schema dependencies. | | Lowering an imported Draft 2020-12 schema that contains `dependencies` to Draft-7 | `2.0.0` | Use `toJsonSchema()` to preserve the original document, or remove the ignored `dependencies` keyword before calling `toJsonSchemaDraft7()`. | @@ -198,7 +203,7 @@ annotations from `package:ack/ack.dart`. Code that reads a rule’s former | Code matching a renamed built-in constraint key | `2.0.0` | `string.startsWith` → `string_starts_with`, `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique_items`, `number.isFinite` → `number_finite`, `integer.isSafe` → `number_safe_integer`, `string_format_time` → `string_time`. | | `AckRule` from `package:ack/annotations.dart` | `2.0.0` | Use the concrete rule annotation type for rule-specific data, or `Object` for a mixed list. | | `implements SchemaContext` | `2.0.0` | Read the context from `SchemaError.context`. `SchemaContext` is a `base` class, so external subclasses require a `base`, `final`, or `sealed` modifier. | -| `SchemaContext.transparent` | `2.0.0` | Ack creates transparent contexts while validating wrapper schemas. Read the resulting context through `SchemaError.context`. | +| `SchemaContext.transparent` | `2.0.0` | Ack uses the internal `createTransparentChild` and `isTransparent` helpers for wrapper contexts. Read the resulting context through `SchemaError.context`. | | `AckSchemaModel.finishTypeJson` or `AckSchemaModel.finishCompositionJson` | `2.0.0` | Render the public model with `toJsonSchema()` and apply any custom JSON Schema keywords to the resulting map. | | UTF-16 code-unit counts in string `minLength`, `maxLength`, and `length` | `2.0.0` | Adjust limits to count Unicode code points. Use a custom refinement based on `String.length` if a protocol measures UTF-16 code units. | | JSON Schema `format: time` from `Ack.string().time()` | `2.0.0` | Read the exported `pattern`. To require RFC 3339 time with an offset, import a schema with `format: time` and pass `assertFormats: true`. | @@ -233,6 +238,8 @@ annotations from `package:ack/ack.dart`. Code that reads a rule’s former ### Class-First Model Migration +**Compile check skipped:** This historical example requires Ack 1.6 and its retired generator. + ```dart // ❌ BEFORE (Ack 1.6) import 'package:ack/ack.dart'; @@ -257,7 +264,7 @@ final class Account with _$AccountAck { } ``` -```dart +```dart compile=model // ✅ AFTER (Ack 2.0) import 'package:ack/ack.dart'; @@ -278,6 +285,8 @@ final class const Account({ ### Schema-First Model Migration +**Compile check skipped:** This historical example requires Ack 1.6 and its retired generator. + ```dart // ❌ BEFORE (Ack 1.6, @AckInfer) import 'package:ack/ack.dart'; @@ -293,7 +302,7 @@ final userSchema = Ack.object({ }); ``` -```dart +```dart compile=model // ✅ AFTER (Ack 2.0) import 'package:ack/ack.dart'; diff --git a/docs/getting-started/quickstart-tutorial.mdx b/docs/getting-started/quickstart-tutorial.mdx index 1331d992..00099c52 100644 --- a/docs/getting-started/quickstart-tutorial.mdx +++ b/docs/getting-started/quickstart-tutorial.mdx @@ -12,7 +12,7 @@ This tutorial validates a Dart map — the kind you get from `jsonDecode()` of a Describe the shape you expect. Fields are required unless you mark them `.optional()`. -```dart +```dart compile=quickstart-schema import 'package:ack/ack.dart'; final userSchema = Ack.object({ @@ -30,7 +30,7 @@ Call `safeParse()` with the data you received — for example 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 +```dart compile=quickstart-parse final result = userSchema.safeParse({'name': 'Alice', 'age': 30}); if (result.isOk) { @@ -66,7 +66,7 @@ void checkResult(SchemaResult result) { if (result.isOk) { print('OK: ${result.getOrThrow()}'); } else { - print(result.getError()); // one JSON Pointer and message per failure + print(result.getError()); // one path: message line per failure } } ``` diff --git a/docs/guides/common-recipes.mdx b/docs/guides/common-recipes.mdx index e106f32e..38f0b23f 100644 --- a/docs/guides/common-recipes.mdx +++ b/docs/guides/common-recipes.mdx @@ -10,7 +10,7 @@ schema pattern you can copy and adapt. Examples assume Validate user credentials with proper constraints: -```dart +```dart compile=body import 'package:ack/ack.dart'; // Email with proper format @@ -48,7 +48,7 @@ if (result.isOk) { Validate nested data structures like addresses: -```dart +```dart compile=library final addressSchema = Ack.object({ 'street': Ack.string().notEmpty(), 'city': Ack.string().notEmpty(), @@ -80,7 +80,7 @@ final result = userWithAddressSchema.safeParse({ Validate lists with constraints on items and length: -```dart +```dart compile=library // Shopping cart with at least 1 item final cartSchema = Ack.object({ 'userId': Ack.string(), @@ -103,7 +103,7 @@ final postSchema = Ack.object({ Validate values against a set of allowed options using Dart enums: -```dart +```dart compile=library enum OrderStatus { pending, processing, shipped, delivered, cancelled } enum Priority { low, medium, high } @@ -125,7 +125,7 @@ final result = orderSchema.safeParse({ Create reusable custom validators for domain-specific rules: -```dart +```dart compile=library import 'package:ack/ack.dart'; // Custom phone number constraint @@ -166,7 +166,7 @@ uses while allowing the rest of GitHub's response to pass through. Add the HTTP client first with `dart pub add http`. -```dart +```dart compile=library import 'dart:convert'; import 'package:ack/ack.dart'; diff --git a/docs/guides/creating-schema-converter-packages.mdx b/docs/guides/creating-schema-converter-packages.mdx index cec8184c..d4734f2d 100644 --- a/docs/guides/creating-schema-converter-packages.mdx +++ b/docs/guides/creating-schema-converter-packages.mdx @@ -27,7 +27,7 @@ codec, default, and discriminator handling in Ack's export layer. If the target accepts Ack's rendered JSON Schema, the conversion can be small: -```dart +```dart compile=target-extension import 'package:ack/ack.dart'; extension TargetJsonSchemaExtension on AckSchema { @@ -84,7 +84,8 @@ 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 +Inspect `model.allWarnings` for warning codes, messages, and JSON Pointer +locations, including in nested nodes and lazy definitions. For example, a default that cannot be exported safely produces a warning. Runtime refinements are not represented in the exported schema; a refinement on `Ack.string()` is omitted without emitting a warning. Decide which warnings the adapter can return to @@ -113,7 +114,7 @@ renderer so definitions and resource identities remain intact. 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 +```dart compile=target-test import 'package:ack/ack.dart'; import 'package:test/test.dart'; diff --git a/docs/guides/custom-validation.mdx b/docs/guides/custom-validation.mdx index b863bcf3..b7f913e3 100644 --- a/docs/guides/custom-validation.mdx +++ b/docs/guides/custom-validation.mdx @@ -12,9 +12,9 @@ While Ack provides many [built-in validation rules](../core-concepts/validation. ## Creating a value constraint -To add reusable validation that only depends on the field value, implement a `Constraint` that mixes in `Validator`. The fluent methods `constrain`, `withConstraint`, and `withConstraints` throw `ArgumentError` if a supplied constraint lacks that validator. +To add reusable validation that only depends on the field value, implement a `Constraint` that mixes in `Validator`. Attach the rule with `constrain()`. It throws `ArgumentError` if the constraint lacks that validator. -```dart +```dart compile=positive-constraint import 'package:ack/ack.dart'; class IsPositiveConstraint extends Constraint with Validator { @@ -41,7 +41,7 @@ print(priceSchema.safeParse(-5.0).isFail); // true When validation depends on multiple fields, use `.refine()` on the parent object schema. -```dart +```dart compile=body final signUpSchema = Ack.object({ 'password': Ack.string().minLength(8), 'confirmPassword': Ack.string().minLength(8), @@ -61,28 +61,21 @@ print(result.isFail); // true The optional `message` parameter on `.constrain()` lets you customize the failure message. -```dart +```dart compile=price-message 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. + print(result.getError().message); // Constraints not met: 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 with Validator { - // ... -} +Move `IsPositiveConstraint` into `validation/constraints.dart` to share it across schemas. +```dart compile=custom-constraint-library // file: schemas/user_schema.dart import 'package:ack/ack.dart'; import '../validation/constraints.dart'; diff --git a/docs/guides/ecosystem-integrations.mdx b/docs/guides/ecosystem-integrations.mdx index f48d6ee8..bd30b6e1 100644 --- a/docs/guides/ecosystem-integrations.mdx +++ b/docs/guides/ecosystem-integrations.mdx @@ -14,7 +14,7 @@ Reuse an `AckSchema` (or a `@Schemable()` model's `Model.schema`) across Ack's o ## 1. Define a Model or Schema Once -```dart title="lib/weather_models.dart" +```dart title="lib/weather_models.dart" compile=model import 'package:ack/ack.dart'; part 'weather_models.g.dart'; @@ -55,7 +55,7 @@ dart pub add ack:^2.0.0-beta.3 ack_mcp_dart:^2.0.0-beta.3 mcp_dart Pass `WeatherQuery.schema` through `input`. The callback receives a `WeatherQuery` and returns a `CallToolResult`; output validation and serialization belong to the callback: -```dart +```dart compile=library import 'dart:convert'; import 'package:ack_mcp_dart/ack_mcp_dart.dart'; @@ -110,7 +110,7 @@ flutter pub add ack:^2.0.0-beta.3 ack_firebase_ai:^2.0.0-beta.3 firebase_ai fire ### Generate and validate structured output -```dart +```dart compile=library import 'dart:convert'; import 'package:ack_firebase_ai/ack_firebase_ai.dart'; diff --git a/docs/guides/flutter-form-validation.mdx b/docs/guides/flutter-form-validation.mdx index 5468cf26..cd650260 100644 --- a/docs/guides/flutter-form-validation.mdx +++ b/docs/guides/flutter-form-validation.mdx @@ -20,9 +20,10 @@ flutter pub add ack:^2.0.0-beta.3 Ack works with Flutter form APIs by running `safeParse` inside `TextFormField.validator` and returning a `String?` error message -(`null` when valid). +(`null` when valid). For example, an invalid email can produce a message that +starts with `Constraints not met: Invalid email format`. -```dart +```dart compile=sign-up import 'package:ack/ack.dart'; import 'package:flutter/material.dart'; @@ -77,7 +78,7 @@ class _SignUpFormState extends State { 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; + return result.isFail ? result.getError().message : null; }, autovalidateMode: AutovalidateMode.onUserInteraction, ), @@ -90,7 +91,7 @@ class _SignUpFormState extends State { keyboardType: TextInputType.emailAddress, validator: (value) { final result = _emailSchema.safeParse(value); - return result.isFail ? result.getError().toString() : null; + return result.isFail ? result.getError().message : null; }, autovalidateMode: AutovalidateMode.onUserInteraction, ), @@ -103,7 +104,7 @@ class _SignUpFormState extends State { obscureText: true, validator: (value) { final result = _passwordSchema.safeParse(value); - return result.isFail ? result.getError().toString() : null; + return result.isFail ? result.getError().message : null; }, autovalidateMode: AutovalidateMode.onUserInteraction, ), @@ -146,13 +147,13 @@ class _SignUpFormState extends State { } ``` -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). +Key steps: define an `AckSchema` per field; in `TextFormField.validator`, call `schema.safeParse(value)` and return `result.getError().message` on failure; trigger full-form validation via `_formKey.currentState!.validate()`; set `autovalidateMode: AutovalidateMode.onUserInteraction` for real-time feedback. Pass `message:` inside the schema definition for [custom error messages](../core-concepts/error-handling.mdx#custom-error-messages). ## Real-time validation with `TextField` Without a `Form` widget, listen to controller changes and update the error state directly. -```dart +```dart compile=library import 'package:ack/ack.dart'; import 'package:flutter/material.dart'; @@ -187,7 +188,7 @@ class _RealtimeValidationFieldState extends State { final result = _emailSchema.safeParse(text); // Update the error state variable, triggering a rebuild setState(() { - _emailErrorText = result.isFail ? result.getError().toString() : null; + _emailErrorText = result.isFail ? result.getError().message : null; }); } else { // Clear error if field becomes empty @@ -228,9 +229,9 @@ Key steps: hold a state variable for the error message; add a listener to `TextE Instead of validating field by field, validate the complete data structure on submission using [`Ack.object`](../core-concepts/schemas.mdx#object). -```dart +```dart compile=form-submission // Define a schema for the whole form data -final _formSchema = Ack.object({ +late final _formSchema = Ack.object({ 'username': _usernameSchema, // Reuse field schemas 'email': _emailSchema, 'password': _passwordSchema, @@ -258,7 +259,7 @@ void _submitForm() { // Submit formData } else { final error = result.getError(); - print('Form submission error: $error'); + print(error); // One path: message line per failure // You might need to map the error path back to specific fields // to display errors if not using TextFormField validators. } diff --git a/docs/guides/json-schema-integration.mdx b/docs/guides/json-schema-integration.mdx index b6673780..6c7acf45 100644 --- a/docs/guides/json-schema-integration.mdx +++ b/docs/guides/json-schema-integration.mdx @@ -5,7 +5,9 @@ title: JSON Schema Integration Your Ack [schema](../core-concepts/schemas.mdx) already describes your data's shape — so you can import and export JSON Schema (preserving Draft 2020-12 resources for imported schemas and emitting Draft-7 for native schemas) and reuse it to document an API, drive a form library, or define an LLM tool, all from one source of truth. Draft-7 imports reject the `dependencies` keyword. Convert the schema to Draft -2020-12 and use `dependentRequired` or `dependentSchemas`. +2020-12 and use `dependentRequired` or `dependentSchemas`. Draft-7 lowering +also rejects `dependencies` in imported 2020-12 schemas and reports the +keyword’s JSON Pointer. Imported schemas share the parse input limit of 100 nested lists or maps along any path. @@ -33,7 +35,7 @@ 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 +```dart compile=body import 'package:ack/ack.dart'; final AckSchema schema = Ack.fromJsonSchema({ @@ -67,7 +69,7 @@ exporter or dependency on a Flutter runtime. You can import an existing export directly: -```dart +```dart compile=library final document = Ack.object({'name': Ack.string()}).toJsonSchema(); final AckSchema schema = Ack.fromJsonSchema(document); final exportedAgain = schema.toJsonSchema(); @@ -78,7 +80,8 @@ The source document and executable validator are distinct. 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. +Import rejects unsupported assertions it recognizes. Unrecognized keywords +are retained as annotations. ### Importing `format` @@ -92,7 +95,7 @@ Draft 2020-12 format suite (`date-time`, `date`, `time`, `duration`, `email`, `relative-json-pointer`, `regex`) as well as standard numeric format bounds (`int32`, `int64`, `uint32`, `uint64`, `float`, `double`): -```dart +```dart compile=body final timestamp = Ack.fromJsonSchema( {'type': 'string', 'format': 'date-time'}, assertFormats: true, @@ -120,7 +123,7 @@ forms such as full-width letters. Ack lowercases ASCII letters only. After normalization, non-ASCII uppercase letters disallowed by IDNA2008 are rejected. With `unorm.nfkc`, `EXAMPLE.com` passes and `MÜNCHEN.de` fails. -```dart +```dart compile=body import 'package:unorm_dart/unorm_dart.dart' as unorm; final host = Ack.fromJsonSchema( @@ -186,7 +189,7 @@ 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 +```dart compile=library final AckSchema schema = Ack.fromJsonSchema( {r'$ref': r'types.json#/$defs/message'}, baseUri: Uri.parse('https://example.com/protocol/root.json'), @@ -241,7 +244,7 @@ to the consuming package's runtime `dependencies` with `part '.schema.g.dart';`), which `ack_generator:ack_generator` compiles in the same `dart run build_runner build` pass: -```dart +```dart compile=person-schema import 'person.schema.dart'; final person = Person.parse({'name': 'Ada', 'age': 36}); @@ -266,7 +269,7 @@ 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 +```dart compile=body final schema = Ack.fromJsonSchema({ 'properties': { 'tags': { @@ -303,7 +306,7 @@ empty when the root schema is `false`. The existing bridge works in both directions: -```dart +```dart compile=library import 'package:ack/ack.dart'; import 'package:ack_json_schema_builder/ack_json_schema_builder.dart'; import 'package:json_schema_builder/json_schema_builder.dart' as jsb; @@ -313,10 +316,12 @@ final AckSchema ackSchema = final builderSchema = ackSchema.toJsonSchemaBuilder(); ``` -`toAckSchema({baseUri, documents, assertFormats})` returns the validator -directly and accepts `Map` bundles. `toJsonSchemaBuilder()` -preserves imported Draft 2020-12 resources by default; use -`toJsonSchemaBuilderDraft7()` when Draft-7 lowering is required. +`toAckSchema({baseUri, documents, assertFormats, unicodeNormalizer})` returns +the validator directly and accepts `Map` bundles. Pass +`unicodeNormalizer: unorm.nfkc` from `package:unorm_dart` to opt in to +[NFKC normalization](#importing-format) for international format checks. +`toJsonSchemaBuilder()` preserves imported Draft 2020-12 resources by default. +Use `toJsonSchemaBuilderDraft7()` when Draft-7 lowering is required. ### A2UI compatibility and verification @@ -328,9 +333,9 @@ 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()`. +Call `toJsonSchema()` on any `AckSchema` instance. This uses the same renderer as `schema.toSchemaModel().toJsonSchema()`. Native schemas emit Draft-7 and imported schemas preserve their resources. -```dart +```dart compile=schema-export import 'dart:convert'; import 'package:ack/ack.dart'; @@ -371,7 +376,7 @@ void main() { Use `toSchemaModel()` for a reusable, target-independent view of an Ack schema: -```dart +```dart compile=exported-model final model = userSchema.toSchemaModel(); final jsonSchemaMap = model.toJsonSchema(); @@ -387,29 +392,31 @@ fragment JSON Pointers like `#` and `#/anyOf/0/properties/a~1b`, using RFC 6901 token escaping without percent-encoding. It rebases any supplied `#`-prefixed path to the warning's node and passes other paths through unchanged. -`AckSchemaModel` describes the boundary values a schema accepts and exports, keeping adapter metadata such as property ordering and discriminator info. Its JSON Schema renderer emits only generic Draft-7-compatible output; provider-specific hints belong in adapter renderers. +`AckSchemaModel` describes the boundary values a schema accepts and exports, keeping adapter metadata such as property ordering and discriminator info. Native models render as Draft-7-compatible JSON Schema. Imported models +preserve supported Draft 2020-12 resources. Adapter renderers add +provider-specific hints. **Output JSON (JSON Schema Object):** ```json { "type": "object", - "description": "Represents a user in the system", "properties": { "id": { "type": "integer", - "description": "Unique user identifier", - "exclusiveMinimum": 0 + "exclusiveMinimum": 0, + "description": "Unique user identifier" }, "name": { "type": "string", - "description": "User's full name", "minLength": 2, - "maxLength": 50 + "maxLength": 50, + "description": "User's full name" }, "email": { "type": "string", "format": "email", + "pattern": "^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$", "description": "User's email address" }, "role": { @@ -426,10 +433,10 @@ token escaping without percent-encoding. It rebases any supplied "default": true }, "tags": { + "description": "List of user tags", "anyOf": [ { "type": "array", - "description": "List of user tags", "items": { "type": "string" }, @@ -441,10 +448,10 @@ token escaping without percent-encoding. It rebases any supplied ] }, "age": { + "description": "User's age", "anyOf": [ { "type": "integer", - "description": "User's age", "minimum": 0, "maximum": 120 }, @@ -458,12 +465,11 @@ token escaping without percent-encoding. It rebases any supplied "id", "name", "email", - "role", - "isActive", "tags", "age" ], - "additionalProperties": false + "additionalProperties": false, + "description": "Represents a user in the system" } ``` @@ -479,7 +485,7 @@ Ack maps its [built-in constraints](../core-concepts/validation.mdx) to correspo | [`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 | +| [`time()`](../core-concepts/validation.mdx#string-constraints) | `pattern: ^(?:[01][0-9]\|2[0-3]):[0-5][0-9]:[0-5][0-9]$` | String | | [`uri()`](../core-concepts/validation.mdx#string-constraints) | `format: uri` | String | | [`uuid()`](../core-concepts/validation.mdx#string-constraints) | `format: uuid` | String | | [`ipv4()`](../core-concepts/validation.mdx#string-constraints) | `format: ipv4` | String | @@ -490,8 +496,8 @@ Ack maps its [built-in constraints](../core-concepts/validation.mdx) to correspo | [`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) | +| [`minItems(n)`](../core-concepts/validation.mdx#list-constraints) | `minItems: n` | List (array) | +| [`maxItems(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: [, {type: null}]` | Any schema | | `withDefault(v)` | `default: v` | JSON/export-safe defaults only in `AckSchemaModel`; unsupported defaults are omitted with a warning | @@ -583,7 +589,7 @@ The nested nullable-union shape is intentional for generic Draft-7 output and ma Use the generated JSON Schema map within a larger API documentation structure. -```dart +```dart compile=api-specification // Assume you have a function to build the full API spec Map buildApiSpecification() { final userJsonSchema = userSchema.toJsonSchema(); @@ -626,7 +632,7 @@ This keeps your validation logic and API documentation in one place. Add descriptions and metadata to your schemas for better documentation: -```dart +```dart compile=library final userSchema = Ack.object({ 'id': Ack.string().uuid().describe('Unique user identifier'), 'name': Ack.string().minLength(1).describe('User\'s full name'), @@ -642,7 +648,7 @@ final jsonSchema = userSchema.toJsonSchema(); Schemas with default values include them in the generated JSON Schema: -```dart +```dart compile=library enum Theme { light, dark } final configSchema = Ack.object({ @@ -659,7 +665,7 @@ final jsonSchema = configSchema.toJsonSchema(); JSON Schema generation works with all Ack schema types: -```dart +```dart compile=complex-schema // Union types final mixedValueSchema = Ack.anyOf([ Ack.string(), diff --git a/docs/index.mdx b/docs/index.mdx index ecf6b42b..d5845ce0 100644 --- a/docs/index.mdx +++ b/docs/index.mdx @@ -6,7 +6,7 @@ External data can't be trusted. APIs change, users mistype, and JSON drifts from ("Ack" is short for "acknowledgment.") -```dart +```dart compile=body import 'package:ack/ack.dart'; final userSchema = Ack.object({ diff --git a/packages/ack/CHANGELOG.md b/packages/ack/CHANGELOG.md index ee299ad6..a83da9a2 100644 --- a/packages/ack/CHANGELOG.md +++ b/packages/ack/CHANGELOG.md @@ -1,5 +1,9 @@ ## Unreleased +* Document the stable URI, list, string length, date codec, constraint error, + and JSON Schema export behavior in the guides and agent skills. +* List the MCP adapter among the related packages. + ### Breaking * **Breaking:** The public `AckRawSchemaModel` constructor no longer accepts @@ -136,6 +140,23 @@ ### Fixed +* Document the 1.x migration for boundary schemas, final types, defaults, + and the new Dart and Flutter SDK floors. + +* Show the root schema error name and JSON Pointer in the error-handling guide. + +* Compile public Dart examples and correct nullable result access. +* Check every public Dart fence and correct examples for optional fields, JSON + encoding, custom constraints, nested models, and Flutter form submission. + +* Show the actual JSON Schema export and explain unknown keyword handling. + +* Use a validation error’s message as Flutter form error text. + +* Show field-level validation output in the quickstart and package example. + +* Document that a non-UTC datetime fails with `SchemaValidationError`. + * Collect nested JSON Schema export warnings with JSON Pointers through `AckSchemaModel.allWarnings`, including warnings from nullable branches and lazy definitions. diff --git a/packages/ack/README.md b/packages/ack/README.md index 93772a74..5558eaaf 100644 --- a/packages/ack/README.md +++ b/packages/ack/README.md @@ -21,7 +21,7 @@ Ack is a schema validation library for Dart and Flutter that helps you validate dart pub add ack:^2.0.0-beta.3 ``` -```dart +```dart compile=body import 'package:ack/ack.dart'; // Define a schema for a user object @@ -42,8 +42,7 @@ if (result.isOk) { final validData = result.getOrThrow(); print('Valid user: $validData'); } else { - final error = result.getError(); - print('Validation failed: $error'); + print(result.getError()); // One path: message line per failure } ``` @@ -53,7 +52,7 @@ Use `.optional()` when a field may be omitted entirely. Chain `.nullable()` if a Import a decoded draft 2020-12 schema without re-declaring it in Dart: -```dart +```dart compile=body import 'package:ack/ack.dart'; final AckSchema schema = Ack.fromJsonSchema({ @@ -88,3 +87,4 @@ for the supported subset, recursive bundles, and round-trip guarantees. - [ack_generator](https://pub.dev/packages/ack_generator) — Generates models from `@Schemable()` schemas and schemas from `@Schemable()` classes - [ack_firebase_ai](https://pub.dev/packages/ack_firebase_ai) — Firebase AI (Gemini) schema converter - [ack_json_schema_builder](https://pub.dev/packages/ack_json_schema_builder) — bidirectional JSON Schema bridge +- [ack_mcp_dart](https://pub.dev/packages/ack_mcp_dart) — MCP tool schemas and typed argument validation diff --git a/packages/ack_firebase_ai/README.md b/packages/ack_firebase_ai/README.md index 8872eef5..04762b3c 100644 --- a/packages/ack_firebase_ai/README.md +++ b/packages/ack_firebase_ai/README.md @@ -114,7 +114,7 @@ as model guidance and ACK validation as the authoritative runtime check. discriminator property; the schema model injects an exact `const` discriminator into each branch export. -```dart +```dart compile=firebase-shape final shapeSchema = Ack.discriminated>( discriminatorKey: 'type', schemas: { diff --git a/packages/ack_generator/CHANGELOG.md b/packages/ack_generator/CHANGELOG.md index 7183a465..9d10f7ca 100644 --- a/packages/ack_generator/CHANGELOG.md +++ b/packages/ack_generator/CHANGELOG.md @@ -56,6 +56,10 @@ ### Changed +* Clarify that generated string length rules count Unicode code points. +* Correct the import prefix in the nested schema-first model example. +* Document the generator installation command for Ack projects. + * Use the canonical Ack list constraint names in generator fixtures. * Expand support to Analyzer 14.x and build 5.x. The generator can resolve with Freezed 4.0.3 and build_runner 2.17.1. diff --git a/packages/ack_generator/README.md b/packages/ack_generator/README.md index 4d86e74f..6abc8e60 100644 --- a/packages/ack_generator/README.md +++ b/packages/ack_generator/README.md @@ -10,6 +10,12 @@ The generator supports Analyzer 13.3.0 through 14.x and build 4.x through 5.x. When keeping build_runner 2.16, use a compatible Analyzer 13.x release from 13.3.0 onward. Use build_runner 2.17 or later with Analyzer 14.x. +## Installation + +```sh +dart pub add ack:^2.0.0-beta.3 dev:ack_generator:^2.0.0-beta.3 dev:build_runner +``` + ## Generate models from JSON Schema The opt-in `ack_json_schema` builder turns a draft 2020-12 JSON Schema into @@ -93,15 +99,13 @@ Validated wrappers do not expose inferred fields or typed `copyWith`. An integral JSON number beyond Dart's `int` range is a known edge case: `Ack.fromJsonSchema` can accept it as an integral `double`, while a typed -`Ack.integer()` model cannot represent it as an `int`. String length bounds also -differ for astral Unicode characters (code points in the importer versus UTF-16 -units in the fluent schema). Set `model_mode: validated` when these edge cases -matter; typed output follows the fluent `Ack.integer()` and `Ack.string()` -semantics. +`Ack.integer()` model cannot represent it as an `int`. Set +`model_mode: validated` when that numeric edge case matters. String length +bounds count Unicode code points in both typed output and imported schemas. ## Schema-first usage -```dart +```dart compile=model import 'package:ack/ack.dart'; part 'user_schema.g.dart'; @@ -116,7 +120,7 @@ final userSchema = Ack.object({ Run `dart run build_runner build`. A declaration ending in `Schema` loses that suffix, so `userSchema` generates `User`: -```dart +```dart compile=readme-user-parse void main() { final user = User.parse({ 'name': 'Ada', @@ -131,7 +135,7 @@ void main() { `User.schema` is the model-valued schema: it parses input into `User` and encodes a `User` back, so it composes like any other Ack schema: -```dart +```dart compile=readme-user-list final users = Ack.list(User.schema).parse(json)!; // List ``` @@ -154,7 +158,7 @@ names must be unchanged UpperCamelCase identifiers. In a class-first library, keep the model in source (using a standard or Dart 3.13+ primary constructor) and apply the generated mixin: -```dart +```dart compile=model import 'package:ack/ack.dart'; part 'account.g.dart'; @@ -170,7 +174,7 @@ final class const Account({@HasMinLength(2) required final String name}) After generation, `Account.schema`, the public `AccountSchema` facade, and model JSON methods all use the same Ack codec boundary: -```dart +```dart compile=readme-account void main() { final account = Account.fromJson({'name': 'Ada'}); print(account.toJson()); @@ -185,7 +189,7 @@ A field whose values are native JSON needs no wrapper. `Ack.any()` and an booleans, `Ack.any()`, inline objects, and lists, maps, unions, or lazy schemas of those) become `Object` fields, including as list items and map values: -```dart +```dart compile=readme-answer final answerValue = Ack.anyOf([ Ack.string(), Ack.number(), Ack.list(Ack.string()), ]); @@ -299,7 +303,7 @@ wrap such a schema as a value model. Every annotated library declares a single `.g.dart` part: -```dart +```dart compile=part-directive part 'account.g.dart'; ``` diff --git a/packages/ack_generator/test/integration/model_generation_guide_build_test.dart b/packages/ack_generator/test/integration/model_generation_guide_build_test.dart index e29eaf08..a4fd2157 100644 --- a/packages/ack_generator/test/integration/model_generation_guide_build_test.dart +++ b/packages/ack_generator/test/integration/model_generation_guide_build_test.dart @@ -38,14 +38,18 @@ void main() { 'typesafe-schemas.mdx', ), ).readAsStringSync(); - final sample = RegExp(r'```dart title="lib/models.dart"\n([\s\S]*?)\n```') - .firstMatch(guide) - ?.group(1); + // Select the titled Dart fence even when its info string has other metadata. + final samples = RegExp( + r'^ *```dart(?:[ \t]+[^\r\n]*)?[ \t]+title="lib/models\.dart"' + r'(?:[ \t]+[^\r\n]*)?\r?\n([\s\S]*?)\r?\n *```[ \t]*\r?$', + multiLine: true, + ).allMatches(guide); expect( - sample, - isNotNull, - reason: 'The guide must contain its canonical lib/models.dart sample.', + samples, + hasLength(1), + reason: 'The guide must contain one canonical lib/models.dart sample.', ); + final sample = samples.single[1]!; final temporary = await Directory.systemTemp.createTemp( 'ack_model_generation_guide_', @@ -71,7 +75,7 @@ dependency_overrides: path: ${p.join(projectRoot.path, 'packages', 'ack')} '''); File(p.join(temporary.path, 'lib', 'models.dart')) - .writeAsStringSync(sample!); + .writeAsStringSync(sample); File(p.join(temporary.path, 'test', 'models_test.dart')) .writeAsStringSync(r''' import 'package:ack_model_generation_guide/models.dart'; diff --git a/packages/ack_json_schema_builder/CHANGELOG.md b/packages/ack_json_schema_builder/CHANGELOG.md index 50c2d670..4b111f07 100644 --- a/packages/ack_json_schema_builder/CHANGELOG.md +++ b/packages/ack_json_schema_builder/CHANGELOG.md @@ -7,6 +7,13 @@ ### Changed +* Document the optional NFKC normalizer for builder model imports. +* Document `minItems` and `maxItems` for list length rules in the bridge README. +* Document the target dependency range and how converter exports handle + custom refinements. + +* Import the target validation extension in the README example. + * Use `minItems` and `maxItems` in the list conversion example. * Forward `unicodeNormalizer` from `toAckSchema` to Ack’s JSON Schema diff --git a/packages/ack_json_schema_builder/README.md b/packages/ack_json_schema_builder/README.md index 4332e93d..67e2176d 100644 --- a/packages/ack_json_schema_builder/README.md +++ b/packages/ack_json_schema_builder/README.md @@ -11,7 +11,7 @@ and imports builder models via `.toAckSchema()`. ## Importing a schema -```dart +```dart compile=library import 'package:ack/ack.dart'; import 'package:ack_json_schema_builder/ack_json_schema_builder.dart'; import 'package:json_schema_builder/json_schema_builder.dart' as jsb; @@ -61,7 +61,7 @@ dependencies: ### Compatibility Requires `ack: ^2.0.0-beta.2` and -`json_schema_builder: >=0.1.3 <1.0.0` as peer dependencies. Report +`json_schema_builder: ^0.1.3` as peer dependencies. Report [compatibility issues](https://github.com/btwld/ack/issues). ## Conversion Model @@ -84,21 +84,17 @@ metadata, composition, and discriminated-union branches follow **Read this first** - json_schema_builder schema conversion has important constraints: -### Custom Refinements Not Supported +### Custom refinements -Custom validation logic cannot be expressed in JSON Schema format. +Conversion succeeds and omits custom refinements from the generated JSON +Schema. Validate data with the original Ack schema when those rules matter. -```dart -// Cannot convert +```dart compile=builder-data final schema = Ack.string().refine((s) => s.startsWith('ACK_')); - -// Validate with ACK schema instead +final jsonSchema = schema.toJsonSchemaBuilder(); final result = schema.safeParse(data); ``` -ACK still remains the authoritative runtime validator for refinements and -other logic that JSON Schema cannot represent. - ### Target Schema Support The converter uses `AckSchema.toJsonSchema()` before constructing the @@ -108,19 +104,21 @@ schema into legacy Draft-7 `definitions`, call `schema.toJsonSchemaBuilderDraft7()`. If a downstream validator or consumer ignores a JSON Schema keyword, validate with ACK after parsing. -```dart +```dart compile=builder-library final schema = Ack.date().min(DateTime(2026)); final jsonSchema = schema.toJsonSchemaBuilder(); // Includes format: date. ``` -`Ack.date()` uses local-midnight `DateTime` values at runtime. Use -`DateTime.utc(...)` with `Ack.datetime()`, whose runtime invariant is UTC. +`Ack.date()` uses the local value returned by `DateTime(year, month, day)`. +That value can be later than midnight on a day with a time zone transition. +Use `DateTime.utc(...)` with `Ack.datetime()`, which requires UTC. ## Usage -```dart +```dart compile=builder-validate 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'; // 1. Define schema final userSchema = Ack.object({ @@ -161,7 +159,8 @@ if (errors.isEmpty) { | ACK Constraint | json_schema_builder | Notes | |----------------|---------------------|-------| -| `.minLength()` / `.maxLength()` | `minLength` / `maxLength` | String and array support | +| `.minLength()` / `.maxLength()` | `minLength` / `maxLength` | Strings | +| `.minItems()` / `.maxItems()` | `minItems` / `maxItems` | Arrays | | `.min()` / `.max()` | `minimum` / `maximum` | Numeric bounds | | `.email()` / `.uuid()` / `.uri()` | `format` | Format hints | | `.optional()` | Excluded from `required` | Optional fields | diff --git a/packages/ack_mcp_dart/CHANGELOG.md b/packages/ack_mcp_dart/CHANGELOG.md index aa59d678..825d2e2e 100644 --- a/packages/ack_mcp_dart/CHANGELOG.md +++ b/packages/ack_mcp_dart/CHANGELOG.md @@ -1,9 +1,18 @@ ## Unreleased +### Breaking + * **Breaking:** Read the original parsing exception through `SchemaError.cause` in custom invalid-argument handlers. The built-in codec message no longer includes exception details. +### Changed + +* Add the MCP topic to the pub.dev package metadata. + +* Identify discriminated tool roots as `anyOf` and document output schemas + registered directly with `mcp_dart`. + ## 2.0.0-beta.3 ### Breaking diff --git a/packages/ack_mcp_dart/README.md b/packages/ack_mcp_dart/README.md index afe6937e..90ca8aa8 100644 --- a/packages/ack_mcp_dart/README.md +++ b/packages/ack_mcp_dart/README.md @@ -22,7 +22,7 @@ dependencies: ## Register a tool -```dart +```dart compile=search-tool import 'package:ack/ack.dart'; import 'package:ack_mcp_dart/ack_mcp_dart.dart'; import 'package:mcp_dart/mcp_dart.dart'; @@ -68,7 +68,7 @@ The model is constructed after ACK parses defaults and codecs. Apps that own registration can use the helpers independently: -```dart +```dart compile=raw-search-tool server.registerTool( 'search', inputSchema: searchInput.toMcpToolInputSchema(), @@ -155,7 +155,7 @@ New emitted keywords require revisiting this dialect assumption. | Nullable or discriminated root | Rejected at registration; renders as composition (`anyOf` in ACK) | | Primitive, list, or other composition root | Rejected at registration | | Nullable, union, discriminated, recursive, or codec **fields** | Supported inside an object | -| Output schemas | Out of scope | +| Output schemas | Declare them directly with `mcp_dart` | | Transport and session controls | Use `mcp_dart` directly | ## Runnable example diff --git a/packages/ack_mcp_dart/lib/ack_mcp_dart.dart b/packages/ack_mcp_dart/lib/ack_mcp_dart.dart index 25ae809b..a10d761e 100644 --- a/packages/ack_mcp_dart/lib/ack_mcp_dart.dart +++ b/packages/ack_mcp_dart/lib/ack_mcp_dart.dart @@ -18,9 +18,9 @@ extension AckMcpToolInputSchema on AckSchema { final json = toJsonSchema(); if (json['type'] != 'object') { final shape = json.containsKey('anyOf') - ? 'anyOf (nullable or union root)' + ? 'anyOf (nullable or union root, including discriminated schemas)' : json.containsKey('oneOf') - ? 'oneOf (discriminated root)' + ? 'oneOf (composition root)' : json['type'] ?? json.keys.join(', '); throw ArgumentError( 'MCP tool input must render as type: object; root renders as $shape.', diff --git a/packages/ack_mcp_dart/pubspec.yaml b/packages/ack_mcp_dart/pubspec.yaml index d5bafa39..78f1bc98 100644 --- a/packages/ack_mcp_dart/pubspec.yaml +++ b/packages/ack_mcp_dart/pubspec.yaml @@ -5,6 +5,7 @@ repository: https://github.com/btwld/ack issue_tracker: https://github.com/btwld/ack/issues resolution: workspace topics: + - mcp - json-schema - schema - validation diff --git a/plugins/ack/skills/ack-provider-schemas/SKILL.md b/plugins/ack/skills/ack-provider-schemas/SKILL.md index c80561c6..1eae707f 100644 --- a/plugins/ack/skills/ack-provider-schemas/SKILL.md +++ b/plugins/ack/skills/ack-provider-schemas/SKILL.md @@ -25,9 +25,9 @@ So every payload coming in from a provider or client goes through `safeParse` on - Gemini API over REST or another SDK, with function declarations or a response schema: [references/gemini-api.md](references/gemini-api.md) Done when you have read the matching reference. -2. **Shape the schema for the provider.** The root is an `Ack.object` (tools and function parameters require an object root, and a discriminated or nullable root exports as `anyOf`). Keep it focused, because schema size costs input tokens. Add `.describe(...)` or `/// @description` on fields the model has to fill in. A `@Schemable` class's `Model.schema` works anywhere a schema does. Done when `schema.toJsonSchema()['type'] == 'object'`, you have reviewed warnings from all [reachable model nodes](../using-ack/references/json-schema.md#export), and you have checked lazy targets separately for runtime rules missing from the export. +2. **Shape the schema for the provider.** The root is an `Ack.object` (tools and function parameters require an object root, and a discriminated or nullable root exports as `anyOf`). Keep it focused, because schema size costs input tokens. Add `.describe(...)` or `/// @description` on fields the model has to fill in. A `@Schemable` class's `Model.schema` works anywhere a schema does. Confirm that `schema.toJsonSchema()['type'] == 'object'` and review [export warnings](../using-ack/references/json-schema.md#export) across the schema, including lazy targets, with `schema.toSchemaModel().allWarnings`. 3. **Export it the way the reference says, and send it.** Use the adapter call or the `toJsonSchema()` map unchanged. Don't hand-edit the map to fit a provider unless the reference says to. -4. **Gate what comes back.** Decode the JSON, then call `schema.safeParse(decoded)` (for a generated class, use `Model.schema.safeParse`). Use the parsed value, never the raw map. On `Fail`, report `path: message` using [`leafErrors`](../using-ack/SKILL.md#3-parse-at-the-boundary). Never surface the top error's `toString()` or an `AckException`, which echo the whole payload. `ack_mcp_dart` already reports leaf lines. +4. **Gate what comes back.** Decode the JSON, then call `schema.safeParse(decoded)` (for a generated class, use `Model.schema.safeParse`). Use the parsed value. On `Fail`, `SchemaError.toString()` provides one `path: message` line per failure, using `#:` at the root. Use [`leafErrors`](../using-ack/SKILL.md#3-parse-at-the-boundary) when you need individual fields. `ack_mcp_dart` already reports leaf lines. ## Done when diff --git a/plugins/ack/skills/ack-provider-schemas/references/gemini-api.md b/plugins/ack/skills/ack-provider-schemas/references/gemini-api.md index 9c7acdf5..882b1396 100644 --- a/plugins/ack/skills/ack-provider-schemas/references/gemini-api.md +++ b/plugins/ack/skills/ack-provider-schemas/references/gemini-api.md @@ -60,7 +60,7 @@ for (final part in (body['candidates'] as List).first['content']['parts'] as Lis } ``` -After a successful parse, `dueDate` is a local-midnight `DateTime` (not UTC), or absent if Gemini omitted the key. +After a successful parse, `dueDate` is the local value of `DateTime(year, month, day)`, or absent if Gemini omitted the key. On days when the local clock skips midnight, the constructor may return a later time. ## Keywords Gemini ignores diff --git a/plugins/ack/skills/ack-provider-schemas/references/mcp.md b/plugins/ack/skills/ack-provider-schemas/references/mcp.md index 387be631..a806399c 100644 --- a/plugins/ack/skills/ack-provider-schemas/references/mcp.md +++ b/plugins/ack/skills/ack-provider-schemas/references/mcp.md @@ -55,7 +55,7 @@ server.registerTool( 'report', description: 'Current weather', inputSchema: reportInput.toMcpToolInputSchema(), - outputSchema: reportOutput.toMcpToolInputSchema(), // same JsonObject type; enforces an object root + outputSchema: JsonObject.fromJson(reportOutput.toJsonSchema()), callback: (args, extra) { final parsed = parseMcpToolArguments(reportInput, args, debugName: 'report'); if (parsed case Fail(:final error)) { diff --git a/plugins/ack/skills/build-data-classes-with-ack/references/schema-first.md b/plugins/ack/skills/build-data-classes-with-ack/references/schema-first.md index 61767668..755bb751 100644 --- a/plugins/ack/skills/build-data-classes-with-ack/references/schema-first.md +++ b/plugins/ack/skills/build-data-classes-with-ack/references/schema-first.md @@ -44,7 +44,7 @@ The generator rejects: Recursion uses named `Ack.lazy('Node', () => nodeSchema)`. -Check the union's export: each branch exports its own `const` discriminator (for example, `{"method": {"const": "card"}}`), and `Ack.datetime()` exports `format: date-time`. The `.min(DateTime)` bound is absent from the export. Use the [warning walk](../../using-ack/references/json-schema.md#export) to find `datetime_constraint_not_draft7` on the reachable field node, and put the bound in `.describe(...)`. For rules inside lazy targets, inspect the exported shape and test the runtime rule separately; the walk cannot reach their warnings. +Check the union's export: each branch exports its own `const` discriminator (for example, `{"method": {"const": "card"}}`), and `Ack.datetime()` exports `format: date-time`. The `.min(DateTime)` bound is absent from the export. Use `Payment.schema.toSchemaModel().allWarnings` to find `datetime_constraint_not_draft7` and its JSON Pointer path. Put the bound in `.describe(...)` so it appears in the export. The same getter includes warnings for rules inside lazy targets. ## Models from `.schema.json` (opt-in builder) diff --git a/plugins/ack/skills/using-ack/SKILL.md b/plugins/ack/skills/using-ack/SKILL.md index ea70fa6f..028dbf4f 100644 --- a/plugins/ack/skills/using-ack/SKILL.md +++ b/plugins/ack/skills/using-ack/SKILL.md @@ -23,7 +23,7 @@ Done when `dart pub deps` resolves to the baseline or a later 2.x release, or th - **Scalars:** `Ack.string()`, `integer()`, `double()`, `number()`, `boolean()`, `literal(v)`, `enumString([...])`, `enumValues(MyEnum.values)`. Primitives are strict: `'42'` is not an integer. `integer()` accepts a lossless `42.0` and returns `42`; `double()` accepts a JSON integer (`9` becomes `9.0`). - **Containers:** `Ack.object({...})` rejects unknown keys by default (`additionalProperties: true` to allow them); `Ack.list(item)`; `Ack.map(valueSchema)` for arbitrary string keys; `Ack.any()` for any non-null JSON value; `Ack.map(Ack.any().nullable())` for an object of anything. -- **Constraints** chain on the schema: strings `minLength`, `maxLength`, `matches` (unanchored, so write `^...$`), `email`, `url`, `uuid`, `date`, `datetime`, plus the two-way normalizers `trim`, `toLowerCase`; numbers `min`, `max`, `greaterThan`, `lessThan`, `positive`, `negative`, `multipleOf`; lists `minItems`, `maxItems`, `unique`. `.describe('...')` sets the exported description. +- **Constraints** chain on the schema: strings `minLength`, `maxLength`, `matches` (unanchored, so write `^...$`), `email`, `uri`, `uuid`, `date`, `datetime`, plus the two-way normalizers `trim`, `toLowerCase`; numbers `min`, `max`, `greaterThan`, `lessThan`, `positive`, `negative`, `multipleOf`; lists `minItems`, `maxItems`, `length`, `notEmpty`, `unique`. `.describe('...')` sets the exported description. - **Composition:** `Ack.anyOf([...])` (first matching branch wins); `Ack.discriminated(discriminatorKey: 'type', schemas: {'a': objA, 'b': objB})`, where the union owns the key and branches omit it; `Ack.lazy('Name', () => schema)` for recursion; `obj.extend({...})`, `pick`, `omit`, `partial()`. - **Custom rules:** `.refine((v) => ..., message: '...')` for a rule across fields; it runs after the shape passes. Use `.constrain(...)` for a reusable `Constraint`. @@ -44,7 +44,7 @@ Done when `dart pub deps` resolves to the baseline or a later 2.x release, or th ### Codecs: values that are not JSON -`Ack.datetime()` (ISO string to UTC `DateTime`), `Ack.date()` (`YYYY-MM-DD` to local midnight, `isUtc` false), `Ack.uri()`, `Ack.duration()` (ms `int`), and custom `Ack.string().codec(decode: ..., encode: ...)` decode on parse and encode back. `.transform(fn)` only goes one way: encoding it fails, and generated models reject it. Put the wire rules on the input schema, before `.codec(...)`, so they export. `min`/`max` on `Ack.datetime()` / `Ack.date()` are enforced by `safeParse` only: the export drops them, so state the bound in `.describe(...)` for anyone reading the JSON Schema. A decoder that hits bad data throws an `Exception`; a thrown `Error` is treated as a bug and propagates out of `safeParse`. +`Ack.datetime()` (ISO string to UTC `DateTime`), `Ack.date()` (`YYYY-MM-DD` to local `DateTime(year, month, day)`, `isUtc` false), `Ack.uri()`, `Ack.duration()` (ms `int`), and custom `Ack.string().codec(decode: ..., encode: ...)` decode on parse and encode back. `.transform(fn)` only goes one way: encoding it fails, and generated models reject it. Put the wire rules on the input schema, before `.codec(...)`, so they export. `min`/`max` on `Ack.datetime()` / `Ack.date()` are enforced by `safeParse` only: the export drops them, so state the bound in `.describe(...)` for anyone reading the JSON Schema. A decoder that hits bad data throws an `Exception`; a thrown `Error` is treated as a bug and propagates out of `safeParse`. ## 3. Parse at the boundary @@ -70,7 +70,7 @@ Iterable leafErrors(SchemaError error) sync* { } ``` -A failing field comes back wrapped: the top error is a `SchemaNestedError` at `#`, and the field errors (`#/address/city`, `#/tags/1`, `#/secret` for an unknown key) sit in `.errors`. Report leaf paths and messages. A leaf message can quote that field's value (`got "2026-13-45"`), so drop it for sensitive fields. The top error's `toString()` (and the `AckException` from `parse`) echoes the whole input, so keep it out of logs and user-facing text. +A failing field comes back wrapped: the top error is a `SchemaNestedError` at `#`, and the field errors (`#/address/city`, `#/tags/1`, `#/secret` for an unknown key) sit in `.errors`. Report leaf paths and messages. A built-in constraint failure has a message such as `Constraints not met: Invalid email format...`. `toString()` prints one `path: message` line per failure, using `#:` at the root. - `parse` throws `AckException`. `safeParse` returns the sealed `SchemaResult` (one type argument, the `Runtime` type): `isOk`, `getOrThrow()`, `getOrNull()`, `getError()` (throws on success), `match(onOk:, onFail:)`. `Ok.value`, raw `AckSchema.parse`, and `getOrThrow()` are typed `Runtime?`, hence the `!`. - `SchemaError` is sealed: `TypeMismatchError`, `SchemaConstraintsError` (`.constraints`), `SchemaNestedError` (`.errors`, one child per failing field), `SchemaValidationError` (a `refine` failure, at the path of the refined schema), `SchemaTransformError` (`.cause`, a codec decoder threw; a malformed `Ack.date()` / `Ack.datetime()` string fails its format check first, as a `SchemaConstraintsError`), `SchemaEncodeError` (`.kind`). Switch on them exhaustively. diff --git a/plugins/ack/skills/using-ack/references/json-schema.md b/plugins/ack/skills/using-ack/references/json-schema.md index 2cf21b65..e3134337 100644 --- a/plugins/ack/skills/using-ack/references/json-schema.md +++ b/plugins/ack/skills/using-ack/references/json-schema.md @@ -4,45 +4,7 @@ Owning guide: [JSON Schema integration](https://github.com/btwld/ack/blob/v2.0.0 ## Export -`schema.toJsonSchema()` returns a `Map`. `schema.toSchemaModel()` returns the `AckSchemaModel` behind it. Each node's `.warnings` lists what the export dropped **at that node**; the warning has a `code` and `message`, but the builder leaves `warning.path` null. Until [#262](https://github.com/btwld/ack/issues/262) lands, walk reachable nodes yourself and carry the schema location as a JSON Pointer fragment: - -```dart -Iterable<(String, AckSchemaModelWarning)> allWarnings( - AckSchemaModel model, [ - String at = '#', -]) sync* { - for (final warning in model.warnings) { - yield (at, warning); - } - final children = switch (model) { - AckObjectSchemaModel(:final properties, :final additionalProperties) => [ - for (final entry in (properties ?? const {}).entries) - ('$at/properties/${pointerToken(entry.key)}', entry.value), - if (additionalProperties case AckAdditionalPropertiesSchema(:final schema)) - ('$at/additionalProperties', schema), - ], - AckArraySchemaModel(:final items?) => [('$at/items', items)], - AckAnyOfSchemaModel(:final schemas) => [ - for (final (index, schema) in schemas.indexed) ('$at/anyOf/$index', schema), - ], - AckOneOfSchemaModel(:final schemas) => [ - for (final (index, schema) in schemas.indexed) ('$at/oneOf/$index', schema), - ], - AckAllOfSchemaModel(:final schemas) => [ - for (final (index, schema) in schemas.indexed) ('$at/allOf/$index', schema), - ], - _ => const <(String, AckSchemaModel)>[], - }; - for (final (location, child) in children) { - yield* allWarnings(child, location); - } -} - -String pointerToken(String key) => - Uri.encodeComponent(key.replaceAll('~', '~0').replaceAll('/', '~1')); -``` - -Warnings inside `Ack.lazy` targets cannot be reached until [#262](https://github.com/btwld/ack/issues/262) lands. The targets are stored as raw JSON under `definitions`, without the model nodes or their warnings. Review recursive targets separately and test any runtime-only rules against the exported shape. +`schema.toJsonSchema()` returns a `Map`. `schema.toSchemaModel()` returns the `AckSchemaModel` behind it. Use `schema.toSchemaModel().allWarnings` to collect export warnings throughout the schema, including inside lazy definitions. Each warning has a `code`, a `message`, and a `path` with its JSON Pointer location, such as `#/properties/items/items`. Use `.warnings` for warnings on the current node. A class-first model exports through its generated `ModelSchema.toJsonSchema()` facade (or `Model.schema.toJsonSchema()` if the class defines that static). A schema-first generated model exports through `Model.schema.toJsonSchema()`. @@ -74,7 +36,7 @@ A date bound has no Draft-7 keyword, so the export carries only `format`. State - References resolve only from the `documents` map (`Uri` mapped to the decoded document), relative to `baseUri`. Nothing is fetched or read from disk. - `format` is only an annotation unless you pass `assertFormats: true` (or the dialect declares `format-assertion`). - Ack bundles no Unicode normalizer. For full IDNA checks of international hostnames and emails, pass an NFKC function, such as `unicodeNormalizer: unorm.nfkc` from `package:unorm_dart`. Without one, full-width forms fail and unnormalized labels can pass. ASCII names need nothing, except that an `xn--` A-label for an unnormalized label can also pass. -- An imported `pattern` uses ECMA-262 Unicode mode (`\p{Lu}` works). A native `.matches` uses Dart `RegExp`, so the same pattern can behave differently after a round trip. Imported `minLength` counts code points; native counts UTF-16 units. +- An imported `pattern` uses ECMA-262 Unicode mode (`\p{Lu}` works). A native `.matches` uses Dart `RegExp`, so the same pattern can behave differently after a round trip. Imported and native string length rules both count Unicode code points. - Imports never fill in defaults or coerce values. A failure is a `JsonSchemaValidationError`: `path` is the instance location (`#/b`) and `pointer` the schema location (`#/additionalProperties`). It reports only the first failing keyword. `keyword` can be empty (an `additionalProperties: false` failure has `keyword == ''`), so branch on `pointer`. - `toJsonSchema()` on an imported schema keeps 2020-12 (`$defs`, `unevaluatedProperties`, ...). `toJsonSchemaDraft7()` / `toSchemaModelDraft7()` convert it down and throw `UnsupportedError` when the meaning would change. Catch that rather than dropping keywords by hand. diff --git a/test/documentation/agent_skill_snippets_test.dart b/test/documentation/agent_skill_snippets_test.dart index 7ab8d1bc..524e47bf 100644 --- a/test/documentation/agent_skill_snippets_test.dart +++ b/test/documentation/agent_skill_snippets_test.dart @@ -40,7 +40,6 @@ Future _writeProject(Directory project) async { as YamlMap; final snippets = _readSnippets(); final [parse, leafErrors] = snippets.remove('using-ack/SKILL.md')!; - final [allWarnings] = snippets.remove('using-ack/references/json-schema.md')!; final [invoice] = snippets.remove('$_models/SKILL.md')!; final [payment] = snippets.remove('$_models/references/schema-first.md')!; final [money, theme] = snippets.remove( @@ -101,7 +100,6 @@ $parse } $leafErrors -$allWarnings ''', 'lib/models/invoice.dart': invoice, 'lib/models/payment.dart': '$_ackImport\n$payment', diff --git a/test/documentation/fixtures/agent_skill_examples.dart.template b/test/documentation/fixtures/agent_skill_examples.dart.template index 3c2bb625..7c2fa899 100644 --- a/test/documentation/fixtures/agent_skill_examples.dart.template +++ b/test/documentation/fixtures/agent_skill_examples.dart.template @@ -16,27 +16,6 @@ import 'package:http/testing.dart'; import 'package:mcp_dart/mcp_dart.dart'; void main() { - test('map and list warnings include the schema path', () { - final schema = Ack.object({ - 'dates/~ %': Ack.map(Ack.datetime().min(DateTime.utc(2026))), - 'names': Ack.list(Ack.string().trim().minLength(3)), - }); - final model = schema.toSchemaModel(); - expect(model.warnings, isEmpty); - final warnings = allWarnings(model).toList(); - expect( - warnings.map((entry) => (entry.$1, entry.$2.code)), - unorderedEquals([ - ( - '#/properties/dates~1~0%20%25/additionalProperties', - 'datetime_constraint_not_draft7', - ), - ('#/properties/names/items', 'codec_runtime_constraint_not_exported'), - ]), - ); - expect(warnings.map((entry) => entry.$2.path), everyElement(isNull)); - }); - test('normalizer constraints validate at runtime but are not exported', () { final schema = Ack.string().trim().minLength(3); expect(schema.toJsonSchema(), {'type': 'string'}); diff --git a/test/documentation/public_snippet_wrappers.dart b/test/documentation/public_snippet_wrappers.dart new file mode 100644 index 00000000..e1a12f79 --- /dev/null +++ b/test/documentation/public_snippet_wrappers.dart @@ -0,0 +1,353 @@ +import 'dart:convert'; + +import 'package:path/path.dart' as p; + +const _ack = "import 'package:ack/ack.dart';"; +const _builder = + "import 'package:ack_json_schema_builder/ack_json_schema_builder.dart';"; +const _convert = "import 'dart:convert';"; +final _constraintMessage = RegExp(r'// (Constraints not met: .+)'); +final _part = RegExp(r"^part '([\w.]+)\.g\.dart';$", multiLine: true); + +const publicSnippetWrappers = { + 'program': SnippetWrapper.library(addAck: false), + 'body': SnippetWrapper.body(), + 'library': SnippetWrapper.library(), + 'expressions': SnippetWrapper.body(expressions: true), + 'model': SnippetWrapper.library(generated: true), + 'part-directive': SnippetWrapper.library(), + 'reference-user': SnippetWrapper.body(generated: true, splitAt: '// Usage:'), + 'reference-account': SnippetWrapper.body( + generated: true, + splitAt: 'final account =', + ), + 'generator-signature': SnippetWrapper.library( + imports: ''' +import 'package:ack_generator/ack_generator.dart' as ack; +import 'package:ack_generator/ack_generator.dart' show AckJsonSchemaLibrary, AckJsonSchemaLibraryOptions; +import 'package:pub_semver/pub_semver.dart';''', + after: ''' +=> ack.generateAckSchemaLibrary(document: document, documentUri: documentUri, + partStem: partStem, options: options, documents: documents, + includeParts: includeParts, languageVersion: languageVersion);''', + ), + 'settings': SnippetWrapper.library(stem: 'settings'), + 'use-settings': SnippetWrapper.body(imports: "import 'settings.dart';"), + 'error-data': SnippetWrapper.body( + before: 'final schema = Ack.string();\nfinal data = 42;', + ), + 'field-validator': SnippetWrapper.body( + imports: "import 'package:flutter/material.dart';", + before: 'final someSchema = Ack.string();\nTextFormField(', + after: ',);', + ), + 'serialization': SnippetWrapper.body( + stem: 'serialization', + splitAt: '// Example Usage', + ), + 'serialized-map': SnippetWrapper.body( + imports: "import 'serialization.dart';", + before: "const jsonData = {'name': 'Ada', 'age': 20};", + ), + 'serialized-model': SnippetWrapper.body( + imports: "import 'package:ack_public_examples/docs/api-reference/index/user.dart';", + ), + 'nested-object': SnippetWrapper.library(stem: 'nested_object'), + 'read-nested-object': SnippetWrapper.body( + imports: "import 'nested_object.dart';", + before: "const data = {'name': 'Ada', 'address': {'street': 'Main', 'city': 'A', 'zipCode': '01010'}};", + ), + 'model-usage': SnippetWrapper.body(imports: "import 'models.dart';"), + 'schema-first-user': SnippetWrapper.library(generated: true, stem: 'user'), + 'schema-first-pet': SnippetWrapper.library( + generated: true, + stem: 'schema_first_pet', + ), + 'profile': SnippetWrapper.library(generated: true, stem: 'profile'), + 'profile-static-members': SnippetWrapper.library( + generated: true, + stem: 'profile_static_members', + before: '@Schemable()\nfinal class const Profile({required final String displayName}) with _\$ProfileAck {', + after: '}', + ), + 'profile-factory': SnippetWrapper.library( + generated: true, + stem: 'profile_factory', + before: '@Schemable()\nfinal class const Profile({required final String displayName}) with _\$ProfileAck {', + after: '}', + ), + 'profile-typed-member': SnippetWrapper.library( + generated: true, + stem: 'profile_typed_member', + before: '@Schemable()\nfinal class const Profile({required final String displayName}) with _\$ProfileAck {', + after: '}', + ), + 'task': SnippetWrapper.body( + generated: true, + stem: 'task', + splitAt: 'TaskSchema.toJsonSchema()', + ), + 'classic-profile': SnippetWrapper.library( + generated: true, + stem: 'classic_profile', + ), + 'optional-example': SnippetWrapper.library( + generated: true, + stem: 'optional_example', + ), + 'profile-patch': SnippetWrapper.library( + generated: true, + stem: 'profile_patch', + ), + 'section': SnippetWrapper.library(generated: true, stem: 'section'), + 'class-first-pet': SnippetWrapper.library( + generated: true, + stem: 'class_first_pet', + ), + 'other-file-order': SnippetWrapper.library(generated: true, stem: 'order'), + 'envelope': SnippetWrapper.library(generated: true, stem: 'envelope'), + 'json-key-field': SnippetWrapper.library( + imports: "import 'package:json_annotation/json_annotation.dart';\nimport 'models.dart';", + before: 'class Container {\n Container(this.account);', + after: '}', + ), + 'migration-account': SnippetWrapper.library( + generated: true, + stem: 'account_summary', + ), + 'quickstart-schema': SnippetWrapper.library(stem: 'user_schema'), + 'quickstart-parse': SnippetWrapper.body( + imports: "import 'user_schema.dart';", + ), + 'target-extension': SnippetWrapper.library(stem: 'adapter'), + 'target-test': SnippetWrapper.library(imports: "import 'adapter.dart';"), + 'positive-constraint': SnippetWrapper.body( + stem: 'validation/constraints', + splitAt: 'print(priceSchema', + ), + 'custom-constraint-library': SnippetWrapper.library( + stem: 'schemas/user_schema', + ), + 'price-message': SnippetWrapper.body( + imports: "import 'validation/constraints.dart';\nimport 'package:test/test.dart';", + after: 'expect(result.getError().message, documentedMessage);', + checkMessage: true, + run: true, + ), + 'sign-up': SnippetWrapper.library(stem: 'sign_up'), + 'form-submission': SnippetWrapper.library( + imports: "import 'package:flutter/material.dart';", + before: ''' +class SignUpFormState extends State { + final _usernameSchema = Ack.string(); + final _emailSchema = Ack.string().email(); + final _passwordSchema = Ack.string(); + final _usernameController = TextEditingController(); + final _emailController = TextEditingController(); + final _passwordController = TextEditingController(); + final _confirmPasswordController = TextEditingController(); + + @override + Widget build(BuildContext context) => const SizedBox.shrink(); +''', + after: '}', + extraImports: "import 'sign_up.dart';", + ), + 'schema-export': SnippetWrapper.library(stem: 'export'), + 'person-schema': SnippetWrapper.body(), + 'exported-model': SnippetWrapper.body(imports: "import 'export.dart';"), + 'api-specification': SnippetWrapper.body( + imports: "$_convert\nimport 'export.dart';", + ), + 'complex-schema': SnippetWrapper.library(imports: "import 'export.dart';"), + 'firebase-shape': SnippetWrapper.library( + imports: "import 'package:ack_firebase_ai/ack_firebase_ai.dart';", + ), + 'readme-user-parse': SnippetWrapper.library( + imports: "import 'user_schema.dart';", + ), + 'readme-user-list': SnippetWrapper.body( + imports: "import 'user_schema.dart';", + before: "const json = [{'name': 'Ada', 'email': 'ada@example.com'}];", + ), + 'readme-account': SnippetWrapper.library(imports: "import 'account.dart';"), + 'readme-answer': SnippetWrapper.library(generated: true, stem: 'answer'), + 'builder-data': SnippetWrapper.body( + imports: _builder, + before: "const data = 'ACK_1';", + ), + 'builder-library': SnippetWrapper.library(imports: _builder), + 'builder-validate': SnippetWrapper.body( + before: + "const data = {'name': 'Ada', 'email': 'ada@example.com', 'age': 20};", + ), + 'search-tool': SnippetWrapper.library(stem: 'search_tool'), + 'raw-search-tool': SnippetWrapper.body( + imports: """ +import 'search_tool.dart'; +import 'package:ack_mcp_dart/ack_mcp_dart.dart'; +import 'package:mcp_dart/mcp_dart.dart';""", + ), +}; + +class SnippetWrapper { + const SnippetWrapper.library({ + this.addAck = true, + this.generated = false, + this.stem, + this.imports = '', + this.extraImports = '', + this.before = '', + this.after = '', + this.run = false, + }) : body = false, + expressions = false, + splitAt = null, + checkMessage = false; + + const SnippetWrapper.body({ + this.generated = false, + this.stem, + this.imports = '', + this.before = '', + this.after = '', + this.expressions = false, + this.splitAt, + this.checkMessage = false, + this.run = false, + }) : addAck = true, + body = true, + extraImports = ''; + + final bool addAck; + final bool generated; + final bool body; + final bool expressions; + final bool checkMessage; + final bool run; + final String? stem; + final String? splitAt; + final String imports; + final String extraImports; + final String before; + final String after; + + String? fileName(String source) { + final name = stem ?? (generated ? (_part.firstMatch(source)?[1]) : null); + return name == null ? null : '$name.dart'; + } + + String render(String source, String location) { + final importLines = [imports, extraImports]; + if (addAck && !source.contains(_ack)) importLines.add(_ack); + final part = generated && !_part.hasMatch(source) + ? "part '$stem.g.dart';" + : ''; + final marker = '// Dart example from $location'; + if (!body) { + if (before.isEmpty && part.isEmpty) { + return '$marker\n${importLines.join('\n')}\n$source\n$after'; + } + final lines = source.split('\n'); + return ''' +$marker +${importLines.join('\n')} +${lines.where((line) => line.startsWith('import ')).join('\n')} +$part +$before +${lines.where((line) => !line.startsWith('import ')).join('\n')} +$after +'''; + } + final lines = source.split('\n'); + importLines.addAll(lines.where((line) => line.startsWith('import '))); + var code = lines.where((line) => !line.startsWith('import ')).join('\n'); + var declarations = ''; + if (splitAt case final delimiter?) { + final offset = code.indexOf(delimiter); + if (offset < 0) throw StateError('$location is missing $delimiter'); + declarations = code.substring(0, offset); + code = code.substring(offset); + } + if (expressions) code = _expressionStatements(code); + final message = checkMessage + ? 'const documentedMessage = ${jsonEncode(_constraintMessage.firstMatch(code)![1])};' + : ''; + return ''' +$marker +${importLines.join('\n')} +$part +$declarations +Future main() async { +$before +$code +$message +$after +} +'''; + } +} + +// These reference blocks show one call per line, with optional chained calls +// indented on the next line and optional trailing comments. +String _expressionStatements(String source) { + final lines = source.split('\n'); + final inlineComment = RegExp(r'\s+//'); + return [ + for (final (index, line) in lines.indexed) + if (line.trim().isEmpty || + line.trimLeft().startsWith('//') || + (index + 1 < lines.length && + lines[index + 1].trimLeft().startsWith('.'))) + line + else if (inlineComment.firstMatch(line) case final comment?) + '${line.substring(0, comment.start)};${line.substring(comment.start)}' + else + '$line;', + ].join('\n'); +} + +Map projectFiles(Map versions) { + String locked(String name) => ' $name: ${jsonEncode(versions[name]!)}'; + String local(String name) => + ' $name: {path: ${jsonEncode(p.absolute('packages', name))}}'; + return { + 'pubspec.yaml': + ''' +name: ack_public_examples +publish_to: none +environment: + sdk: '>=3.13.0 <4.0.0' +dependencies: + flutter: {sdk: flutter} +${['ack', 'ack_firebase_ai', 'ack_json_schema_builder', 'ack_mcp_dart'].map(local).join('\n')} +${['firebase_ai', 'firebase_core', 'http', 'json_annotation', 'json_schema_builder', 'mcp_dart', 'pub_semver', 'test', 'unorm_dart'].map(locked).join('\n')} +dev_dependencies: + flutter_test: {sdk: flutter} +${local('ack_generator')} +${locked('analyzer')} +${locked('build_runner')} +dependency_overrides: +${local('ack')} +''', + 'lib/docs/core-concepts/typesafe-schemas/address.dart': + ''' +$_ack +part 'address.g.dart'; +@Schemable() +final class const Address({required final String street}) with _\$AddressAck; +''', + 'lib/docs/guides/json-schema-integration/person.schema.json': r''' +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$defs": { + "Person": { + "type": "object", + "properties": {"name": {"type": "string"}, "age": {"type": "integer"}}, + "required": ["name", "age"] + } + } +} +''', + }; +} diff --git a/test/documentation/public_snippets_test.dart b/test/documentation/public_snippets_test.dart new file mode 100644 index 00000000..eee61cba --- /dev/null +++ b/test/documentation/public_snippets_test.dart @@ -0,0 +1,200 @@ +@Tags(['integration']) +library; + +import 'dart:convert'; +import 'dart:io'; + +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; +import 'package:yaml/yaml.dart'; + +import 'public_snippet_wrappers.dart'; + +final _fence = RegExp(r'^([ \t]*)(`{3,}|~{3,})[ \t]*(.*)$'); +final _main = RegExp(r'^(?:void|Future) main\s*\(', multiLine: true); +final _skip = RegExp(r'^\*\*Compile check skipped:\*\*\s+(\S.*)$'); +final _wrapperInfo = RegExp(r'(?:^|\s)compile=([\w-]+)(?=\s|$)'); + +void main() { + test( + 'every public Dart example has a compile check or visible skip reason', + () { + final snippets = _readSnippets().toList(); + expect(snippets, isNotEmpty); + expect( + snippets + .where((snippet) => snippet.mode == null) + .map((s) => s.location), + isEmpty, + reason: 'Declare compile= or a visible skip reason.', + ); + }, + ); + + test('compile the public Dart examples together', () async { + final snippets = _readSnippets().where((s) => s.mode != 'skip').toList(); + if (snippets.any((s) => s.mode == null)) return; + final project = await Directory.systemTemp.createTemp( + 'ack_public_examples', + ); + addTearDown(() => project.delete(recursive: true)); + final files = {...projectFiles(_lockedVersions())}; + final imports = []; + final examples = []; + final models = ['lib/**/address.dart', 'lib/**/*.schema.dart']; + + for (final (index, snippet) in snippets.indexed) { + final wrapper = publicSnippetWrappers[snippet.mode]!; + final base = p.withoutExtension(snippet.path); + final partOnly = snippet.mode == 'part-directive'; + final folder = partOnly ? '$base/line_${snippet.line}' : base; + final source = wrapper.render(snippet.source, snippet.location); + final name = + wrapper.fileName(snippet.source) ?? 'line_${snippet.line}.dart'; + final asset = p.posix.join(folder, name); + expect(files, isNot(contains('lib/$asset')), reason: snippet.location); + files['lib/$asset'] = source; + if (wrapper.generated) models.add('lib/$asset'); + if (partOnly) { + final partName = snippet.source.split("'")[1]; + files['lib/$folder/$partName'] = "part of '$name';"; + } + imports.add("import 'package:ack_public_examples/$asset' as s$index;"); + if (wrapper.run) { + examples.add('test(${jsonEncode(snippet.location)}, s$index.main);'); + } + if (snippet.mode == 'target-test') examples.add('s$index.main();'); + } + + files['build.yaml'] = + ''' +targets: + \$default: + builders: + ack_generator:ack_json_schema: + enabled: true + ack_generator:ack_generator: + generate_for: +${models.map((asset) => ' - ${jsonEncode(asset)}').join('\n')} +'''; + files['test/docs_test.dart'] = + ''' +import 'package:flutter_test/flutter_test.dart'; +${imports.join('\n')} + +void main() { + test('load compiled public examples', () {}); + ${examples.join('\n ')} +} +'''; + for (final entry in files.entries) { + final file = File(p.join(project.path, entry.key)); + await file.create(recursive: true); + await file.writeAsString(entry.value); + } + await _run(project, 'flutter', ['pub', 'get', '--offline']); + await _run(project, Platform.resolvedExecutable, [ + 'run', + 'build_runner', + 'build', + ]); + await _run(project, 'flutter', ['test', '--no-pub', 'test/docs_test.dart']); + }, timeout: const Timeout(Duration(minutes: 5))); +} + +Iterable<_Snippet> _readSnippets() sync* { + final files = [ + ...Directory('docs') + .listSync(recursive: true) + .whereType() + .where((file) => file.path.endsWith('.mdx')), + ...Directory('packages') + .listSync() + .whereType() + .map((directory) => File(p.join(directory.path, 'README.md'))) + .where((file) => file.existsSync()), + ]..sort((a, b) => a.path.compareTo(b.path)); + + for (final file in files) { + final lines = file.readAsLinesSync(); + var preceding = ''; + for (var index = 0; index < lines.length; index++) { + final start = _fence.firstMatch(lines[index]); + if (start == null) { + if (lines[index].trim().isNotEmpty) preceding = lines[index].trim(); + continue; + } + final startLine = index + 1; + final info = start[3]!.trim(); + final closing = RegExp( + '^[ \\t]*${start[2]![0]}{${start[2]!.length},}[ \\t]*\$', + ); + final indent = start[1]!; + final body = []; + while (++index < lines.length && !closing.hasMatch(lines[index])) { + final line = lines[index]; + body.add( + line.startsWith(indent) ? line.substring(indent.length) : line, + ); + } + final path = p.posix.joinAll(p.split(file.path)); + final location = '$path:$startLine'; + expect( + index, + lessThan(lines.length), + reason: 'Unclosed fence at $location', + ); + if (RegExp(r'^dart(?:\s|$)').hasMatch(info)) { + final source = body.join('\n'); + final wrapper = _wrapperInfo.firstMatch(info)?[1]; + final skipped = _skip.hasMatch(preceding); + if (wrapper != null) { + expect( + skipped, + isFalse, + reason: '$location has a wrapper and a skip reason', + ); + expect(publicSnippetWrappers, contains(wrapper), reason: location); + } + final mode = skipped + ? 'skip' + : wrapper ?? (_main.hasMatch(source) ? 'program' : null); + yield _Snippet(path, startLine, source, mode); + } + preceding = ''; + } + } +} + +class _Snippet { + const _Snippet(this.path, this.line, this.source, this.mode); + + final String path; + final int line; + final String source; + final String? mode; + + String get location => '$path:$line'; +} + +Map _lockedVersions() { + final lock = loadYaml(File('pubspec.lock').readAsStringSync()) as YamlMap; + final packages = lock['packages'] as YamlMap; + return { + for (final entry in packages.entries) + entry.key as String: (entry.value as YamlMap)['version'] as String, + }; +} + +Future _run(Directory project, String command, List args) async { + final result = await Process.run( + command, + args, + workingDirectory: project.path, + ); + expect( + result.exitCode, + 0, + reason: '$command ${args.join(' ')}\n${result.stdout}\n${result.stderr}', + ); +} diff --git a/test/documentation/release_guidance_test.dart b/test/documentation/release_guidance_test.dart new file mode 100644 index 00000000..2079ce45 --- /dev/null +++ b/test/documentation/release_guidance_test.dart @@ -0,0 +1,83 @@ +import 'dart:io'; + +import 'package:test/test.dart'; + +String _read(String path) => File(path).readAsStringSync(); + +void main() { + test( + 'reference and skills describe the stable schema names and semantics', + () { + final reference = _read('docs/api-reference/index.mdx'); + final skill = _read('plugins/ack/skills/using-ack/SKILL.md'); + for (final text in [reference, skill]) { + expect(text, isNot(contains('`url')), reason: 'Use the URI rule.'); + expect(text, contains('DateTime(year, month, day)')); + } + expect(skill, isNot(contains('echoes the whole input'))); + expect(skill, isNot(contains('got "2026-13-45"'))); + expect( + _read( + 'plugins/ack/skills/ack-provider-schemas/references/gemini-api.md', + ), + contains('DateTime(year, month, day)'), + ); + + final integration = _read('docs/guides/json-schema-integration.mdx'); + expect( + integration, + contains(r'^(?:[01][0-9]\|2[0-3]):[0-5][0-9]:[0-5][0-9]$'), + ); + expect(integration, isNot(contains('`format: time`'))); + for (final name in ['minItems', 'maxItems']) { + expect(integration, contains('| [`$name(n)`]')); + } + final builder = _read('packages/ack_json_schema_builder/README.md'); + expect(builder, contains('`.minItems()` / `.maxItems()`')); + expect(builder, isNot(contains('String and array support'))); + + final generator = _read('packages/ack_generator/README.md'); + final schemaSkill = _read( + 'plugins/ack/skills/using-ack/references/json-schema.md', + ); + for (final text in [generator, schemaSkill]) { + expect(text, contains('code points')); + expect(text, isNot(contains('UTF-16'))); + } + expect(schemaSkill, contains('schema.toSchemaModel().allWarnings')); + expect(schemaSkill, isNot(contains('#262'))); + expect( + _read( + 'plugins/ack/skills/build-data-classes-with-ack/references/schema-first.md', + ), + contains('toSchemaModel().allWarnings'), + ); + expect( + _read('docs/guides/custom-validation.mdx'), + contains('Constraints not met: Price must be greater than zero.'), + ); + expect( + _read('docs/guides/flutter-form-validation.mdx'), + contains('Constraints not met: Invalid email format'), + ); + }, + ); + + test('migration guide gives the NFKC opt-in for international formats', () { + final guide = _read('docs/getting-started/migration-guide.mdx'); + final row = guide.split('\n').singleWhere((line) => line.contains('NFKC')); + expect(row, startsWith('|')); + expect(row, contains('`unicodeNormalizer: nfkc`')); + expect(row, contains('`package:unorm_dart`')); + }); + + test('builder import guidance lists the Unicode normalizer parameter', () { + final guide = _read('docs/guides/json-schema-integration.mdx'); + expect( + guide, + contains( + '`toAckSchema({baseUri, documents, assertFormats, unicodeNormalizer})`', + ), + ); + }); +}