Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
87 commits
Select commit Hold shift + click to select a range
cc5ce89
fix(ack)!: reject unsupported Draft-7 dependencies
leoafarias Dec 1, 2026
65310c1
fix(ack): bound hostname labels before Punycode decoding
leoafarias Dec 1, 2026
2f6d20e
fix(ack): preserve valid IDNA case across platforms
leoafarias Dec 1, 2026
26a07e2
fix(ack): preserve format annotations in Draft-7 export
leoafarias Dec 1, 2026
8c1ac3f
refactor(ack)!: remove duplicate list rule names
leoafarias Dec 1, 2026
01d910a
fix(ack): align email quoting and year zero format checks
leoafarias Dec 1, 2026
22b44ff
feat(ack)!: use one API for URI validation
leoafarias Dec 1, 2026
03f3f04
feat(ack)!: standardize built-in constraint keys
leoafarias Dec 1, 2026
eebac2d
test(json-schema-builder): check asserted format lowering errors
leoafarias Dec 1, 2026
134ac43
fix(ack): export SchemaOperation
leoafarias Dec 1, 2026
c4dc903
feat: expose Unicode normalization in schema import adapters
leoafarias Dec 1, 2026
4329ccb
refactor(ack): keep transparent schema contexts internal
leoafarias Dec 1, 2026
9b609fd
fix(ack)!: report nested warnings and handle nullable raw schemas
leoafarias Dec 1, 2026
20315ae
docs(ack): clarify JSON Schema import expectations
leoafarias Dec 1, 2026
697af54
feat(ack)!: share the concrete public rule annotation exports
leoafarias Dec 1, 2026
cb1bf68
docs(ack): clarify which public types support exhaustive switches
leoafarias Dec 1, 2026
b77b54e
fix(ack): preserve typed iteration in schema warning traversal
leoafarias Dec 1, 2026
db2795d
fix(generator): qualify generated model field reads
leoafarias Dec 1, 2026
7d96087
refactor(ack)!: internalize schema model rendering helpers
leoafarias Dec 1, 2026
d14c7a5
fix(generator): escape discriminator keys in emitted errors
leoafarias Dec 1, 2026
c0133ca
fix(generator): qualify class statics in constructor defaults
leoafarias Dec 1, 2026
1c09946
fix(generator)!: inherit sealed union branch naming defaults
leoafarias Dec 1, 2026
57b52ef
fix(generator): name inline JSON Schema objects in UpperCamelCase
leoafarias Dec 1, 2026
7158672
fix(generator)!: validate through class-owned schemas
leoafarias Dec 1, 2026
2c3836d
fix(generator): report invalid rule arguments at their source
leoafarias Dec 1, 2026
3c81ef9
feat(generator)!: derive Dart field names from schema-first JSON keys
leoafarias Dec 1, 2026
d2b8791
fix(generator)!: normalize union and generated model behavior
leoafarias Dec 1, 2026
d03b3fa
docs(generator): clarify reserved fields and shared builder migration
leoafarias Dec 1, 2026
5328b43
test(generator): pin updated field reads and Set construction
leoafarias Dec 1, 2026
3ea3097
docs: complete the JSON Schema migration rows
leoafarias Dec 1, 2026
acfb12e
test(generator): expect nested generic fields to use model-owned schemas
leoafarias Dec 1, 2026
cea8b83
docs: complete the public API migration rows
leoafarias Dec 1, 2026
322f01c
test(generator): satisfy linting in wire key assertions
leoafarias Dec 1, 2026
e7bdaae
fix(generator): recognize rules without the public base type
leoafarias Dec 1, 2026
dccc05a
test(generator): pin class-owned collection schemas
leoafarias Dec 1, 2026
1500d07
test(ack): exercise legacy aliases through their public base
leoafarias Dec 1, 2026
a076566
style(json-schema): use the pinned SDK formatter
leoafarias Dec 1, 2026
548826c
test(generator): match each normalized wire key assertion
leoafarias Dec 1, 2026
09df6ce
fix(generator)!: reject custom class-owned schemas in sealed unions
leoafarias Dec 1, 2026
f0f513d
fix(ack)!: align built-in constraint keys with their rule families
leoafarias Dec 1, 2026
69f59fd
fix(json-schema): resolve warnings through nullable nodes and definit…
leoafarias Dec 1, 2026
10d95e8
fix(generator): qualify constructor defaults inherited through super …
leoafarias Dec 1, 2026
ad14c95
test(ack): cover schema rendering and context internals
leoafarias Dec 1, 2026
0c1e591
docs(ack): clarify internal schema keyword migration
leoafarias Dec 1, 2026
ee1460c
docs: group URI breaking notes under unreleased headings
leoafarias Dec 1, 2026
3979edd
docs(ack): move schema operation into error context guidance
leoafarias Dec 1, 2026
d477fea
fix(json-schema)!: reject dependencies when lowering to Draft-7
leoafarias Dec 1, 2026
b7c9259
fix(generator)!: prevent identifier shadowing in generated models
leoafarias Dec 1, 2026
f7e730f
docs(json-schema): clarify the default dialect and import stack limits
leoafarias Dec 1, 2026
72a64e5
fix(json-schema): bound Unicode label length before Punycode conversion
leoafarias Dec 1, 2026
a830948
fix(generator)!: unify schema-first key tokenization
leoafarias Dec 1, 2026
ef694e4
docs(generator): correct refinement and migration guidance
leoafarias Dec 1, 2026
552fd62
test(generator): cover wire keys, field names, and union diagnostics
leoafarias Dec 1, 2026
acbce0b
docs(ack): record the internal indexed schema constructor
leoafarias Dec 1, 2026
f6c5f7b
fix(generator): resolve union schema aliases in clean builds
leoafarias Dec 1, 2026
9b26114
fix(generator): use a null-aware prefix set element
leoafarias Dec 1, 2026
841f9a5
fix(json-schema)!: use ASCII-only case mapping for IDNA labels
leoafarias Dec 1, 2026
e70c605
chore(example): regenerate class-first runtime helpers
leoafarias Dec 1, 2026
dcfffe9
fix(generator): report missing Unicode normalization dependency
leoafarias Dec 1, 2026
7e7b3a5
fix(generator): show the missing union annotation hint in builds
leoafarias Dec 1, 2026
568440b
refactor(ack)!: make constraint attachment helpers internal
leoafarias Dec 1, 2026
67346fd
fix(json-schema): export versionless IP constraints with anyOf
leoafarias Dec 1, 2026
a3dfa01
fix(generator): report invalid discriminators on the union
leoafarias Dec 1, 2026
0d26441
fix(generator)!: express inherited case style through the public anno…
leoafarias Dec 1, 2026
2cef326
fix(ack): expose the abstract generated field schema type
leoafarias Dec 1, 2026
e67856e
fix(generator)!: normalize digits and acronyms in generated names
leoafarias Dec 1, 2026
3bd1d7a
fix(generator): preserve interpolated class-owned defaults
leoafarias Dec 1, 2026
46be36b
refactor(ack)!: restrict schema context implementations
leoafarias Dec 1, 2026
42f151e
fix(json-schema): relocate nested references in public nullable raw m…
leoafarias Dec 1, 2026
55ae444
fix(json-schema): show source locations in Draft-7 lowering errors
leoafarias Dec 1, 2026
19d9ed0
docs(json-schema): specify schema-model warning paths and order
leoafarias Dec 1, 2026
990f8f8
fix(generator)!: resolve inherited defaults in the receiving library
leoafarias Dec 1, 2026
b161685
refactor(ack)!: make transparent context construction private
leoafarias Dec 1, 2026
55ce7f1
docs(json-schema): clarify NFKC and ASCII-only case mapping
leoafarias Dec 1, 2026
9f03d79
fix(ack)!: validate constraints on schema copies
leoafarias Dec 1, 2026
4f68500
fix(generator)!: fall back on invalid translated JSON Schema names
leoafarias Dec 1, 2026
69c9582
fix(ack)!: name the local time constraint string_time
leoafarias Dec 1, 2026
c20d847
fix(generator)!: validate class-owned schemas before emitting facades
leoafarias Dec 1, 2026
77b9d02
fix(generator)!: reject explicit case style on schemas and libraries
leoafarias Dec 1, 2026
9dd7f71
fix(ack): infer the lazy context parent type
leoafarias Dec 1, 2026
d3c8eaa
docs(generator): clarify class-owned schema type requirements
leoafarias Dec 1, 2026
bed131d
docs(json-schema): link the import stack overflow issue
leoafarias Dec 1, 2026
8a84821
Merge remote-tracking branch 'origin/main' into release-readiness/e-p…
leoafarias Dec 1, 2026
5ba914a
Merge remote-tracking branch 'origin/release-readiness/e-public-api' …
leoafarias Dec 1, 2026
b84cc40
Merge origin/release-readiness/c-generator into release-readiness/d-j…
leoafarias Dec 1, 2026
9999102
test(generator): pin Unicode fixture to workspace toolchain
leoafarias Dec 1, 2026
1fdbf5f
Merge origin/main (E #272, C #274 squashes) into release-readiness/d-…
leoafarias Dec 2, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ jobs:
test/schemas/extensions/numeric_extensions_test.dart \
test/schemas/extensions/list_schema_extensions_test.dart \
test/utils/collection_utils_test.dart \
test/json_schema_idna_decode_failure_test.dart \
test/json_schema_import_test.dart \
test/json_schema_bundled_dialect_test.dart \
test/json_schema_vocabulary_contract_test.dart \
Expand Down
5 changes: 3 additions & 2 deletions docs/core-concepts/validation.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,9 @@ These methods live directly on `StringSchema` and normalize the string in
declaration order alongside constraints during both `parse` and `encode`.
Because they return `StringSchema`, you can continue chaining string
constraints (`Ack.string().trim().minLength(2)`), use them inside `@Schemable()`
models, and export them to JSON Schema as `type: 'string'` without
`'x-transformed': true`.
models, and export the string type. The export of
`Ack.string().trim().minLength(2)` is `{ "type": "string" }` because the minimum
applies to the trimmed text. Keep the native schema for that validation.

### `trim()`
Removes leading and trailing whitespace on parse and encode.
Expand Down
5 changes: 5 additions & 0 deletions docs/getting-started/migration-guide.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,11 @@ annotations from `package:ack/ack.dart`. Code that reads a rule’s former
| `ack_generator\|ack_models` & `ack_generator\|ack_model_json` in `build.yaml` | `2.0.0` | `ack_generator:ack_generator` (plus optional `ack_generator:ack_json_schema` for `.schema.json` files) |
| `@AckType()` `*Type` extension type, `.args`, `ModelType.parse(...)` | `2.0.0` | Generated `Model` class with typed fields, `Model.parse(...)`, `Model.safeParse(...)`, `Model.fromJson(...)`, `model.toJson()` |
| `Ack.enumCodec(MyEnum.values)` | `2.0.0` | `Ack.enumValues(MyEnum.values)` |
| Draft-7 `dependencies` passed to `Ack.fromJsonSchema` | `2.0.0` | Convert the resource to Draft 2020-12. Use `dependentRequired` for property lists and `dependentSchemas` for schema dependencies. |
| Lowering an imported Draft 2020-12 schema that contains `dependencies` to Draft-7 | `2.0.0` | Use `toJsonSchema()` to preserve the original document, or remove the ignored `dependencies` keyword before calling `toJsonSchemaDraft7()`. |
| A quoted email local part has unbalanced or misplaced quotes | `2.0.0` | Imported `email` and `idn-email` assertions reject it. Provide a valid email address. |
| Imported hostname or email domain assertions that relied on lowercasing non-ASCII labels | `2.0.0` | Ack lowercases ASCII only. Supply labels valid under IDNA2008, such as the permitted lowercase form of a disallowed Unicode capital letter. |
| `AckRawSchemaModel(indexedSchemas: …)` | `2.0.0` | Omit the internal schema index when constructing a raw schema model. |
| `ListSchema.minLength`, `maxLength`, `exactLength`, `nonEmpty` | `2.0.0` | Use `minItems`, `maxItems`, `length`, and `notEmpty`, respectively. |
| `StringSchema.url()` | `2.0.0` | Use `StringSchema.uri()` for the same validation and schema export. |
| Code matching a renamed built-in constraint key | `2.0.0` | `string.startsWith` → `string_starts_with`, `string.endsWith` → `string_ends_with`, `string.ip` → `string_ip`, `list.unique` → `list_unique_items`, `number.isFinite` → `number_finite`, `integer.isSafe` → `number_safe_integer`, `string_format_time` → `string_time`. |
Expand Down
49 changes: 39 additions & 10 deletions docs/guides/json-schema-integration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,27 @@ 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`.

Imported schemas share the parse input limit of 100 nested lists or maps
along any path.

## Importing published schemas

Import schemas from sources you trust. The cost of compiling and validating a
schema can grow with nested composition and repeated references. Reuse the
compiled validator when checking multiple values against the same schema.
A `$dynamicRef` cycle or a schema nested several thousand levels deep can
throw `StackOverflowError` during import
([tracked for 2.0.x in #279](https://github.com/btwld/ack/issues/279)).

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

Only the declared `$schema` string is checked — a document is never matched
against a dialect by shape. Draft-7 documents are evaluated under the same
Expand Down Expand Up @@ -104,8 +115,10 @@ input mapping. The data is bundled; validation does not fetch it at runtime.
Ack does not bundle Unicode normalization tables, so its core has no extra
dependencies. ASCII hostnames and email addresses need nothing more, except
that `xn--` A-labels are checked for normalized form only when a normalizer is
given. For full IDNA normalization of international names, pass an NFKC
function as `unicodeNormalizer`, for example from `package:unorm_dart`:
given. Pass an NFKC function as `unicodeNormalizer` to map compatibility
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
import 'package:unorm_dart/unorm_dart.dart' as unorm;
Expand Down Expand Up @@ -197,7 +210,8 @@ imported Draft 2020-12 resources by default** (`$defs`, `$dynamicRef`,
self-contained Draft-7 document with root-scoped `definitions` and rewritten
references, call `schema.toJsonSchemaDraft7()` or `schema.toSchemaModelDraft7()`
(which throws `UnsupportedError` if the imported schema relies on 2020-12-only
semantics).
semantics). Format annotations are preserved. An asserted `format` causes
lowering to report the keyword and its JSON Pointer.

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

Expand All @@ -215,8 +229,14 @@ targets:
- lib/**/*.schema.json
options:
assert_formats: false
normalize_unicode: false
```

Set `normalize_unicode: true` to apply NFKC normalization when generated
validators assert international hostname and email formats. Add `unorm_dart`
to the consuming package's runtime `dependencies` with
`dart pub add unorm_dart` before building.

`ack_generator:ack_json_schema` emits `<name>.schema.dart` (declaring
`part '<name>.schema.g.dart';`), which `ack_generator:ack_generator` compiles
in the same `dart run build_runner build` pass:
Expand Down Expand Up @@ -355,11 +375,18 @@ Use `toSchemaModel()` for a reusable, target-independent view of an Ack schema:
final model = userSchema.toSchemaModel();
final jsonSchemaMap = model.toJsonSchema();

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

`model.warnings` holds the node's own warnings. The builder leaves their
`path` null. `model.allWarnings` yields the node's warnings first, then its
definition warnings, then its descendants' warnings. It fills null paths with
fragment JSON Pointers like `#` and `#/anyOf/0/properties/a~1b`, using RFC 6901
token escaping without percent-encoding. It rebases any supplied
`#`-prefixed path to the warning's node and passes other paths through unchanged.

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

**Output JSON (JSON Schema Object):**
Expand Down Expand Up @@ -542,9 +569,11 @@ The nested nullable-union shape is intentional for generic Draft-7 output and ma
- **Date/time range constraints:** Draft-7 has no standard `formatMinimum` or
`formatMaximum` keywords. ACK validates `.min()` and `.max()` at runtime and
records schema-model warnings instead of rendering non-standard keywords.
- **List item nullability:** `Ack.list(...)` does not support nullable item
schemas yet. Make the list itself nullable with `Ack.list(item).nullable()`
when the whole field may be null.
- **List item nullability:** `Ack.list(item)` requires a schema that rejects
null items. An imported schema without an explicit non-null type may admit
null. Use `Ack.list(item.nullable(value: false))` to explicitly reject null elements,
or import the entire array schema to preserve nullable item behavior.
Use `Ack.list(item).nullable()` when the whole list may be null.
- **Discriminated branches:** `Ack.discriminated(...)` owns the discriminator.
Branches may omit the discriminator field; compatible `Ack.literal(...)` or
`Ack.enumString(...)` fields are accepted; generated branches expose the
Expand Down
50 changes: 50 additions & 0 deletions packages/ack/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,17 @@

### Breaking

* **Breaking:** The public `AckRawSchemaModel` constructor no longer accepts
the importer’s internal schema index.

* **Breaking:** Imported `email` and `idn-email` format assertions now
reject malformed quoting in the local part.

* **Breaking:** Draft-7 import rejects `dependencies` with
`unsupported_keyword` instead of silently ignoring the assertion.
Draft-7 lowering also rejects `dependencies` in imported 2020-12 schemas
and reports the keyword's JSON Pointer.

* **Breaking:** `Schemable.caseStyle` is now an `AckCaseStyle?`. An omitted
style is null. Use `AckCaseStyle.none` for an explicit override.

Expand Down Expand Up @@ -92,11 +103,24 @@
pass. This includes `xn--` A-labels in plain `hostname` and `email` values.
Other ASCII hostnames and email addresses are not affected.

* **Breaking:** International hostname and email domain assertions lowercase
ASCII letters only. After optional NFKC normalization, non-ASCII uppercase
letters disallowed by IDNA2008 are rejected on every platform. IDNA-valid
Cherokee letters remain valid.

* **Breaking:** An object field with `withDefault` before a transform or
codec is omitted from the exported JSON Schema `required` list.

### Changed

* Document trusted sources and validator reuse for JSON Schema imports, the
default Draft 2020-12 dialect, and when imports can overflow the stack.

* Document the ordering, escaping, and rebasing of schema-model warning paths.

* Clarify that NFKC maps compatibility forms and IDNA case mapping only
lowercases ASCII letters.

* Support `AckSchema.forGeneratedField<B, R>` as a generated-code entry point
returning `AckSchema<B, R>`.

Expand All @@ -112,6 +136,27 @@

### Fixed

* Collect nested JSON Schema export warnings with JSON Pointers through
`AckSchemaModel.allWarnings`, including warnings from nullable branches and
lazy definitions.
* Export nullable raw schema models without a resource ID, and clarify why
an imported nullable item schema cannot be passed to `Ack.list`.
* Rewrite local references in nullable raw schema models created with the public
constructor, including recursive references and resource IDs ending in `#`.

* Accept year `0000` in imported `date` assertions, matching `date-time`.

* Preserve format annotations when lowering an imported schema to Draft-7.
An asserted format reports its keyword and JSON Pointer.
* Include the retrieval URI in Draft-7 lowering errors for external documents
and report unsupported property conversions with a single error prefix.

* Export `Ack.string().ip()` with `anyOf` so valid IPv4 and IPv6 addresses
pass when `format` is an annotation.

* Reject hostname labels over 63 Unicode code points before Punycode
conversion in hostname and email format assertions.

* Clarify that exhaustive switches are supported for `SchemaError`. A switch
over the public `AckSchema` types needs a fallback branch.

Expand Down Expand Up @@ -173,6 +218,11 @@
Wrapper contexts such as anyOf, lazy, boundary, and discriminated objects
still add no path segment.

### Internal

* Add the `@internal` constructor `AckRawSchemaModel.indexed` for resources
already indexed by the JSON Schema importer.

## 2.0.0-beta.3

### Breaking
Expand Down
14 changes: 12 additions & 2 deletions packages/ack/lib/src/ack.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ final class Ack {
/// a supplied dialect requiring the format-assertion vocabulary also enables
/// them. Unknown asserted formats are rejected when compiling.
/// Unsupported semantics throw [JsonSchemaImportException].
/// A document without `$schema` is read as Draft 2020-12, which ignores
/// `dependencies`.
///
/// Import schema documents from sources you trust. Compilation and
/// validation costs depend on the shape of the schema. A `$dynamicRef`
/// cycle or a schema nested several thousand levels deep can throw
/// [StackOverflowError] during import
/// ([tracked for 2.0.x in #279](https://github.com/btwld/ack/issues/279)).
///
/// [unicodeNormalizer] supplies Unicode NFKC normalization for the
/// international hostname checks used by `hostname`, `idn-hostname`,
Expand All @@ -26,8 +34,10 @@ final class Ack {
/// can pass. Without one, an `xn--` A-label whose decoded label is not
/// normalized can also pass; other ASCII hostnames and email addresses do
/// not need it. Pass a function such as `nfkc` from `package:unorm_dart`
/// for full IDNA normalization. The normalizer is not part of the exported
/// JSON Schema.
/// to map compatibility forms such as full-width letters. Ack lowercases
/// ASCII letters only. After normalization, non-ASCII uppercase letters
/// disallowed by IDNA2008 are rejected. Exported JSON Schema omits the
/// normalizer.
static AckSchema<Object, Object> fromJsonSchema(
Object document, {
Uri? baseUri,
Expand Down
3 changes: 2 additions & 1 deletion packages/ack/lib/src/constraints/string_ip_constraint.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,9 @@ final class StringIpConstraint extends Constraint<String>
if (version == 4) return {'format': 'ipv4'};
if (version == 6) return {'format': 'ipv6'};

// Both branches can match when format is an annotation.
return {
'oneOf': [
'anyOf': [
{'format': 'ipv4'},
{'format': 'ipv6'},
],
Expand Down
41 changes: 30 additions & 11 deletions packages/ack/lib/src/json_schema/json_schema_compiler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -175,12 +175,20 @@ final class _ImportedNode {

/// The Draft-7 representation of an imported node, used by
/// `toJsonSchemaDraft7()`. 2020-12 assertions that cannot be lowered fail.
Map<String, Object?> renderDraft7(String Function(_ImportedNode) refOf) {
// Draft-7 silently ignores these keywords (and applies `items` to the
// entire array instead of only the suffix after `prefixItems`). Until a
// semantics-preserving lowering exists, fail instead of changing which
// instances the exported schema accepts.
Map<String, Object?> renderDraft7(
String Function(_ImportedNode) refOf, {
required Uri rootDocumentUri,
}) {
String location(String keyword) {
final pointer = _keywordPointer(this, keyword);
return documentUri == rootDocumentUri ? pointer : '$documentUri$pointer';
}

// Draft-7 treats `dependencies` as an assertion and ignores the 2020-12
// keywords below. It also applies `items` to the entire array when
// `prefixItems` is present. Reject lowering that would change validation.
const unsupportedKeywords = {
'dependencies',
'prefixItems',
'dependentRequired',
'dependentSchemas',
Expand All @@ -193,17 +201,19 @@ final class _ImportedNode {
for (final keyword in unsupportedKeywords) {
if (isKeywordActive(keyword) && document.containsKey(keyword)) {
throw UnsupportedError(
'Cannot lower "$keyword" at ${_keywordPointer(this, keyword)} '
'Cannot lower "$keyword" at ${location(keyword)} '
'with toJsonSchemaDraft7(); use toJsonSchema() for 2020-12 semantics.',
);
}
}
}
if (dynamicReference != null ||
dynamicAnchorName != null ||
(isKeywordActive('format') &&
source is Map<String, Object?> &&
(source as Map<String, Object?>).containsKey('format'))) {
if (formatAssertion && format != null) {
throw UnsupportedError(
'Cannot lower asserted "format" at ${location('format')} '
'with toJsonSchemaDraft7(); use toJsonSchema() to preserve the assertion.',
);
}
if (dynamicReference != null || dynamicAnchorName != null) {
throw UnsupportedError(
'This imported schema needs 2020-12 semantics and cannot be lowered '
'with toJsonSchemaDraft7().',
Expand Down Expand Up @@ -799,6 +809,15 @@ final class _JsonSchemaCompiler {
_fail(node, key, 'Expected a positive finite number.');
}
node.keywords[key] = node.multipleOf = value;
} else if (key == 'dependencies' &&
draft7Dialects.contains(node.dialectUri)) {
_fail(
node,
key,
'Draft-7 dependencies are unsupported. In Draft 2020-12, use '
'dependentRequired for property lists and dependentSchemas for schemas.',
code: 'unsupported_keyword',
);
} else if (key == 'uniqueItems') {
if (value is! bool) _fail(node, key, 'Expected a boolean.');
node.keywords[key] = node.uniqueItems = value;
Expand Down
19 changes: 13 additions & 6 deletions packages/ack/lib/src/json_schema/json_schema_formats.dart
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ bool _isFullDate(String value) {
final year = int.parse(match[1]!);
final month = int.parse(match[2]!);
final day = int.parse(match[3]!);
if (year == 0 || month < 1 || month > 12 || day < 1) return false;
if (month < 1 || month > 12 || day < 1) return false;
final leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
final days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return day <= days[month - 1];
Expand Down Expand Up @@ -234,6 +234,12 @@ bool _isRegex(String value) {
}
}

// Let the IDNA2008 data decide whether non-ASCII code points are valid.
String _lowercaseIdna(String value) => String.fromCharCodes([
for (final rune in value.runes)
if (rune >= 0x41 && rune <= 0x5a) rune + 0x20 else rune,
]);

// Without a normalizer, Unicode input is checked as given: IDNA2008 code point
// rules, CONTEXTJ/CONTEXTO and Bidi rules still apply, but compatibility
// mappings (such as full-width letters) and composition are not applied.
Expand All @@ -245,13 +251,15 @@ bool _isHostname(
if (!international && value.runes.any((rune) => rune > 127)) return false;
final nfkc = normalizer ?? _identityNormalizer;
final mapped = international
? nfkc(value.replaceAll(RegExp('[。.。]'), '.').replaceAll('\u200b', ''))
.toLowerCase()
? _lowercaseIdna(
nfkc(value.replaceAll(RegExp('[。.。]'), '.').replaceAll('\u200b', '')),
)
: value.toLowerCase();
if (mapped.isEmpty) return false;
final asciiLabels = <String>[];
final unicodeLabels = <String>[];
for (final rawLabel in mapped.split('.')) {
if (rawLabel.runes.length > 63) return false;
if (rawLabel.isEmpty ||
rawLabel.startsWith('-') ||
rawLabel.endsWith('-')) {
Expand All @@ -270,7 +278,7 @@ bool _isHostname(
if (label.isEmpty || label.runes.every((rune) => rune < 128)) {
return false;
}
label = nfkc(label).toLowerCase();
label = _lowercaseIdna(nfkc(label));
if (_punycodeEncode(label) != rawLabel.substring(4)) {
return false;
}
Expand Down Expand Up @@ -457,7 +465,7 @@ bool _isEmail(
required bool international,
_UnicodeNormalizer? normalizer,
}) {
final match = RegExp(r'^("(?:[^"\\]|\\[\s\S])*"|[^@]+)@(.+)$')
final match = RegExp(r'^("(?:[^"\\]|\\[\s\S])*"|[^"@]+)@(.+)$')
.firstMatch(value);
if (match == null) return false;
final local = match[1]!;
Expand All @@ -466,7 +474,6 @@ bool _isEmail(
return false;
}
if (local.startsWith('"')) {
if (!local.endsWith('"')) return false;
if (RegExp(r'[\u0000-\u001f\u007f]').hasMatch(local)) return false;
} else {
final atom = international
Expand Down
Loading
Loading