diff --git a/.alta/plans/2026-11-17-jsontron-spec-js-python.md b/.alta/plans/2026-11-17-jsontron-spec-js-python.md new file mode 100644 index 0000000..9b8d1f2 --- /dev/null +++ b/.alta/plans/2026-11-17-jsontron-spec-js-python.md @@ -0,0 +1,254 @@ +--- +title: Jsontron spec, conformance suite, and JS + Python ports +status: in-progress +created: 2026-11-17 +summary: Rename src/ to dotnet/, extract a language-neutral spec and shared JSON conformance suite that .NET runs first, then add reference implementations for JavaScript (Ajv + jq-wasm) and Python (jsonschema + jq) in this repo. +--- + +# Jsontron spec, conformance suite, and JS + Python ports + +## Goal + +Jsontron today is one .NET package whose semantics live in `readme.md` and the C# code. +This plan makes the semantics portable and ships two more implementations that plug into +the most used JSON Schema library of their language, the way the .NET one plugs into +JsonSchema.Net: + +| Language | Host library | jq engine | Package | Folder | +|---|---|---|---|---| +| .NET (exists) | JsonSchema.Net 9 | Devlooped.JQSharp | NuGet `Jsontron` | `dotnet/` (renamed from `src/`) | +| JavaScript / TypeScript | Ajv 8 | `jq-wasm` (jq 1.8.2) | npm `ajv-jsontron` | `js/` | +| Python | `jsonschema` 4 | `jq` (libjq 1.8.2) | PyPI `jsontron` | `python/` | + +## Decisions already made + +- **JS jq engine**: `jq-wasm` now, behind an engine interface. A native TypeScript engine is a + later phase and replaces the default once it passes the conformance suite. +- **Error shape**: one error per failed assert/report, in every language. .NET changes from its + `"; "`-joined string to match. +- **Go and Rust**: upstream first. Their leading libraries (santhosh-tekuri/jsonschema v6, the + `jsonschema` crate) do not give a custom keyword the root document. Ask for a root accessor; + no wrapper API in the meantime. +- **Scope of this plan**: spec + suite + JS + Python. Java (networknt + jackson-jq) gets its own plan. +- **Layout**: one repo, one folder per language; `src/` becomes `dotnet/`. +- **Rename details**: the snk stays skipped (it is already absent); `includes.yml` is marked + `skip` in `.netconfig` and edited locally. + +## Assumptions to confirm at review + +- **Package names**: npm `jsontron` is taken, so the npm package is `ajv-jsontron` (free, and + follows the `ajv-formats` / `ajv-keywords` convention). PyPI `jsontron` is free. +- **Versions in lockstep**: one GitHub release publishes NuGet, npm and PyPI with the same + version. Simplest to explain ("0.3 everywhere implements spec 0.2"); the cost is a release of + all three for a fix in one. +- **Reference jq**: jq 1.8 is the reference for the portable profile, since JS and Python both + run real jq 1.8.2. Where JQSharp differs, that is a JQSharp bug to fix upstream, not a + profile exclusion, unless the fix is out of reach. +- **Spec version stays 0.2**: the keyword syntax does not change, so the meta-schema + `schemas/jsontron-0.2.json` and its SchemaStore id are untouched. + +## Design + +### Spec (`spec/jsontron.md`) + +Normative text for what the readme describes informally: + +- Keyword shapes (`rules`, `assert`, `report`, `let`), by reference to the meta-schema. +- Normalization: sugar forms, and the merge of sibling `assert` / `report` / `let` into the + `context: "."` rule. +- Evaluation: `.` at the schema location's instance, `$root`, `let` order, scope and shadowing, + first-result-or-null binding, jq truthiness for assert and report. +- Messages: implicit quoting of plain text, the `[rule-id][assert-id][flag=value] ` prefix, + non-string results, and an empty message when the message expression fails. +- Errors: each failed assert or report is one error at the instance location of the schema + object carrying the keyword. A jq runtime error in `context`, `let` or `test` fails the + keyword with one error carrying the engine's text (the text is not normative). +- Build time: invalid shape or invalid jq must fail when the schema is compiled. +- **Reference lowering**: a rule set compiles to one jq program that takes `{root, node}` and + returns the array of failure messages. It defines the semantics precisely and is what + engines without evaluation-time variables run. An implementation may evaluate differently + (as .NET does) if it passes the suite. +- **Portable jq profile**: the jq 1.8 features schema authors can rely on in every + implementation, with the known exclusions listed. + +### Conformance suite (`tests/`) + +JSON files in the style of the JSON-Schema-Test-Suite, one per area (rules, assert sugar, +report, let, merge, severity and ids, nested locations, applicators, build errors, jq profile): + +```json +[ + { + "description": "report fails when the test is truthy", + "schema": { "report": { "test": ".total < 0", "message": "negative total" } }, + "tests": [ + { "description": "positive total", "data": { "total": 5 }, "valid": true }, + { "description": "negative total", "data": { "total": -1 }, "valid": false, + "errors": [ "negative total" ] } + ] + }, + { "description": "invalid jq fails at build", "schema": { "assert": ".a |" }, "buildError": true } +] +``` + +`errors` is compared as a sorted list of messages, so it does not depend on the order in which +a host walks schema locations. A `tests/schema.json` validates the suite files themselves. + +### JavaScript (`js/`, npm `ajv-jsontron`) + +- `const addJsontron = await loadJsontron(); addJsontron(ajv)`: loading is async because the + wasm module is; everything after is synchronous, as Ajv requires. +- `rules` is a compiled Ajv keyword (`compile(schema, parentSchema)`), which gives the sibling + keywords for the merge and a build-time step. `assert` / `report` / `let` are registered too; + when `rules` is absent, `assert` (else `report`) owns the evaluation. +- Root comes from Ajv's `dataCxt.rootData`. It is passed to jq only when the lowered program + references `$root`, because each call serializes its input. +- Keyword values are validated against the meta-schema definitions, so Ajv strict mode stays on. +- Engine interface `{ check(program), run(program, input) }` with `jq-wasm` as the default. +- TypeScript, ESM + CJS, Node 20+, and the browser through `jq-wasm/inline`. + +Spike numbers to keep in mind: about 0.6 ms per jq call, 3.4 ms with a 2,000-item root. A +per-item rule that reads `$root` over 2,000 items took 6.8 s. The readme must say so, and the +TypeScript engine (later phase) is the fix. + +### Python (`python/`, PyPI `jsontron`) + +- `JsontronValidator = validators.extend(Draft202012Validator, {...})`, used like any + `jsonschema` validator class; also `jsontron.extend(SomeValidator)` for other drafts. +- Keyword callbacks get the parent schema, which gives the sibling keywords for the merge. +- Root: `iter_errors` on the extended class records the top-level instance in a + `contextvars.ContextVar` when none is set, so nested `descend` calls see it. +- `jsonschema` has no per-keyword compile step: lowered programs are compiled on first use and + cached per schema object; `check_schema` is overridden to also compile every jq expression, + so invalid jq fails before the first instance. +- `jq` binds variables at compile time, so `$root` travels in the input (the lowering). +- Python 3.10+, typed, `pyproject.toml` with hatchling, pytest. + +Spike numbers: about 1.7 ms per call with a 2,000-item root; same note in the readme. + +## Steps + +### 1. Rename `src/` to `dotnet/` + +- [x] `git mv src dotnet`; update both paths in `Jsontron.slnx`. +- [x] `.netconfig`: re-key `src/Directory.Build.props`, `src/Directory.Build.targets` and + `src/nuget.config` to `dotnet/...` with the same `url`, `sha`, `etag`. +- [x] `.netconfig`: add `skip` entries at the three old `src/` paths, and keep the existing + `src/kzu.snk` skip. The repo-wide `[file] url = https://github.com/devlooped/oss` entry + expands upstream at its default paths and matches by path; without these the nightly sync + recreates `src/`. +- [x] `.netconfig`: add `skip` to `.github/workflows/includes.yml`; change its line 41 to + `dotnet/Directory.Build.props`. +- [x] `_config.yml`: exclude `dotnet/`, `js/`, `python/`, `spec/`, `tests/` instead of `src/`. + It is synced from upstream: mark it `skip` as well. +- [x] Verify: `dotnet build`, `dnx --yes retest`, and `dotnet file changes` shows no file about + to be written under `src/`. +- [x] Commit on a new branch `feature/ports`. + +### 2. Spec + +- [x] Write `spec/jsontron.md` as described under Design, taking each rule from the C# code + (`RuleSetCompiler.cs`, `JqEvaluation.cs`) rather than from the readme where they differ. +- [x] Write the reference lowering as an algorithm with one worked example. +- [x] List every behaviour the code has that the readme does not state, and decide each one in + the spec (for example: a jq runtime error in a test, a non-string message result). + +### 3. Conformance suite, run by .NET + +- [x] Create `tests/*.json`, `tests/schema.json` and `tests/readme.md` (120 groups, checked against jq 1.8.2 + where the rule set is at the root). +- [x] Port the existing xUnit cases the suite does not cover yet. +- [x] Add cases the xUnit tests lack: jsontron inside `if`/`then`/`else`, `not`, `anyOf`, + `$ref`; `$root` from nested locations; the jq profile features one by one. +- [x] Add a data-driven xUnit theory in `dotnet/Tests` that runs every suite file; keep only + the C# tests that cover .NET-specific API (`MetaSchemas.Register`, dialect, vocabulary). +- [x] One error per failure in .NET. `KeywordEvaluation` has a single `Error` string, so find + how JsonSchema.Net lets one keyword report several (its `Details` sub-results are the + candidate). If it cannot, stop and report: the fallback is a documented separator plus a + helper that splits, and that is a decision for the user. +- [x] Fix any other divergence the suite shows in .NET. +- [ ] File the JQSharp issue: `Jq.Parse` accepts undefined variables (`$x`), jq rejects them at + compile time. Four build-error cases are skipped in the .NET runner's known-gaps list + until then. Proposed as a follow-up task. + +### 4. JavaScript port + +- [x] Scaffold `js/` (TypeScript, tsup or equivalent for ESM + CJS, vitest). +- [x] Normalization and merge, the lowering, message preparation: pure functions with unit tests. +- [x] Engine interface and the `jq-wasm` engine, with the build-time check. +- [x] Ajv keywords and `loadJsontron`; meta-schema copied from `schemas/` at build, never + duplicated in the source tree. +- [x] Suite runner over `../tests`; all cases pass under Ajv strict mode with `allErrors`. +- [x] `js/readme.md`: quick start mirroring the .NET one, the async load, the performance note. + +### 5. Python port + +- [x] Scaffold `python/` (`pyproject.toml`, `src/jsontron`, pytest, ruff). +- [x] Normalization, lowering and message preparation, with unit tests. Same algorithm as JS; + the suite is what keeps the two equal. +- [x] `JsontronValidator`, `extend`, root capture, program cache, `check_schema`. +- [x] Suite runner over `../tests`; all cases pass on Windows. +- [ ] Linux and macOS: covered by the `python.yml` matrix, which has not run yet (nothing is pushed). +- [x] `python/readme.md`: quick start, the performance note. + +### 6. CI, publishing, docs + +- [x] `.github/workflows/js.yml` and `python.yml`: build and run the suite on push and pull + request. New files, because `build.yml` and `publish.yml` are synced from upstream. +- [x] Publishing on release, in the same new workflows: npm and PyPI trusted publishing (OIDC), + as the NuGet publish already does. The user sets up the trusted publishers on npm and PyPI. +- [x] Root `readme.md`: an implementations table and links; the .NET content stays as is. +- [x] `AGENTS.md` at the root (the repository guidance asks for it): layout, spec and suite as + the source of truth, the lowering, per-language integration, how to add a language. +- [x] ~~`changelog.md` entry~~: the file is generated on release from merged pull requests, so + the error-shape change belongs in the pull request title/description instead. + +### 7. Go and Rust upstream requests + +- [x] Draft the two issues (root instance accessor for custom keywords), each with the Jsontron + use case and the smallest API that would do. Show them to the user; file only after + their approval. + +## Deviations and findings during execution + +- **Message wrapping changed in the spec** (section 4). Real jq rejects `\"` inside `\(...)`, so + the old rule (escape every `"`) made plain-text messages such as + `order \(.id // "?")`, which the root readme uses, a build error in JS and Python. JQSharp + accepts it, which hid this in .NET. Interpolations are now copied unchanged and a backslash + keeps the next character; implemented in all three, with suite cases. +- **Default message is literal** (decided while writing the spec): an item without `message` + reports its `test` text as is. Before, .NET evaluated that text as a jq string, which broke + on tests containing quotes or `\(`. +- **.NET one error per failure** works: each keyword evaluates a private subschema once per + failure, so failures are child results (`Details`) at `/`. +- **Python root document** uses a registry of validators (weak references) filled by + `iter_errors` and `evolve()`, not a context variable: `iter_errors` is a generator, so a + context variable would leak into an interleaved validation. +- **Lowering**: each expression is followed by two newlines, not one, because jq 1.8 continues + a comment that ends in a backslash onto the next line. +- **Results on Windows**: .NET 238 passed, 4 skipped (JQSharp gap); JS 276 passed; Python 329 + passed. + +## Verification + +- `dnx --yes retest`, `dotnet format whitespace` and `dotnet format style` for .NET. +- `npm test` in `js/` and `pytest` in `python/`, each running every file under `tests/`. +- The three implementations report the same validity and the same sorted messages for every + suite case; CI fails if any suite file is not run by all three. + +## Risks + +- **.NET cannot emit several errors per keyword**: handled as a stop-and-ask in step 3. +- **JQSharp differs from jq 1.8** on profile features: each difference is either fixed in + JQSharp or excluded from the profile, case by case. +- **Performance of per-item rules** in JS and Python: documented, not solved here. +- **`jsonschema` internals**: replacing `iter_errors` on the extended class relies on current + behaviour of `descend` / `evolve`; pinned by a test and a minimum version. +- **Synced files**: three more files become local-only (`includes.yml`, `_config.yml`, and the + renamed paths). Upstream changes to them no longer arrive. + +## Later, not in this plan + +- Native TypeScript jq engine for `ajv-jsontron`. +- Java: networknt json-schema-validator + jackson-jq. +- Go and Rust ports, once the root accessor exists upstream. diff --git a/.github/workflows/includes.yml b/.github/workflows/includes.yml index ee446be..929df86 100644 --- a/.github/workflows/includes.yml +++ b/.github/workflows/includes.yml @@ -38,7 +38,7 @@ jobs: shell: pwsh run: | $file = "osmfeula.txt" - $props = "src/Directory.Build.props" + $props = "dotnet/Directory.Build.props" if (-not (test-path $file) -or -not (test-path $props)) { exit 0 } diff --git a/.github/workflows/js.yml b/.github/workflows/js.yml new file mode 100644 index 0000000..f7554f3 --- /dev/null +++ b/.github/workflows/js.yml @@ -0,0 +1,80 @@ +# Builds and tests the JavaScript implementation (js/) against the conformance suite, +# and publishes it to npm when a release is published. +# Publishing uses npm trusted publishing (OIDC): configure the trusted publisher for the +# @devlooped/jsontron package on npmjs.com with repository devlooped/Jsontron and workflow js.yml. + +name: js +on: + workflow_dispatch: + push: + branches: [ main, 'feature/*', 'rel/*' ] + paths: [ 'js/**', 'tests/**', 'schemas/**', '.github/workflows/js.yml' ] + pull_request: + paths: [ 'js/**', 'tests/**', 'schemas/**', '.github/workflows/js.yml' ] + release: + types: [released] + +defaults: + run: + working-directory: js + +jobs: + test: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ ubuntu-latest, windows-latest, macos-latest ] + node: [ 20, 22, 24 ] + steps: + - name: ๐Ÿค˜ checkout + uses: actions/checkout@v4 + + - name: โš™ node + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + cache: npm + cache-dependency-path: js/package-lock.json + + - name: ๐Ÿ“ฆ install + run: npm ci + + - name: ๐Ÿ” typecheck + run: npm run typecheck + + - name: ๐Ÿ™ build + run: npm run build + + - name: ๐Ÿงช test + run: npm test + + publish: + needs: test + if: github.event_name == 'release' + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + steps: + - name: ๐Ÿค˜ checkout + uses: actions/checkout@v4 + + - name: โš™ node + uses: actions/setup-node@v4 + with: + node-version: 24 + registry-url: https://registry.npmjs.org + + - name: ๐Ÿ“ฆ install + run: npm ci + + - name: ๐Ÿท version + env: + TAG: ${{ github.event.release.tag_name }} + run: npm version "${TAG#v}" --no-git-tag-version --allow-same-version + + - name: ๐Ÿ™ build + run: npm run build + + - name: ๐Ÿš€ publish + run: npm publish --provenance --access public diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml new file mode 100644 index 0000000..3835781 --- /dev/null +++ b/.github/workflows/python.yml @@ -0,0 +1,75 @@ +# Builds and tests the Python implementation (python/) against the conformance suite, +# and publishes it to PyPI when a release is published. +# Publishing uses PyPI trusted publishing (OIDC): configure the trusted publisher for the +# jsontron project on pypi.org with repository devlooped/Jsontron and workflow python.yml. + +name: python +on: + workflow_dispatch: + push: + branches: [ main, 'feature/*', 'rel/*' ] + paths: [ 'python/**', 'tests/**', 'schemas/**', '.github/workflows/python.yml' ] + pull_request: + paths: [ 'python/**', 'tests/**', 'schemas/**', '.github/workflows/python.yml' ] + release: + types: [released] + +defaults: + run: + working-directory: python + +jobs: + test: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ ubuntu-latest, windows-latest, macos-latest ] + python: [ '3.11', '3.13' ] + steps: + - name: ๐Ÿค˜ checkout + uses: actions/checkout@v4 + + - name: โš™ python + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + + - name: ๐Ÿ“ฆ install + run: python -m pip install -e ".[test]" + + - name: ๐Ÿงน lint + run: ruff check + + - name: ๐Ÿงช test + run: pytest + + publish: + needs: test + if: github.event_name == 'release' + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + steps: + - name: ๐Ÿค˜ checkout + uses: actions/checkout@v4 + + - name: โš™ python + uses: actions/setup-python@v5 + with: + python-version: '3.13' + + - name: ๐Ÿท version + env: + TAG: ${{ github.event.release.tag_name }} + run: sed -i "s/^version = .*/version = \"${TAG#v}\"/" pyproject.toml + + - name: ๐Ÿ™ build + run: | + python -m pip install build + python -m build + + - name: ๐Ÿš€ publish + uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: python/dist diff --git a/.netconfig b/.netconfig index 25756d1..7c895a5 100644 --- a/.netconfig +++ b/.netconfig @@ -18,6 +18,15 @@ [file "src/kzu.snk"] url = https://github.com/devlooped/oss/blob/main/src/kzu.snk skip +[file "src/Directory.Build.props"] + url = https://github.com/devlooped/oss/blob/main/src/Directory.Build.props + skip +[file "src/Directory.Build.targets"] + url = https://github.com/devlooped/oss/blob/main/src/Directory.Build.targets + skip +[file "src/nuget.config"] + url = https://github.com/devlooped/oss/blob/main/src/nuget.config + skip [file ".github/workflows/combine-prs.yml"] url = https://github.com/devlooped/oss/blob/main/.github/workflows/combine-prs.yml skip @@ -84,9 +93,7 @@ weak [file ".github/workflows/includes.yml"] url = https://github.com/devlooped/oss/blob/main/.github/workflows/includes.yml - sha = d571412f07b0fb3c40023dc906f64906d7ed2b46 - etag = ab627107749577bb619b024aff93027359b66b4c3f5a85a36b235e428387cd17 - weak + skip [file ".github/workflows/publish.yml"] url = https://github.com/devlooped/oss/blob/main/.github/workflows/publish.yml sha = 0ca5fd11125cd10c51b4433a86917c06ff1ae839 @@ -104,9 +111,7 @@ weak [file "_config.yml"] url = https://github.com/devlooped/oss/blob/main/_config.yml - sha = 68b409c486842062e0de0e5b11e6fdb7cd12d6e2 - etag = d608aa0ddaedc2d8a87260f50756e8d8314964ad4671b76bd085bcb458757010 - weak + skip [file "assets/css/style.scss"] url = https://github.com/devlooped/oss/blob/main/assets/css/style.scss sha = 9db26e2710b084d219d6355339d822f159bf5780 @@ -117,17 +122,17 @@ sha = 0683ee777d7d878d4bf013d7deea352685135a05 etag = 2c6335b37e4ae05eea7c01f5d0c9d82b49c488f868a8b5ba7bff7c6ff01f3994 weak -[file "src/Directory.Build.props"] +[file "dotnet/Directory.Build.props"] url = https://github.com/devlooped/oss/blob/main/src/Directory.Build.props sha = 6e2438919e108aeb75106dc0737c45f5e55d5f42 etag = f1d6384abf18d8d891ce5e835a10c73fe029c42151374be96d7e4af43d189c65 weak -[file "src/Directory.Build.targets"] +[file "dotnet/Directory.Build.targets"] url = https://github.com/devlooped/oss/blob/main/src/Directory.Build.targets sha = 3a758f47e8955c15a016b3db08f383781cbdee26 etag = 22005ab28676aa6d790171003057c81fe4ceec01251626385a3dcef3417ae3cd weak -[file "src/nuget.config"] +[file "dotnet/nuget.config"] url = https://github.com/devlooped/oss/blob/main/src/nuget.config sha = 032439dbf180fca0539a5bd3a019f18ab3484b76 etag = da7c0104131bd474b52fc9bc9f9bda6470e24ae38d4fb9f5c4f719bc01370ab5 diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..f76555b --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,81 @@ +# Jsontron: implementation notes + +Jsontron is a JSON Schema vocabulary (`rules`, `assert`, `report`, `let`) for Schematron-style +business rules written in jq. This repository holds the specification and one implementation +per language. + +## Layout + +| Path | Content | +|------|---------| +| `spec/jsontron.md` | Normative specification. The source of truth for behaviour. | +| `schemas/` | Meta-schema of the keywords (published on SchemaStore). The version of the meta-schema is the version of the spec. | +| `tests/` | Language-neutral conformance suite (JSON). Every implementation runs every file. | +| `dotnet/` | .NET: JsonSchema.Net keywords, jq by `JQLite`. NuGet `Jsontron`. | +| `js/` | JavaScript/TypeScript: Ajv keywords, jq by `@devlooped/jqlite`. npm `@devlooped/jsontron`. | +| `python/` | Python: `jsonschema` keywords, jq by `devlooped-jqlite`. PyPI `jsontron`. | + +## Rules for changes + +- Behaviour changes start in `spec/jsontron.md` and `tests/`, then reach every implementation + in the same change. An implementation never special-cases a suite case. +- All three implementations share [`devlooped/jqlite`](https://github.com/devlooped/jqlite) + (a portable profile of jq 1.8) for jq semantics. A difference between jqlite and jq 1.8 + outside the documented jqlite profile is a bug to fix in jqlite, not a reason to change a + case. +- Each implementation is a real assertion keyword of its host library, so that it takes part + in `if`, `not`, `anyOf`, `oneOf` and `$ref`. Post-processing annotations is not conforming. + +## Key decisions + +- **Shared jq engine**: all three implementations use `devlooped/jqlite` (`JQLite` on NuGet, + `@devlooped/jqlite` on npm, `devlooped-jqlite` on PyPI), giving identical jq semantics, + zero native/WASM dependencies, and synchronous evaluation everywhere. +- **Reference lowering** (spec section 7): a rule set compiles to one jq program with input + `{root, node}` and the array of failure texts as output. JS and Python run this lowering; + .NET evaluates expression by expression with `JQLite` variables; the suite keeps the two + equal. +- **One error per failure**, in every language (spec section 5). +- **Default message is literal**: an item without `message` reports its `test` text as is. +- **Build-time checks**: every expression is checked in isolation, because text such as + `true) , (false` is valid once embedded in the lowered program. Unbound `$variable` + references are checked at evaluation time under `jqlite` (which treats unbound `$name` as + a host variable). +- **Python root document**: `jsonschema` does not pass the root instance to keyword callbacks. + The outermost `iter_errors` of the extended class registers the validator with the document, + and `evolve()` registers every validator derived from it. A context variable was ruled out: + `iter_errors` is a generator, so the variable would stay set between two errors and leak + into an interleaved validation. +- **.NET errors**: a JsonSchema.Net keyword result holds one error string, so each Jsontron + keyword evaluates a private subschema once per failure; failures appear as child results + of the schema object, at `/`. +- **Message wrapping** (spec section 4) copies `\(...)` interpolations unchanged, because jq + rejects `\"` inside an interpolation. +- **Go and Rust** are not implemented: santhosh-tekuri/jsonschema and the `jsonschema` crate + do not give a custom keyword the root instance. The plan is to get a root accessor upstream + rather than ship a wrapper API. +- **Java** is planned on networknt json-schema-validator with jqlite (when a Java port exists) + or jackson-jq. +- **Versions**: one GitHub release publishes NuGet, npm and PyPI with the same version. + +## Repository mechanics + +- Many files are synced from `devlooped/oss` by dotnet-file (`.netconfig`). The .NET code + lives in `dotnet/`, not the upstream `src/`: the `Directory.Build.*` and `nuget.config` + entries are keyed by their `dotnet/` path, and the upstream `src/` paths are marked `skip` + so that the sync does not recreate them. `.github/workflows/includes.yml` and `_config.yml` + carry local edits and are also `skip`. +- `.github/copilot-instructions.md` is synced and still says `src/`; read it as `dotnet/`. +- `build.yml` and `publish.yml` are synced and cover .NET only. `js.yml` and `python.yml` are + local and cover the other two, including publishing by OIDC trusted publishing. +- `changelog.md` is generated on release; do not edit it by hand. + +## Adding a language + +1. Pick the most used JSON Schema library that lets a custom keyword see its sibling keywords, + run a step at schema compile time, and read the root instance. +2. Pick a jq engine; prefer `devlooped/jqlite` if available for the language, or one that + tracks jq 1.8. +3. Implement normalization and merge (spec section 2), then either the lowering or direct + evaluation, and a runner over `tests/*.json` as `tests/readme.md` describes. +4. Add a workflow, a row in the root `readme.md`, and a row in the layout table above. diff --git a/Jsontron.slnx b/Jsontron.slnx index 3768745..0c03f3f 100644 --- a/Jsontron.slnx +++ b/Jsontron.slnx @@ -1,4 +1,4 @@ - - + + diff --git a/_config.yml b/_config.yml index 04e6093..78a7a6b 100644 --- a/_config.yml +++ b/_config.yml @@ -1,3 +1,3 @@ theme: jekyll-theme-slate -exclude: [ 'src/', '*.sln', '*.slnx', 'Gemfile*', '*.rsp' ] +exclude: [ 'dotnet/', 'js/', 'python/', 'spec/', 'tests/', '*.sln', '*.slnx', 'Gemfile*', '*.rsp' ] diff --git a/src/Directory.Build.props b/dotnet/Directory.Build.props similarity index 100% rename from src/Directory.Build.props rename to dotnet/Directory.Build.props diff --git a/src/Directory.Build.targets b/dotnet/Directory.Build.targets similarity index 100% rename from src/Directory.Build.targets rename to dotnet/Directory.Build.targets diff --git a/src/Directory.props b/dotnet/Directory.props similarity index 100% rename from src/Directory.props rename to dotnet/Directory.props diff --git a/src/Jsontron/Dialect.cs b/dotnet/Jsontron/Dialect.cs similarity index 100% rename from src/Jsontron/Dialect.cs rename to dotnet/Jsontron/Dialect.cs diff --git a/src/Jsontron/Jq/JqEvaluation.cs b/dotnet/Jsontron/Jq/JqEvaluation.cs similarity index 69% rename from src/Jsontron/Jq/JqEvaluation.cs rename to dotnet/Jsontron/Jq/JqEvaluation.cs index 8f5a760..c12b951 100644 --- a/src/Jsontron/Jq/JqEvaluation.cs +++ b/dotnet/Jsontron/Jq/JqEvaluation.cs @@ -1,7 +1,8 @@ using System.Text; using System.Text.Json; -using Devlooped; +using JQLite; using Json.Schema; +using Jsontron.Keywords; namespace Jsontron; @@ -10,9 +11,9 @@ static class JqEvaluation /// /// Evaluates a compiled rule set against the current evaluation context. /// Binds $root to the document root and applies any schema-level / rule-level - /// let bindings. + /// let bindings. Each failure, or the evaluation error, is reported as its own error. /// - public static KeywordEvaluation Evaluate(string keyword, CompiledRuleSet ruleSet, EvaluationContext context) + public static KeywordEvaluation Evaluate(KeywordData keyword, CompiledRuleSet ruleSet, EvaluationContext context) { if (ruleSet.IsDelegated || ruleSet.Rules.Count == 0) return KeywordEvaluation.Ignore; @@ -42,7 +43,9 @@ public static KeywordEvaluation Evaluate(string keyword, CompiledRuleSet ruleSet continue; failures ??= []; - var message = EvaluateMessage(assert.Message, node, ruleVariables); + var message = assert.Message is null + ? assert.TestText + : EvaluateMessage(assert.Message, node, ruleVariables); failures.Add(ComposePrefix(rule.Id, assert.Id, assert.Flag) + message); } } @@ -50,29 +53,12 @@ public static KeywordEvaluation Evaluate(string keyword, CompiledRuleSet ruleSet } catch (JqException ex) { - return new KeywordEvaluation - { - Keyword = keyword, - IsValid = false, - Error = ex.Message - }; - } - - if (failures is null) - { - return new KeywordEvaluation - { - Keyword = keyword, - IsValid = true - }; + return FailureKeyword.Fail(keyword, context, [ex.Message]); } - return new KeywordEvaluation - { - Keyword = keyword, - IsValid = false, - Error = string.Join("; ", failures) - }; + return failures is null + ? new KeywordEvaluation { Keyword = keyword.Handler.Name, IsValid = true } + : FailureKeyword.Fail(keyword, context, failures); } /// @@ -92,12 +78,12 @@ static void ApplyLets( { JsonElement bound = default; var any = false; - foreach (var result in let.Expression.Evaluate(input, variables)) + let.Expression.Evaluate(input, result => { bound = result; any = true; - break; - } + return false; + }, variables); variables[let.Name] = any ? bound : JsonNull; } @@ -146,24 +132,26 @@ public static string EvaluateMessage( JsonElement node, IReadOnlyDictionary variables) { + var text = ""; try { - foreach (var result in message.Evaluate(node, variables)) + message.Evaluate(node, result => { - return result.ValueKind switch + text = result.ValueKind switch { JsonValueKind.String => result.GetString() ?? "", JsonValueKind.Null => "", _ => result.GetRawText() }; - } + return false; + }, variables); } catch (JqException) { // Fall through to empty message on evaluation failure. } - return ""; + return text; } /// @@ -176,12 +164,22 @@ public static string PrepareMessageExpression(string message) if (trimmed.Length > 0 && trimmed[0] == '"') return message; - // Wrap as a jq string. Preserve \ so jq interpolation (\(.x)) works; - // only escape quotes and control characters. + // Wrap as a jq string. Outside interpolations, escape quotes and control characters + // and let a backslash keep the character after it; copy \(...) unchanged. var sb = new StringBuilder(message.Length + 2); sb.Append('"'); - foreach (var c in message) + var i = 0; + while (i < message.Length) { + var c = message[i]; + if (c == '\\' && i + 1 < message.Length) + { + var end = message[i + 1] == '(' ? InterpolationEnd(message, i + 2) : i + 2; + sb.Append(message, i, end - i); + i = end; + continue; + } + switch (c) { case '"': @@ -200,12 +198,62 @@ public static string PrepareMessageExpression(string message) sb.Append(c); break; } + + i++; } sb.Append('"'); return sb.ToString(); } + /// + /// Returns the index after the ) that closes an interpolation whose content starts at . + /// + static int InterpolationEnd(string s, int i) + { + var depth = 1; + while (i < s.Length && depth > 0) + { + var c = s[i]; + if (c == '"') + { + i = StringEnd(s, i + 1); + continue; + } + + if (c == '(') + depth++; + else if (c == ')') + depth--; + + i++; + } + + return i; + } + + /// + /// Returns the index after the " that closes a jq string literal whose content starts at . + /// + static int StringEnd(string s, int i) + { + while (i < s.Length) + { + var c = s[i]; + if (c == '\\' && i + 1 < s.Length) + { + i = s[i + 1] == '(' ? InterpolationEnd(s, i + 2) : i + 2; + continue; + } + + i++; + if (c == '"') + break; + } + + return i; + } + public static JqExpression ParseExpression(string expression, string role) { try diff --git a/src/Jsontron/Jsontron.csproj b/dotnet/Jsontron/Jsontron.csproj similarity index 84% rename from src/Jsontron/Jsontron.csproj rename to dotnet/Jsontron/Jsontron.csproj index d6919a9..6d5031b 100644 --- a/src/Jsontron/Jsontron.csproj +++ b/dotnet/Jsontron/Jsontron.csproj @@ -1,11 +1,11 @@ -๏ปฟ + net10.0 Jsontron - + runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Jsontron/Keywords/AssertKeyword.cs b/dotnet/Jsontron/Keywords/AssertKeyword.cs similarity index 92% rename from src/Jsontron/Keywords/AssertKeyword.cs rename to dotnet/Jsontron/Keywords/AssertKeyword.cs index 98246d6..8121de7 100644 --- a/src/Jsontron/Keywords/AssertKeyword.cs +++ b/dotnet/Jsontron/Keywords/AssertKeyword.cs @@ -39,11 +39,12 @@ public void BuildSubschemas(KeywordData keyword, BuildContext context) lets = RuleSetCompiler.ParseLet(letEl); keyword.Value = RuleSetCompiler.CompileSugarOnly(asserts, reports, lets); + FailureKeyword.Build(keyword, context); } public KeywordEvaluation Evaluate(KeywordData keyword, EvaluationContext context) { var ruleSet = (CompiledRuleSet)keyword.Value!; - return JqEvaluation.Evaluate(Name, ruleSet, context); + return JqEvaluation.Evaluate(keyword, ruleSet, context); } } diff --git a/dotnet/Jsontron/Keywords/FailureKeyword.cs b/dotnet/Jsontron/Keywords/FailureKeyword.cs new file mode 100644 index 0000000..f2b7baa --- /dev/null +++ b/dotnet/Jsontron/Keywords/FailureKeyword.cs @@ -0,0 +1,79 @@ +using System.Text.Json; +using Json.Pointer; +using Json.Schema; +using SchemaDialect = Json.Schema.Dialect; + +namespace Jsontron.Keywords; + +/// +/// Reports each Jsontron failure as its own validation error. +/// +/// +/// A carries a single , and +/// can only be created by evaluating a . +/// So the owning keyword builds one private subschema { "<keyword>": null } whose only +/// keyword is this handler, and evaluates it once per failure: each evaluation is one entry of +/// , at the instance location of the schema object, with the +/// failure text as its error under the Jsontron keyword name. The text travels as the +/// of that evaluation. +/// +sealed class FailureKeyword : IKeywordHandler +{ + static readonly Dictionary Nodes = new[] { "rules", "assert", "report" } + .ToDictionary(name => name, name => ( + new SchemaDialect([new FailureKeyword(name)]), + JsonDocument.Parse($$"""{ "{{name}}": null }""").RootElement)); + + FailureKeyword(string name) => Name = name; + + public string Name { get; } + + /// + /// Builds the failure subschema of as its only subschema. + /// + public static void Build(KeywordData keyword, BuildContext context) + { + var (dialect, schema) = Nodes[keyword.Handler.Name]; + var nodeContext = context; + nodeContext.Dialect = dialect; + nodeContext.LocalSchema = schema; + nodeContext.RelativePath = JsonPointer.Empty; + keyword.Subschemas = [JsonSchema.BuildNode(nodeContext)]; + } + + /// + /// Returns the evaluation of a keyword that failed with the given texts, one error each. + /// + public static KeywordEvaluation Fail(KeywordData keyword, EvaluationContext context, IReadOnlyList errors) + { + var name = keyword.Handler.Name; + if (context.CanOptimize) + return new KeywordEvaluation { Keyword = name, IsValid = false }; + + var node = keyword.Subschemas[0]; + var details = new EvaluationResults[errors.Count]; + for (var i = 0; i < errors.Count; i++) + { + details[i] = node.Evaluate(context with + { + Instance = JsonSerializer.SerializeToElement(errors[i]), + EvaluationPath = context.EvaluationPath.Combine(name), + }); + } + + return new KeywordEvaluation { Keyword = name, IsValid = false, Details = details }; + } + + public object? ValidateKeywordValue(JsonElement value) => null; + + public void BuildSubschemas(KeywordData keyword, BuildContext context) + { + } + + public KeywordEvaluation Evaluate(KeywordData keyword, EvaluationContext context) => new() + { + Keyword = Name, + IsValid = false, + Error = context.Instance.GetString(), + }; +} diff --git a/src/Jsontron/Keywords/LetKeyword.cs b/dotnet/Jsontron/Keywords/LetKeyword.cs similarity index 100% rename from src/Jsontron/Keywords/LetKeyword.cs rename to dotnet/Jsontron/Keywords/LetKeyword.cs diff --git a/src/Jsontron/Keywords/ReportKeyword.cs b/dotnet/Jsontron/Keywords/ReportKeyword.cs similarity index 92% rename from src/Jsontron/Keywords/ReportKeyword.cs rename to dotnet/Jsontron/Keywords/ReportKeyword.cs index 2b35930..0d3f6f2 100644 --- a/src/Jsontron/Keywords/ReportKeyword.cs +++ b/dotnet/Jsontron/Keywords/ReportKeyword.cs @@ -38,11 +38,12 @@ public void BuildSubschemas(KeywordData keyword, BuildContext context) lets = RuleSetCompiler.ParseLet(letEl); keyword.Value = RuleSetCompiler.CompileSugarOnly([], reports, lets); + FailureKeyword.Build(keyword, context); } public KeywordEvaluation Evaluate(KeywordData keyword, EvaluationContext context) { var ruleSet = (CompiledRuleSet)keyword.Value!; - return JqEvaluation.Evaluate(Name, ruleSet, context); + return JqEvaluation.Evaluate(keyword, ruleSet, context); } } diff --git a/src/Jsontron/Keywords/RulesKeyword.cs b/dotnet/Jsontron/Keywords/RulesKeyword.cs similarity index 93% rename from src/Jsontron/Keywords/RulesKeyword.cs rename to dotnet/Jsontron/Keywords/RulesKeyword.cs index 6063543..c715448 100644 --- a/src/Jsontron/Keywords/RulesKeyword.cs +++ b/dotnet/Jsontron/Keywords/RulesKeyword.cs @@ -40,11 +40,12 @@ public void BuildSubschemas(KeywordData keyword, BuildContext context) lets = RuleSetCompiler.ParseLet(letEl); keyword.Value = RuleSetCompiler.Compile(rules, lets); + FailureKeyword.Build(keyword, context); } public KeywordEvaluation Evaluate(KeywordData keyword, EvaluationContext context) { var ruleSet = (CompiledRuleSet)keyword.Value!; - return JqEvaluation.Evaluate(Name, ruleSet, context); + return JqEvaluation.Evaluate(keyword, ruleSet, context); } } diff --git a/src/Jsontron/MetaSchemas.cs b/dotnet/Jsontron/MetaSchemas.cs similarity index 100% rename from src/Jsontron/MetaSchemas.cs rename to dotnet/Jsontron/MetaSchemas.cs diff --git a/dotnet/Jsontron/Model/AssertSpec.cs b/dotnet/Jsontron/Model/AssertSpec.cs new file mode 100644 index 0000000..a262b10 --- /dev/null +++ b/dotnet/Jsontron/Model/AssertSpec.cs @@ -0,0 +1,6 @@ +namespace Jsontron; + +/// +/// Uncompiled assert specification (test and optional message source text). +/// +readonly record struct AssertSpec(string Test, string? Message, string? Id = null, string? Flag = null); diff --git a/src/Jsontron/Model/CompiledAssert.cs b/dotnet/Jsontron/Model/CompiledAssert.cs similarity index 66% rename from src/Jsontron/Model/CompiledAssert.cs rename to dotnet/Jsontron/Model/CompiledAssert.cs index 1dcf409..3433d2f 100644 --- a/src/Jsontron/Model/CompiledAssert.cs +++ b/dotnet/Jsontron/Model/CompiledAssert.cs @@ -1,4 +1,4 @@ -using Devlooped; +using JQLite; namespace Jsontron; @@ -6,19 +6,24 @@ namespace Jsontron; /// Assert with pre-parsed jq expressions for the test and message. /// /// +/// is when the item has no message: +/// its failure text is then , taken literally. +/// /// When is , this represents a /// report: it fails when the test IS jq-truthy (Schematron report semantics). /// Otherwise it fails when the test is NOT truthy (Schematron assert semantics). /// sealed class CompiledAssert( JqExpression test, - JqExpression message, + string testText, + JqExpression? message, bool negate = false, string? id = null, string? flag = null) { public JqExpression Test { get; } = test; - public JqExpression Message { get; } = message; + public string TestText { get; } = testText; + public JqExpression? Message { get; } = message; public bool Negate { get; } = negate; public string? Id { get; } = id; public string? Flag { get; } = flag; diff --git a/src/Jsontron/Model/CompiledLet.cs b/dotnet/Jsontron/Model/CompiledLet.cs similarity index 94% rename from src/Jsontron/Model/CompiledLet.cs rename to dotnet/Jsontron/Model/CompiledLet.cs index ab2c569..28a7143 100644 --- a/src/Jsontron/Model/CompiledLet.cs +++ b/dotnet/Jsontron/Model/CompiledLet.cs @@ -1,4 +1,4 @@ -using Devlooped; +using JQLite; namespace Jsontron; diff --git a/src/Jsontron/Model/CompiledRule.cs b/dotnet/Jsontron/Model/CompiledRule.cs similarity index 97% rename from src/Jsontron/Model/CompiledRule.cs rename to dotnet/Jsontron/Model/CompiledRule.cs index bf5a27a..c8a5e56 100644 --- a/src/Jsontron/Model/CompiledRule.cs +++ b/dotnet/Jsontron/Model/CompiledRule.cs @@ -1,4 +1,4 @@ -using Devlooped; +using JQLite; namespace Jsontron; diff --git a/src/Jsontron/Model/CompiledRuleSet.cs b/dotnet/Jsontron/Model/CompiledRuleSet.cs similarity index 100% rename from src/Jsontron/Model/CompiledRuleSet.cs rename to dotnet/Jsontron/Model/CompiledRuleSet.cs diff --git a/src/Jsontron/Model/LetSpec.cs b/dotnet/Jsontron/Model/LetSpec.cs similarity index 100% rename from src/Jsontron/Model/LetSpec.cs rename to dotnet/Jsontron/Model/LetSpec.cs diff --git a/src/Jsontron/Model/RuleSetCompiler.cs b/dotnet/Jsontron/Model/RuleSetCompiler.cs similarity index 93% rename from src/Jsontron/Model/RuleSetCompiler.cs rename to dotnet/Jsontron/Model/RuleSetCompiler.cs index e7dc048..0ccd29b 100644 --- a/src/Jsontron/Model/RuleSetCompiler.cs +++ b/dotnet/Jsontron/Model/RuleSetCompiler.cs @@ -55,8 +55,7 @@ static AssertSpec ParseAssertItem(JsonElement value, string keyword) if (string.IsNullOrWhiteSpace(expr)) throw new JsonSchemaException($"'{keyword}' string must not be empty."); - // Shorthand: test and message source are the same expression text. - return new AssertSpec(expr, expr); + return new AssertSpec(expr, null); } if (value.ValueKind is not JsonValueKind.Object) @@ -70,18 +69,13 @@ static AssertSpec ParseAssertItem(JsonElement value, string keyword) if (string.IsNullOrWhiteSpace(test)) throw new JsonSchemaException($"'{keyword}' test must not be empty."); - string message; + string? message = null; if (value.TryGetProperty("message", out var messageEl)) { if (messageEl.ValueKind is not JsonValueKind.String) throw new JsonSchemaException($"'{keyword}' message must be a string."); - message = messageEl.GetString() - ?? throw new JsonSchemaException($"'{keyword}' message must not be null."); - } - else - { - message = test; + message = messageEl.GetString(); } var id = ParseOptionalLabel(value, "id", $"'{keyword}' id"); @@ -219,20 +213,14 @@ static IReadOnlyList ParseRuleItems(JsonElement array, int ruleIndex throw new JsonSchemaException( $"'rules[{ruleIndex}].{name}[{itemIndex}].test' must not be empty."); - string message; + string? message = null; if (el.TryGetProperty("message", out var messageEl)) { if (messageEl.ValueKind is not JsonValueKind.String) throw new JsonSchemaException( $"'rules[{ruleIndex}].{name}[{itemIndex}].message' must be a string."); - message = messageEl.GetString() - ?? throw new JsonSchemaException( - $"'rules[{ruleIndex}].{name}[{itemIndex}].message' must not be null."); - } - else - { - message = test; + message = messageEl.GetString(); } var itemId = ParseOptionalLabel(el, "id", $"'rules[{ruleIndex}].{name}[{itemIndex}].id'"); @@ -352,15 +340,15 @@ public static CompiledRuleSet Compile( foreach (var assert in rule.Asserts) { var test = JqEvaluation.ParseExpression(assert.Test, "test"); - var message = JqEvaluation.ParseMessage(assert.Message); - asserts.Add(new CompiledAssert(test, message, negate: false, assert.Id, assert.Flag)); + var message = assert.Message is null ? null : JqEvaluation.ParseMessage(assert.Message); + asserts.Add(new CompiledAssert(test, assert.Test, message, negate: false, assert.Id, assert.Flag)); } foreach (var report in rule.Reports) { var test = JqEvaluation.ParseExpression(report.Test, "test"); - var message = JqEvaluation.ParseMessage(report.Message); - asserts.Add(new CompiledAssert(test, message, negate: true, report.Id, report.Flag)); + var message = report.Message is null ? null : JqEvaluation.ParseMessage(report.Message); + asserts.Add(new CompiledAssert(test, report.Test, message, negate: true, report.Id, report.Flag)); } var lets = CompileLets(rule.Lets); diff --git a/src/Jsontron/Model/RuleSpec.cs b/dotnet/Jsontron/Model/RuleSpec.cs similarity index 100% rename from src/Jsontron/Model/RuleSpec.cs rename to dotnet/Jsontron/Model/RuleSpec.cs diff --git a/src/Jsontron/Vocabulary.cs b/dotnet/Jsontron/Vocabulary.cs similarity index 100% rename from src/Jsontron/Vocabulary.cs rename to dotnet/Jsontron/Vocabulary.cs diff --git a/src/Jsontron/readme.md b/dotnet/Jsontron/readme.md similarity index 100% rename from src/Jsontron/readme.md rename to dotnet/Jsontron/readme.md diff --git a/dotnet/Tests/ApiTests.cs b/dotnet/Tests/ApiTests.cs new file mode 100644 index 0000000..8d234af --- /dev/null +++ b/dotnet/Tests/ApiTests.cs @@ -0,0 +1,102 @@ +using System.Text.Json; +using Json.Schema; + +namespace Jsontron.Tests; + +/// +/// .NET-specific surface: registration, the dialect, exception types and the shape of the +/// reported errors. Jsontron semantics are covered by . +/// +public class ApiTests +{ + static ApiTests() => MetaSchemas.Register(); + + static JsonElement Json(string json) => JsonDocument.Parse(json).RootElement; + + [Fact] + public void Register_is_idempotent_and_loads_meta_schema() + { + MetaSchemas.Register(); + MetaSchemas.Register(); + + Assert.NotNull(MetaSchemas.Jsontron); + Assert.False(JsonSchema.FromText("""{ "assert": "false" }""").Evaluate(Json("{}")).IsValid); + } + + [Fact] + public void Jsontron_dialect_is_selected_by_schema_uri() + { + var schema = JsonSchema.FromText( + $$""" + { + "$schema": "{{Dialect.Id}}", + "assert": { "test": ".a", "message": "a required" } + } + """); + + var result = schema.Evaluate(Json("{}")); + + Assert.False(result.IsValid); + } + + [Theory] + [InlineData("""{ "assert": 42 }""")] + [InlineData("""{ "assert": ".a |" }""")] + [InlineData("""{ "let": { "root": "." } }""")] + public void Build_errors_are_JsonSchemaException(string schema) + => Assert.ThrowsAny(() => JsonSchema.FromText(schema)); + + [Fact] + public void Each_failure_is_its_own_error_at_the_instance_location() + { + var schema = JsonSchema.FromText( + """ + { + "properties": { + "order": { + "rules": [ + { + "context": ".lines[]", + "asserts": [ { "test": ". > 0", "message": "line \\(.) must be positive" } ] + } + ] + } + } + } + """); + + var result = schema.Evaluate(Json("""{ "order": { "lines": [ -1, 2, -3 ] } }"""), + new EvaluationOptions { OutputFormat = OutputFormat.List }); + + Assert.False(result.IsValid); + var errors = result.Details!.Where(x => x.Errors?.ContainsKey("rules") == true).ToList(); + Assert.Equal(["line -1 must be positive", "line -3 must be positive"], errors.Select(x => x.Errors!["rules"])); + Assert.All(errors, x => + { + Assert.Equal("/order", x.InstanceLocation.ToString()); + Assert.Equal("/properties/order/rules", x.EvaluationPath.ToString()); + }); + } + + [Fact] + public void Evaluation_error_is_one_error() + { + var schema = JsonSchema.FromText("""{ "assert": [ ".a.b", ".c.d" ] }"""); + + var result = schema.Evaluate(Json("""{ "a": 1, "c": 1 }"""), + new EvaluationOptions { OutputFormat = OutputFormat.List }); + + Assert.False(result.IsValid); + Assert.Single(result.Details!, x => x.Errors?.ContainsKey("assert") == true); + } + + [Fact] + public void Flag_output_reports_invalid() + { + var schema = JsonSchema.FromText("""{ "assert": ".a" }"""); + + var result = schema.Evaluate(Json("{}"), new EvaluationOptions { OutputFormat = OutputFormat.Flag }); + + Assert.False(result.IsValid); + } +} diff --git a/dotnet/Tests/ConformanceSuite.cs b/dotnet/Tests/ConformanceSuite.cs new file mode 100644 index 0000000..0dd658b --- /dev/null +++ b/dotnet/Tests/ConformanceSuite.cs @@ -0,0 +1,106 @@ +using System.Reflection; +using System.Text.Json; +using Json.Schema; + +namespace Jsontron.Tests; + +/// +/// Runs the language-neutral conformance suite in the repository's tests/ folder, +/// one test case per group (build errors) or per test (validations). See tests/readme.md. +/// +public class ConformanceSuite +{ + static ConformanceSuite() => MetaSchemas.Register(); + + static readonly HashSet JsontronKeywords = ["rules", "assert", "report"]; + + public static string SuiteDirectory { get; } = typeof(ConformanceSuite).Assembly + .GetCustomAttributes() + .Single(x => x.Key == "SuiteDirectory").Value!; + + public static IEnumerable Cases() + { + foreach (var file in SuiteFiles()) + { + using var document = JsonDocument.Parse(File.ReadAllText(file)); + var name = Path.GetFileName(file); + var groupIndex = 0; + foreach (var group in document.RootElement.EnumerateArray()) + { + var groupDescription = group.GetProperty("description").GetString()!; + if (group.TryGetProperty("tests", out var tests)) + { + var testIndex = 0; + foreach (var test in tests.EnumerateArray()) + { + yield return [$"{name}: {groupDescription} / {test.GetProperty("description").GetString()}", name, groupIndex, testIndex]; + testIndex++; + } + } + else + { + yield return [$"{name}: {groupDescription}", name, groupIndex, -1]; + } + + groupIndex++; + } + } + } + + static string[] SuiteFiles() => Directory.Exists(SuiteDirectory) + ? [.. Directory.GetFiles(SuiteDirectory, "*.json") + .Where(x => !Path.GetFileName(x).Equals("schema.json", StringComparison.OrdinalIgnoreCase)) + .Order(StringComparer.Ordinal)] + : []; + + [Fact] + public void Suite_is_present() + { + Assert.True(Directory.Exists(SuiteDirectory), $"Conformance suite not found at {SuiteDirectory}."); + Assert.NotEmpty(SuiteFiles()); + Assert.NotEmpty(Cases()); + } + + [Theory] + [MemberData(nameof(Cases))] + public void Run(string description, string file, int groupIndex, int testIndex) + { + _ = description; + + using var document = JsonDocument.Parse(File.ReadAllText(Path.Combine(SuiteDirectory, file))); + var group = document.RootElement[groupIndex]; + var schemaElement = group.GetProperty("schema"); + + if (testIndex < 0) + { + Assert.True(group.GetProperty("buildError").GetBoolean()); + Assert.ThrowsAny(() => JsonSchema.Build(schemaElement)); + return; + } + + var schema = JsonSchema.Build(schemaElement); + var test = group.GetProperty("tests")[testIndex]; + var results = schema.Evaluate(test.GetProperty("data"), new EvaluationOptions { OutputFormat = OutputFormat.Hierarchical }); + + var errors = new List(); + CollectErrors(results, errors); + + Assert.True(test.GetProperty("valid").GetBoolean() == results.IsValid, + $"Expected valid={test.GetProperty("valid").GetBoolean()}, got {results.IsValid}. Jsontron errors: [{string.Join(", ", errors)}]"); + + if (test.TryGetProperty("errors", out var expectedErrors)) + { + var expected = expectedErrors.EnumerateArray().Select(x => x.GetString()!).Order(StringComparer.Ordinal).ToArray(); + Assert.Equal(expected, errors.Order(StringComparer.Ordinal).ToArray()); + } + } + + static void CollectErrors(EvaluationResults result, List errors) + { + if (result.Errors is not null) + errors.AddRange(result.Errors.Where(x => JsontronKeywords.Contains(x.Key)).Select(x => x.Value)); + + foreach (var detail in result.Details ?? []) + CollectErrors(detail, errors); + } +} diff --git a/src/Tests/Tests.csproj b/dotnet/Tests/Tests.csproj similarity index 74% rename from src/Tests/Tests.csproj rename to dotnet/Tests/Tests.csproj index 524fc20..7498250 100644 --- a/src/Tests/Tests.csproj +++ b/dotnet/Tests/Tests.csproj @@ -1,4 +1,4 @@ -๏ปฟ + net10.0 @@ -12,6 +12,9 @@ + + + diff --git a/src/icon.png b/dotnet/icon.png similarity index 100% rename from src/icon.png rename to dotnet/icon.png diff --git a/src/nuget.config b/dotnet/nuget.config similarity index 100% rename from src/nuget.config rename to dotnet/nuget.config diff --git a/js/.gitignore b/js/.gitignore new file mode 100644 index 0000000..0abad90 --- /dev/null +++ b/js/.gitignore @@ -0,0 +1,7 @@ +node_modules/ +dist/ +*.tgz +# copied from the repository root when packing +/license.txt +# The root .gitignore (synced from upstream) ignores lock files; npm ci needs this one. +!package-lock.json diff --git a/js/package-lock.json b/js/package-lock.json new file mode 100644 index 0000000..3a53206 --- /dev/null +++ b/js/package-lock.json @@ -0,0 +1,2171 @@ +{ + "name": "@devlooped/jsontron", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@devlooped/jsontron", + "version": "0.0.0", + "license": "MIT", + "dependencies": { + "@devlooped/jqlite": "^1.0.0" + }, + "devDependencies": { + "@types/node": "^20.19.43", + "ajv": "^8.20.0", + "tsup": "^8.5.1", + "typescript": "^5.9.3", + "vitest": "^3.2.7" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "ajv": "^8.12.0" + } + }, + "node_modules/@devlooped/jqlite": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@devlooped/jqlite/-/jqlite-1.0.0.tgz", + "integrity": "sha512-JDbZJ2JDaQrguD1/o4o7ej6tpNuWIJ2u8JahDYx3mzVgaE+q5r/az9ZOB1NG313JTSJd8kK9NHCGesX/USd6Rw==", + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz", + "integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.7.tgz", + "integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz", + "integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.7.tgz", + "integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz", + "integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz", + "integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz", + "integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz", + "integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz", + "integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz", + "integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz", + "integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz", + "integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz", + "integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz", + "integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz", + "integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz", + "integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz", + "integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz", + "integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz", + "integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz", + "integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz", + "integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz", + "integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz", + "integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz", + "integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz", + "integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz", + "integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.68.5.tgz", + "integrity": "sha512-4iPGohjhOlA8ovAwOrHcbsLFw2X0lG49y2iWSlyLrRLJMO47D+XNM930CcGVQKPUpCsDfCdK3BV0y1ki6OBdhw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.68.5.tgz", + "integrity": "sha512-mBK6NsYThYGRkGy8uX7fODOIT0YHz9UyvtYv/fhqdfEZw8Sg2kPiuUsQ8OmzRfq5ve0nHqZVDz2zLOy1xVaVzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-x64": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-x64/-/rollup-android-x64-4.68.5.tgz", + "integrity": "sha512-8D/A3B5bsLlBcVGsUN+IWcA0wreB+Fvmvs3PLBHyEq3itxGefdPsubG/tPHvezUKPTDAh05YoutzsVFDxkcrJQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.68.5.tgz", + "integrity": "sha512-xJVTzKZnwwQsQ5WA9cV4Q8l1SVYF9UyVa/3ECoCFfgtow4MUt7HcI3AB8Hwa/4790fimHPXzYfsuyMp67ErQ8w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.68.5.tgz", + "integrity": "sha512-0Ft351J6xgaXhBtsRtV1qC1iFRSGzOoEpqbfIw5kPA1/R2ldOON8IVHx15XK6X46OI1QvxkETmWT+BIQxfHiOQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.68.5.tgz", + "integrity": "sha512-crcRf4EJ792/UuuPf8QduPogDOS9t6E7Mlkvgk8KSBQ/r+ZYyL4VKLEg4GmNmz4AUjq/Mr+4fHJ/RqtCFXq47w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.68.5.tgz", + "integrity": "sha512-6SrbCoHnaFiipnX4TsDnQ74Zd8puOFQma6WdXDvnh0/Oy5Ash2RbNbeOdfbQNQOyNZe65eAg/G/U+EOoaR284w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.68.5.tgz", + "integrity": "sha512-Du8EftwTEY5i9H/VmLrvHrv8W4WpnLSvlT4/th5zQR10baXOQM/8Vn+q4MkNZrWwwulUuhuAUItevugalTNCLA==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.68.5.tgz", + "integrity": "sha512-eT4t5h+qexha98N75YpiKMY1XDfimwkVL4TCHgQXr3JRFEqRacd38ldXB7dAAi5G62Mkuxlvw7VBHe5UXY2UHw==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.68.5.tgz", + "integrity": "sha512-jUsTbXqgd+cJlwgKePc56J8Yie+JZRWl7xiViSR2eQuloZ26PzWCS7ZJrCEZRmY7vrqhnvnbj6fP1ikinE0dfQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.68.5.tgz", + "integrity": "sha512-HHjSkN3VAI8ZD45xEO4WcV5+yUB04vpR0r5g0ayLX8YfafV61hAIWoh8Qa22HujnxEtOXYDstF4qKbWGicI2RA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.68.5.tgz", + "integrity": "sha512-Y//CvF+v/RiwP6ZscB23xFU+x8BtSbRpwEnVb6140X1TBqSjrZwQwdH/hRCG2FKBaUF2sWsOVjdeZ5UmsF5Cqg==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.68.5.tgz", + "integrity": "sha512-O3fyuDSEV+sXQNTfVfZFPCdc5QymYVxS4PT7YXxsouO/LZhmYy8y6xNZJx9tBQCiR96c2sBfRNLRztkhnvahcg==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.68.5.tgz", + "integrity": "sha512-xIzFIoRROEVGJZBc/ljGteOcF/sA6Hjuz+x3zHNdcFc24xlVenPm3RPTOJfNvNVF0MZTyfGq1YYIhG4Tj/nYiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.68.5.tgz", + "integrity": "sha512-srRfsMFnBDxlmpXwlStiwUSQ/4jCbR4u4i52pZg+bV+Anni0V5EmDeHGZ4YbmTIvM+XhcvEecFcjHmZWFWzVpA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.68.5.tgz", + "integrity": "sha512-hkrVfI5WMnWaZg0vaM8DlJCRlIUhaRa3Z2BT99AuFl739uIcOnnvpYr7kVhUiPuCvHvWEPgExtXtgNRpBDuxbw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.68.5.tgz", + "integrity": "sha512-ZWDUe13obQhNg0qD1pkft3aWBZgDD26TO3ADvuJ2T9SN/T3h632VRVc+GDCjgRzEnd8a8yCOkl9opkkTPxhF0Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.68.5.tgz", + "integrity": "sha512-9TsAn9NJQv5NsyGS4yOmJZGlM2ASrzQXC6pc6hrjduk5QwtoapONtooLiDSJlPq6+IAwhS2AdJ9+B8tidcdh5w==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.68.5.tgz", + "integrity": "sha512-JK5S9YhArjVwuetZ9nf6/GdpiXLl7DAVTdRUpF40wVMQNq28hkBrQI1+xy9sqjqtPvW08xagGPfBCBj5wLerZA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.68.5.tgz", + "integrity": "sha512-pF0UxfDULcfZhdp5azfIvTW5c++AYjYs0Q8iTCzVCVzVH9+9e0Ah0vIZS3MIZbO7GoyPjTuPjAcUgQQvYbM81A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.68.5.tgz", + "integrity": "sha512-5bkgrD3xTj4pVAaKZ/D+GBWfWaJtorYRdj8i7nHcCsalDaIgiGVmCb/KucTO8P80UXCcPnqMJGcCS4xM94qsbw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.68.5.tgz", + "integrity": "sha512-Fu+Jd8JWALOrVQdXTBfqUgkDXqWYqWAfjrpvSuvqYOVaSfwwi2wc9TORUEbbyd/8dsAmHLi04K9FnIwnjvWoJQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.68.5.tgz", + "integrity": "sha512-WX+jUzphTWxca8eKMPtNSTW58aW6TxScbKQ3Tc0Nagjwrysy1Bu0Wl7BUt5STCPB+WM0EisGFFAyjfZ952f/JA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.68.5.tgz", + "integrity": "sha512-z7EKzmD+jJQ3/ISVQSBkLptuUhtYcPf9Vamg8Ovf2jnZMN/Zvf5xCxHPh+TWPoUx9knc1al4EIOi6c9XayVXyQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.68.5.tgz", + "integrity": "sha512-VnHYErHaF8wRwdvq0A92NHmE1/u0sbuSgyTgGyOrH1vO14GWhu9aXERntg9SPnZoyK/LM+X4YawBE4g1FNkLBA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.68.5.tgz", + "integrity": "sha512-gVfBrzSqeYl0/QRJegeK9njmGxojS3oiU9cAHNY0wU22AjS44dGzt4WnnuYsTCNO8P40H4Ulykg8cxq2zWWo9Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "20.19.43", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz", + "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@vitest/expect": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.7.tgz", + "integrity": "sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.7.tgz", + "integrity": "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "3.2.7", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.7.tgz", + "integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.7.tgz", + "integrity": "sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "3.2.7", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.7.tgz", + "integrity": "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.7.tgz", + "integrity": "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^4.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.7.tgz", + "integrity": "sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "loupe": "^3.1.4", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "dev": true, + "license": "MIT" + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/bundle-require": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz", + "integrity": "sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "load-tsconfig": "^0.2.3" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "peerDependencies": { + "esbuild": ">=0.18" + } + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/chai": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/check-error": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz", + "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/confbox": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", + "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/consola": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", + "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.10.0" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.7.tgz", + "integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.7", + "@esbuild/android-arm": "0.27.7", + "@esbuild/android-arm64": "0.27.7", + "@esbuild/android-x64": "0.27.7", + "@esbuild/darwin-arm64": "0.27.7", + "@esbuild/darwin-x64": "0.27.7", + "@esbuild/freebsd-arm64": "0.27.7", + "@esbuild/freebsd-x64": "0.27.7", + "@esbuild/linux-arm": "0.27.7", + "@esbuild/linux-arm64": "0.27.7", + "@esbuild/linux-ia32": "0.27.7", + "@esbuild/linux-loong64": "0.27.7", + "@esbuild/linux-mips64el": "0.27.7", + "@esbuild/linux-ppc64": "0.27.7", + "@esbuild/linux-riscv64": "0.27.7", + "@esbuild/linux-s390x": "0.27.7", + "@esbuild/linux-x64": "0.27.7", + "@esbuild/netbsd-arm64": "0.27.7", + "@esbuild/netbsd-x64": "0.27.7", + "@esbuild/openbsd-arm64": "0.27.7", + "@esbuild/openbsd-x64": "0.27.7", + "@esbuild/openharmony-arm64": "0.27.7", + "@esbuild/sunos-x64": "0.27.7", + "@esbuild/win32-arm64": "0.27.7", + "@esbuild/win32-ia32": "0.27.7", + "@esbuild/win32-x64": "0.27.7" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fix-dts-default-cjs-exports": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz", + "integrity": "sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "magic-string": "^0.30.17", + "mlly": "^1.7.4", + "rollup": "^4.34.8" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/joycon": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz", + "integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, + "node_modules/lilconfig": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.5.tgz", + "integrity": "sha512-aRAOI9Ia43ygL4o1EOmC/sc/0OFxrm7qcQngiIyWaqVnSnz932ybJ07zyCcgMNGSDP8Yxaf88Xj1zHEXmvQ4SA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true, + "license": "MIT" + }, + "node_modules/load-tsconfig": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/load-tsconfig/-/load-tsconfig-0.2.5.tgz", + "integrity": "sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/loupe": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/mlly": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz", + "integrity": "sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.16.0", + "pathe": "^2.0.3", + "pkg-types": "^1.3.1", + "ufo": "^1.6.3" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pirates": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", + "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/pkg-types": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", + "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.1.8", + "mlly": "^1.7.4", + "pathe": "^2.0.1" + } + }, + "node_modules/postcss": { + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-load-config": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz", + "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "lilconfig": "^3.1.1" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "jiti": ">=1.21.0", + "postcss": ">=8.0.9", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + }, + "postcss": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/rollup": { + "version": "4.68.5", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.5.tgz", + "integrity": "sha512-m6toRYCueVCY+5aEIriX7Dc36g3EHzn3Wk7xCW5aGgCQtTo4uXLZiZPNhDFMmPfVSvC92y3wEwIP2DCUp/ukXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.10" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.68.5", + "@rollup/rollup-android-arm64": "4.68.5", + "@rollup/rollup-android-x64": "4.68.5", + "@rollup/rollup-darwin-arm64": "4.68.5", + "@rollup/rollup-darwin-x64": "4.68.5", + "@rollup/rollup-freebsd-arm64": "4.68.5", + "@rollup/rollup-freebsd-x64": "4.68.5", + "@rollup/rollup-linux-arm-gnueabihf": "4.68.5", + "@rollup/rollup-linux-arm-musleabihf": "4.68.5", + "@rollup/rollup-linux-arm64-gnu": "4.68.5", + "@rollup/rollup-linux-arm64-musl": "4.68.5", + "@rollup/rollup-linux-loong64-gnu": "4.68.5", + "@rollup/rollup-linux-loong64-musl": "4.68.5", + "@rollup/rollup-linux-ppc64-gnu": "4.68.5", + "@rollup/rollup-linux-ppc64-musl": "4.68.5", + "@rollup/rollup-linux-riscv64-gnu": "4.68.5", + "@rollup/rollup-linux-riscv64-musl": "4.68.5", + "@rollup/rollup-linux-s390x-gnu": "4.68.5", + "@rollup/rollup-linux-x64-gnu": "4.68.5", + "@rollup/rollup-linux-x64-musl": "4.68.5", + "@rollup/rollup-openbsd-x64": "4.68.5", + "@rollup/rollup-openharmony-arm64": "4.68.5", + "@rollup/rollup-win32-arm64-msvc": "4.68.5", + "@rollup/rollup-win32-ia32-msvc": "4.68.5", + "@rollup/rollup-win32-x64-gnu": "4.68.5", + "@rollup/rollup-win32-x64-msvc": "4.68.5", + "fsevents": "~2.3.2" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/source-map": { + "version": "0.7.6", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz", + "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">= 12" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, + "node_modules/strip-literal": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz", + "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^9.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/sucrase": { + "version": "3.35.1", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", + "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "tinyglobby": "^0.2.11", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinypool": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", + "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.6.tgz", + "integrity": "sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "dev": true, + "license": "MIT", + "bin": { + "tree-kill": "cli.js" + } + }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/tsup": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/tsup/-/tsup-8.5.1.tgz", + "integrity": "sha512-xtgkqwdhpKWr3tKPmCkvYmS9xnQK3m3XgxZHwSUjvfTjp7YfXe5tT3GgWi0F2N+ZSMsOeWeZFh7ZZFg5iPhing==", + "dev": true, + "license": "MIT", + "dependencies": { + "bundle-require": "^5.1.0", + "cac": "^6.7.14", + "chokidar": "^4.0.3", + "consola": "^3.4.0", + "debug": "^4.4.0", + "esbuild": "^0.27.0", + "fix-dts-default-cjs-exports": "^1.0.0", + "joycon": "^3.1.1", + "picocolors": "^1.1.1", + "postcss-load-config": "^6.0.1", + "resolve-from": "^5.0.0", + "rollup": "^4.34.8", + "source-map": "^0.7.6", + "sucrase": "^3.35.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.11", + "tree-kill": "^1.2.2" + }, + "bin": { + "tsup": "dist/cli-default.js", + "tsup-node": "dist/cli-node.js" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@microsoft/api-extractor": "^7.36.0", + "@swc/core": "^1", + "postcss": "^8.4.12", + "typescript": ">=4.5.0" + }, + "peerDependenciesMeta": { + "@microsoft/api-extractor": { + "optional": true + }, + "@swc/core": { + "optional": true + }, + "postcss": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/ufo": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz", + "integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==", + "dev": true, + "license": "MIT" + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "7.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.8.tgz", + "integrity": "sha512-3tTi78MAKhVk9h+YZVXMQ8POmneJuE97QUPAWtJghHzhH7BAyiqQOC2KZh1DWOsu/USB2cRXhznPByaabvYXfw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.27.0 || ^0.28.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz", + "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vitest": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.7.tgz", + "integrity": "sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.7", + "@vitest/mocker": "3.2.7", + "@vitest/pretty-format": "^3.2.7", + "@vitest/runner": "3.2.7", + "@vitest/snapshot": "3.2.7", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.1", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.4", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.7", + "@vitest/ui": "3.2.7", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + } + } +} diff --git a/js/package.json b/js/package.json new file mode 100644 index 0000000..9064077 --- /dev/null +++ b/js/package.json @@ -0,0 +1,60 @@ +{ + "name": "@devlooped/jsontron", + "version": "0.0.0", + "description": "Jsontron: Schematron-style rules, assert, report and let keywords for JSON Schema (Ajv), with jq expressions.", + "license": "MIT", + "author": "Daniel Cazzulino", + "homepage": "https://github.com/devlooped/jsontron/tree/main/js#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/devlooped/jsontron.git", + "directory": "js" + }, + "keywords": [ + "ajv", + "json-schema", + "schematron", + "jq", + "jqlite", + "validation", + "business-rules" + ], + "type": "module", + "engines": { + "node": ">=20" + }, + "sideEffects": false, + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "dist", + "readme.md", + "license.txt" + ], + "scripts": { + "build": "tsup", + "prepack": "node -e \"require('node:fs').copyFileSync('../license.txt', 'license.txt')\"", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "peerDependencies": { + "ajv": "^8.12.0" + }, + "dependencies": { + "@devlooped/jqlite": "^1.0.0" + }, + "devDependencies": { + "@types/node": "^20.19.43", + "ajv": "^8.20.0", + "tsup": "^8.5.1", + "typescript": "^5.9.3", + "vitest": "^3.2.7" + } +} diff --git a/js/readme.md b/js/readme.md new file mode 100644 index 0000000..832ea52 --- /dev/null +++ b/js/readme.md @@ -0,0 +1,113 @@ +# Jsontron for JavaScript / TypeScript + +[Jsontron](../readme.md) for [Ajv](https://ajv.js.org): Schematron-style `rules`, `assert`, +`report` and `let` keywords for JSON Schema (draft 2020-12), whose `context` and `test` +expressions are [jq](https://jqlang.org), evaluated in-process by +[`@devlooped/jqlite`](https://www.npmjs.com/package/@devlooped/jqlite) (pure TypeScript, no +WebAssembly or native dependencies). + +- Structural validation stays with JSON Schema; cross-field business rules sit next to it. +- Implements the [Jsontron 0.2 specification](../spec/jsontron.md) and passes its + [conformance suite](../tests/readme.md). +- Fully synchronous in Node.js 20+ and browsers; Ajv strict mode stays on. + +## Quick start + +```sh +npm install ajv @devlooped/jsontron +``` + +```js +import Ajv2020 from "ajv/dist/2020.js"; +import { addJsontron } from "@devlooped/jsontron"; + +const ajv = addJsontron(new Ajv2020({ allErrors: true })); + +const validate = ajv.compile({ + type: "object", + required: ["orders", "policy", "approvedCustomers"], + rules: [ + { + context: ".orders[] | select(.total > 1000)", + asserts: [ + { + test: ".discount >= ($root.policy.minHighValueDiscount // 0.1)", + message: "High-value order \\(.id) discount \\(.discount) is below policy", + }, + { + test: ".customer.id | IN($root.approvedCustomers[])", + message: "Customer \\(.customer.id) is not on the approved list", + }, + ], + }, + ], +}); + +const valid = validate({ + policy: { minHighValueDiscount: 0.15 }, + approvedCustomers: ["acme", "globex"], + orders: [ + { id: "O-1001", total: 2500, discount: 0.05, customer: { id: "initech" } }, + { id: "O-1002", total: 80, discount: 0, customer: { id: "unknown" } }, + ], +}); + +// O-1001 fails both asserts (discount + customer). +// O-1002 is ignored by the rule (total โ‰ค 1000). +console.log(valid); // false +console.log(validate.errors.map((e) => e.message)); +// [ 'High-value order O-1001 discount 0.05 is below policy', +// 'Customer initech is not on the approved list' ] +``` + +The keywords, messages, labels and `let` bindings are described in the +[root readme](../readme.md#keywords) and defined by the [specification](../spec/jsontron.md). + +## Behaviour + +- `addJsontron(ajv)` adds the four keywords (`rules`, `assert`, `report`, `let`) to any Ajv + instance and returns it. +- `ajv.compile` validates every Jsontron keyword value and parses every jq expression in + isolation, throwing a `JsontronSchemaError` for invalid keyword shapes or invalid jq. +- Each schema object with a rule set lowers to one compiled `jqlite` expression + ([reference lowering](../spec/jsontron.md#7-reference-lowering)) and is reused on every + validation. The root document is passed in only when an expression references `$root`. + +## Errors + +Each failed assert or report is one Ajv error, at the instance location of the schema object +that holds the keywords: + +```js +{ keyword: "rules", instancePath: "/order", schemaPath: "#/properties/order/rules", + message: "[orders][flag=warning] order O-1 discount is below policy", params: {} } +``` + +`keyword` is the keyword that evaluates the schema object's rule set: `rules` when present, +else `assert`, else `report`. A jq error while evaluating (in a `let`, `context` or `test`) +discards the failures of that rule set and raises a single error whose `params` is +`{ evaluationError: "" }`. + +## Performance + +Each evaluation of a schema object converts its input to `jqlite` values (the instance, and +the whole document when an expression reads `$root`) and runs the compiled expression +in-process. For large arrays, prefer one rule at the level of the array with a `context` +expression over a rule set under `items` that reads `$root`, so the document is converted +once rather than per item. + +## Requirements + +- Node.js 20 or later (ESM), or modern browsers. +- Ajv 8 (peer dependency); the suite runs with `ajv/dist/2020`. +- Implements Jsontron specification 0.2 (`specVersion`); the meta-schema is exported as + `metaSchema`. + +## Development + +```sh +npm install +npm test # unit tests and the conformance suite in ../tests +npm run typecheck +npm run build # dist/: ESM and type declarations +``` diff --git a/js/src/compile.ts b/js/src/compile.ts new file mode 100644 index 0000000..812fb3b --- /dev/null +++ b/js/src/compile.ts @@ -0,0 +1,58 @@ +import { Jq, JqError, JqParseError, type JqExpression, type JsonInput } from "@devlooped/jqlite"; +import { expressions, lowerRuleSet } from "./lowering.js"; +import { buildRuleSet, type SchemaObject } from "./ruleset.js"; +import { JsontronSchemaError } from "./types.js"; + +/** The outcome of evaluating a rule set on one instance: its failure texts, or one evaluation error. */ +export type Evaluation = { readonly failures: readonly string[] } | { readonly error: string }; + +/** A rule set ready to evaluate. */ +export interface CompiledRuleSet { + readonly program: string; + evaluate(instance: unknown, root: unknown): Evaluation; +} + +/** + * The build-time step of spec section 6: validates the Jsontron keywords of a schema + * object, parses every jq expression in isolation, then lowers and compiles the rule set + * to one jqlite expression. + * + * Returns `undefined` when there is nothing to evaluate (no keyword, or a lone `let`). + * @throws {JsontronSchemaError} when a keyword value or an expression is invalid. + */ +export function compileRuleSet(schema: SchemaObject): CompiledRuleSet | undefined { + const ruleSet = buildRuleSet(schema); + for (const { where, expression } of expressions(ruleSet)) + parse(expression, `Invalid jq in '${where}'`); + if (ruleSet.rules.length === 0) return undefined; + + const { program, usesRoot } = lowerRuleSet(ruleSet); + // Each expression is valid on its own; the assembled program is compiled as well + // (spec section 6), in case some text is valid alone but not once embedded. + const compiled = parse(program, "Invalid jq rule set"); + + return { + program, + evaluate(instance, root) { + let results: unknown[]; + try { + results = compiled.evaluate({ root: usesRoot ? root : null, node: instance } as JsonInput); + } catch (e) { + if (e instanceof JqError) return { error: e.message }; + throw e; + } + const output = results[0]; + if (!Array.isArray(output)) return { error: `unexpected rule set output: ${JSON.stringify(output)}` }; + return { failures: output.map(String) }; + }, + }; +} + +function parse(expression: string, context: string): JqExpression { + try { + return Jq.parse(expression); + } catch (e) { + if (e instanceof JqParseError) throw new JsontronSchemaError(`${context}: ${e.message}`); + throw e; + } +} diff --git a/js/src/index.ts b/js/src/index.ts new file mode 100644 index 0000000..b843c6c --- /dev/null +++ b/js/src/index.ts @@ -0,0 +1,32 @@ +import type Ajv from "ajv/dist/core.js"; +import { keywordDefinitions } from "./keywords.js"; + +export type { JsontronEvaluationErrorParams } from "./keywords.js"; +export { metaSchema } from "./schema.js"; +export { + JsontronSchemaError, + type JsontronItem, + type JsontronKeywords, + type JsontronLet, + type JsontronRule, + type JsontronSugar, +} from "./types.js"; + +/** The version of the Jsontron specification this package implements. */ +export const specVersion = "0.2"; + +/** + * Adds the Jsontron keywords (`rules`, `assert`, `report`, `let`) to an Ajv instance + * and returns it. + * + * ```ts + * import Ajv2020 from "ajv/dist/2020.js"; + * import { addJsontron } from "@devlooped/jsontron"; + * + * const ajv = addJsontron(new Ajv2020({ allErrors: true })); + * ``` + */ +export function addJsontron(ajv: T): T { + for (const definition of keywordDefinitions()) ajv.addKeyword(definition); + return ajv; +} diff --git a/js/src/keywords.ts b/js/src/keywords.ts new file mode 100644 index 0000000..0a9a231 --- /dev/null +++ b/js/src/keywords.ts @@ -0,0 +1,50 @@ +import type { AnySchemaObject, DataValidationCxt, ErrorObject, FuncKeywordDefinition } from "ajv/dist/types/index.js"; +import { compileRuleSet, type CompiledRuleSet } from "./compile.js"; +import { KEYWORDS, type Keyword } from "./schema.js"; + +/** `params` of the Ajv error raised for a jq error while evaluating a rule set. */ +export interface JsontronEvaluationErrorParams { + /** The engine's error text; not normative. */ + evaluationError: string; +} + +type Validate = ((data: unknown, cxt?: DataValidationCxt) => boolean) & { errors?: Partial[] }; + +const alwaysValid: Validate = () => true; + +/** The keyword that evaluates the rule set of a schema object: `rules`, else `assert`, else `report`, else `let`. */ +function owner(schema: AnySchemaObject): Keyword { + return KEYWORDS.find((k) => schema[k] !== undefined) ?? "let"; +} + +/** The Ajv definitions of the four Jsontron keywords. */ +export function keywordDefinitions(): FuncKeywordDefinition[] { + // A schema object that Ajv compiles more than once is validated and lowered once. + const compiled = new WeakMap(); + + return KEYWORDS.map((keyword) => ({ + keyword, + errors: true, + compile(_value: unknown, parentSchema: AnySchemaObject): Validate { + // All four keywords are registered so that strict mode accepts them; the + // first present one validates and evaluates them all as one rule set. + if (owner(parentSchema) !== keyword) return alwaysValid; + if (!compiled.has(parentSchema)) compiled.set(parentSchema, compileRuleSet(parentSchema)); + const ruleSet = compiled.get(parentSchema); + if (!ruleSet) return alwaysValid; + + const validate: Validate = (data, cxt) => { + const result = ruleSet.evaluate(data, cxt ? cxt.rootData : data); + if ("error" in result) { + const params: JsontronEvaluationErrorParams = { evaluationError: result.error }; + validate.errors = [{ keyword, message: `jq evaluation error: ${result.error}`, params }]; + return false; + } + if (result.failures.length === 0) return true; + validate.errors = result.failures.map((message) => ({ keyword, message, params: {} })); + return false; + }; + return validate; + }, + })); +} diff --git a/js/src/lowering.ts b/js/src/lowering.ts new file mode 100644 index 0000000..68bf139 --- /dev/null +++ b/js/src/lowering.ts @@ -0,0 +1,90 @@ +import { messageExpression, messagePrefix } from "./messages.js"; +import type { Binding, Item, Rule, RuleSet } from "./ruleset.js"; + +/** A jq expression of a rule set and the variables in scope for it (spec section 6). */ +export interface ScopedExpression { + /** What the expression is, for error messages, such as `rules[0].context`. */ + readonly where: string; + readonly expression: string; + /** Variable names without `$`, `root` included. */ + readonly variables: readonly string[]; +} + +/** The program of a rule set (spec section 7). */ +export interface LoweredRuleSet { + /** One jq program: input `{ root, node }`, output the array of failure texts. */ + readonly program: string; + /** Whether any expression references `$root`, so that the root must be passed in. */ + readonly usesRoot: boolean; +} + +const STR = 'if type == "string" then . elif . == null then "" else tojson end'; +const ROOT = /\$root(?![A-Za-z0-9_])/; + +/** + * `โŸจxโŸฉ`: the expression and two newlines, so that a trailing comment cannot swallow what + * follows, even one that a final backslash continues onto the next line. + */ +const text = (expression: string) => `${expression}\n\n`; + +const lets = (bindings: readonly Binding[]) => + bindings.map((b) => `first((${text(b.expression)}), null) as $${b.name} | `).join(""); + +const truthy = (item: Item) => `([(${text(item.test)})] | length > 0 and all(.[]; . != null and . != false))`; + +function failureText(rule: Rule, item: Item): string { + const prefix = messagePrefix(rule.id, item); + if (item.message === undefined) return JSON.stringify(prefix + item.test); + return `(${JSON.stringify(prefix)} + (try first(((${text(messageExpression(item.message))}) | ${STR}), "") catch ""))`; +} + +function lowerRule(rule: Rule): string { + const items = [ + ...rule.asserts.map((a) => `(if ${truthy(a)} then empty else ${failureText(rule, a)} end)`), + ...rule.reports.map((r) => `(if ${truthy(r)} then ${failureText(rule, r)} else empty end)`), + ]; + return `((${text(rule.context)}) | ${lets(rule.let)}(${items.join(", ")}))`; +} + +/** Lowers a rule set to the single jq program of spec section 7. */ +export function lowerRuleSet(ruleSet: RuleSet): LoweredRuleSet { + const program = `.root as $root | .node | ${lets(ruleSet.let)}[ ${ruleSet.rules.map(lowerRule).join(", ")} ]`; + const usesRoot = expressions(ruleSet).some((e) => ROOT.test(e.expression)); + return { program, usesRoot }; +} + +/** + * Every jq expression of a rule set with the variables in scope for it: schema-level + * bindings see the ones before them, `context` sees the schema-level ones, rule-level + * bindings add to those in order, and tests and messages see all of the rule's. + */ +export function expressions(ruleSet: RuleSet): ScopedExpression[] { + const result: ScopedExpression[] = []; + const scope = ["root"]; + const bind = (bindings: readonly Binding[], where: string, variables: string[]) => { + for (const b of bindings) { + result.push({ where: `${where}.${b.name}`, expression: b.expression, variables: [...variables] }); + if (!variables.includes(b.name)) variables.push(b.name); + } + }; + bind(ruleSet.let, "let", scope); + ruleSet.rules.forEach((rule, r) => { + result.push({ where: `rules[${r}].context`, expression: rule.context, variables: [...scope] }); + const ruleScope = [...scope]; + bind(rule.let, `rules[${r}].let`, ruleScope); + const items = (kind: "asserts" | "reports", list: readonly Item[]) => + list.forEach((item, i) => { + const where = `rules[${r}].${kind}[${i}]`; + result.push({ where: `${where}.test`, expression: item.test, variables: ruleScope }); + if (item.message !== undefined) + result.push({ + where: `${where}.message`, + expression: messageExpression(item.message), + variables: ruleScope, + }); + }); + items("asserts", rule.asserts); + items("reports", rule.reports); + }); + return result; +} diff --git a/js/src/messages.ts b/js/src/messages.ts new file mode 100644 index 0000000..2f99560 --- /dev/null +++ b/js/src/messages.ts @@ -0,0 +1,71 @@ +import type { Item } from "./ruleset.js"; + +/** + * Turns a `message` into a jq expression (spec section 4): used as is when it starts + * with `"` (ignoring leading whitespace), otherwise wrapped as a jq string literal. + * Outside interpolations, `"`, newline, carriage return and tab are escaped and a + * backslash keeps the character after it; the text of a `\(...)` interpolation is + * copied unchanged. + */ +export function messageExpression(message: string): string { + if (message.trimStart().startsWith('"')) return message; + let out = '"'; + let i = 0; + while (i < message.length) { + const c = message[i]!; + if (c === "\\" && i + 1 < message.length) { + const end = message[i + 1] === "(" ? interpolationEnd(message, i + 2) : i + 2; + out += message.slice(i, end); + i = end; + } else { + out += ESCAPES[c] ?? c; + i++; + } + } + return `${out}"`; +} + +const ESCAPES: Record = { '"': '\\"', "\n": "\\n", "\r": "\\r", "\t": "\\t" }; + +/** The index after the `)` that closes an interpolation whose content starts at `i`. */ +function interpolationEnd(s: string, i: number): number { + let depth = 1; + while (i < s.length && depth > 0) { + const c = s[i]; + if (c === '"') { + i = stringEnd(s, i + 1); + continue; + } + if (c === "(") depth++; + else if (c === ")") depth--; + i++; + } + return i; +} + +/** The index after the `"` that closes a jq string literal whose content starts at `i`. */ +function stringEnd(s: string, i: number): number { + while (i < s.length) { + const c = s[i]; + if (c === "\\" && i + 1 < s.length) { + i = s[i + 1] === "(" ? interpolationEnd(s, i + 2) : i + 2; + continue; + } + i++; + if (c === '"') break; + } + return i; +} + +/** + * The prefix of a failure text (spec section 4): `[][][flag=]` + * and one space, or the empty string when no label is set. + */ +export function messagePrefix(ruleId: string | undefined, item: Pick): string { + const labels = [ + ruleId === undefined ? "" : `[${ruleId}]`, + item.id === undefined ? "" : `[${item.id}]`, + item.flag === undefined ? "" : `[flag=${item.flag}]`, + ].join(""); + return labels === "" ? "" : `${labels} `; +} diff --git a/js/src/ruleset.ts b/js/src/ruleset.ts new file mode 100644 index 0000000..6ca9662 --- /dev/null +++ b/js/src/ruleset.ts @@ -0,0 +1,110 @@ +import { validateKeyword } from "./schema.js"; +import { JsontronSchemaError, type JsontronItem, type JsontronLet, type JsontronRule } from "./types.js"; + +/** A `let` binding: `$name` bound to the first value of `expression`. */ +export interface Binding { + readonly name: string; + readonly expression: string; +} + +/** A normalized assert or report item. Labels are trimmed; `flag` holds `flag` or `role`. */ +export interface Item { + readonly test: string; + readonly message?: string; + readonly id?: string; + readonly flag?: string; +} + +/** A normalized rule. */ +export interface Rule { + readonly context: string; + readonly id?: string; + readonly let: readonly Binding[]; + readonly asserts: readonly Item[]; + readonly reports: readonly Item[]; +} + +/** The rule set of a schema object (spec section 2); without rules when the object has none. */ +export interface RuleSet { + readonly let: readonly Binding[]; + readonly rules: readonly Rule[]; +} + +/** A schema object; Jsontron reads its `rules`, `assert`, `report` and `let`. */ +export type SchemaObject = { readonly [keyword: string]: unknown }; + +/** + * Validates the Jsontron keywords of a schema object and builds its rule set + * (spec sections 1 and 2): `rules` in order, then the `assert` / `report` sugar + * merged into the first rule whose context is exactly `"."`, or a new one. + * + * When the object has none of `rules`, `assert`, `report`, the result has no rules: + * a lone `let` is checked at build time and never evaluated. + * @throws {JsontronSchemaError} when a keyword value is invalid. + */ +export function buildRuleSet(schema: SchemaObject): RuleSet { + const bindings = schema.let === undefined ? [] : toBindings(checked("let", schema.let) as JsontronLet); + + const rules: Rule[] = + schema.rules === undefined + ? [] + : (checked("rules", schema.rules) as JsontronRule[]).map((rule, index) => ({ + context: rule.context, + id: label(rule.id, `rules[${index}].id`), + let: rule.let === undefined ? [] : toBindings(rule.let), + asserts: (rule.asserts ?? []).map((item, i) => toItem(item, `rules[${index}].asserts[${i}]`)), + reports: (rule.reports ?? []).map((item, i) => toItem(item, `rules[${index}].reports[${i}]`)), + })); + + const asserts = sugar("assert", schema.assert); + const reports = sugar("report", schema.report); + if (asserts.length > 0 || reports.length > 0) { + const index = rules.findIndex((rule) => rule.context === "."); + const target = rules[index]; + if (target) + rules[index] = { + ...target, + asserts: [...target.asserts, ...asserts], + reports: [...target.reports, ...reports], + }; + else rules.push({ context: ".", let: [], asserts, reports }); + } + + return { let: bindings, rules }; +} + +function checked(keyword: "rules" | "assert" | "report" | "let", value: unknown): unknown { + validateKeyword(keyword, value); + return value; +} + +function sugar(keyword: "assert" | "report", value: unknown): Item[] { + if (value === undefined) return []; + checked(keyword, value); + const items = Array.isArray(value) ? (value as (string | JsontronItem)[]) : [value as string | JsontronItem]; + return items.map((item, i) => toItem(typeof item === "string" ? { test: item } : item, `${keyword}[${i}]`)); +} + +function toItem(item: JsontronItem, where: string): Item { + if (item.flag !== undefined && item.role !== undefined) + throw new JsontronSchemaError(`Invalid '${where}': 'flag' and 'role' are mutually exclusive.`); + return { + test: item.test, + message: item.message, + id: label(item.id, `${where}.id`), + flag: label(item.flag ?? item.role, `${where}.${item.flag !== undefined ? "flag" : "role"}`), + }; +} + +/** Labels are non-empty once trimmed; the meta-schema only checks `minLength`. */ +function label(value: string | undefined, where: string): string | undefined { + if (value === undefined) return undefined; + const trimmed = value.trim(); + if (trimmed === "") throw new JsontronSchemaError(`Invalid '${where}': must not be blank.`); + return trimmed; +} + +function toBindings(value: JsontronLet): Binding[] { + // Binding names cannot look like array indexes, so object key order is document order. + return Object.entries(value).map(([name, expression]) => ({ name, expression })); +} diff --git a/js/src/schema.ts b/js/src/schema.ts new file mode 100644 index 0000000..f080a04 --- /dev/null +++ b/js/src/schema.ts @@ -0,0 +1,39 @@ +import Ajv2020 from "ajv/dist/2020.js"; +import type { ValidateFunction } from "ajv"; +import metaSchemaJson from "../../schemas/jsontron-0.2.json"; +import { JsontronSchemaError } from "./types.js"; + +/** The Jsontron 0.2 meta-schema (`https://www.schemastore.org/jsontron-0.2.json`). */ +export const metaSchema: Readonly> = metaSchemaJson; + +/** The Jsontron keywords, in the order that decides which one evaluates the rule set. */ +export const KEYWORDS = ["rules", "assert", "report", "let"] as const; +export type Keyword = (typeof KEYWORDS)[number]; + +let validators: Record | undefined; + +function getValidators(): Record { + if (!validators) { + // A private instance, so that the options of the host Ajv do not change what is rejected. + const ajv = new Ajv2020({ allErrors: true, strict: false }); + ajv.addSchema(metaSchemaJson); + const id = metaSchemaJson.$id; + validators = Object.fromEntries( + KEYWORDS.map((k) => [k, ajv.compile({ $ref: `${id}#/properties/${k}` })]), + ) as Record; + } + return validators; +} + +/** + * Validates the value of one Jsontron keyword against the meta-schema. + * @throws {JsontronSchemaError} when it does not match. + */ +export function validateKeyword(keyword: Keyword, value: unknown): void { + const validate = getValidators()[keyword]; + if (validate(value)) return; + const details = (validate.errors ?? []) + .map((e) => `${keyword}${e.instancePath} ${e.message}`) + .join("; "); + throw new JsontronSchemaError(`Invalid '${keyword}': ${details}`); +} diff --git a/js/src/types.ts b/js/src/types.ts new file mode 100644 index 0000000..79af075 --- /dev/null +++ b/js/src/types.ts @@ -0,0 +1,37 @@ +/** An assert or report item of a rule (`asserts[]` / `reports[]`). */ +export interface JsontronItem { + test: string; + message?: string; + id?: string; + flag?: string; + /** Alias of `flag`; setting both is an error. */ + role?: string; +} + +/** The value of the `assert` and `report` keywords. */ +export type JsontronSugar = string | JsontronItem | (string | JsontronItem)[]; + +/** The value of a `let` keyword: binding name to jq expression, in document order. */ +export type JsontronLet = Record; + +/** A rule of the `rules` keyword. */ +export interface JsontronRule { + context: string; + id?: string; + let?: JsontronLet; + asserts?: JsontronItem[]; + reports?: JsontronItem[]; +} + +/** The Jsontron keywords of a schema object. */ +export interface JsontronKeywords { + rules?: JsontronRule[]; + assert?: JsontronSugar; + report?: JsontronSugar; + let?: JsontronLet; +} + +/** A keyword value that does not match the Jsontron 0.2 syntax, or a jq expression that does not compile. */ +export class JsontronSchemaError extends Error { + override name = "JsontronSchemaError"; +} diff --git a/js/test/ajv.test.ts b/js/test/ajv.test.ts new file mode 100644 index 0000000..4933ae0 --- /dev/null +++ b/js/test/ajv.test.ts @@ -0,0 +1,110 @@ +import Ajv2020 from "ajv/dist/2020.js"; +import { describe, expect, it } from "vitest"; +import { addJsontron, JsontronSchemaError, metaSchema, specVersion } from "../src/index.js"; + +const newAjv = () => addJsontron(new Ajv2020({ allErrors: true })); + +describe("Ajv keywords", () => { + it("exposes the meta-schema and the spec version", () => { + expect(metaSchema.$id).toBe("https://www.schemastore.org/jsontron-0.2.json"); + expect(specVersion).toBe("0.2"); + }); + + it("adds the keywords and returns the Ajv instance", () => { + const ajv = new Ajv2020(); + expect(addJsontron(ajv)).toBe(ajv); + }); + + it("raises one error per failure, at the instance location", () => { + const ajv = newAjv(); + const validate = ajv.compile({ + properties: { + order: { + rules: [ + { + id: "lines", + context: ".lines[]", + asserts: [{ test: ". > 0", message: "line \\(.) must be positive" }], + }, + ], + }, + }, + }); + expect(validate({ order: { lines: [1, -1, 0] } })).toBe(false); + expect(validate.errors).toMatchObject([ + { + keyword: "rules", + instancePath: "/order", + schemaPath: "#/properties/order/rules", + message: "[lines] line -1 must be positive", + params: {}, + }, + { keyword: "rules", instancePath: "/order", message: "[lines] line 0 must be positive" }, + ]); + }); + + it("names the keyword that owns the rule set", () => { + const ajv = newAjv(); + const validate = ajv.compile({ report: ".bad", let: { x: "1" } }); + expect(validate({ bad: true })).toBe(false); + expect(validate.errors).toMatchObject([{ keyword: "report", message: ".bad" }]); + }); + + it("raises one error for a jq runtime error", () => { + const ajv = newAjv(); + const validate = ajv.compile({ assert: [".a.b == 1", "false"] }); + expect(validate({ a: "text" })).toBe(false); + expect(validate.errors).toHaveLength(1); + expect(validate.errors?.[0]).toMatchObject({ + keyword: "assert", + params: { evaluationError: expect.any(String) }, + }); + expect(validate.errors?.[0]?.message).toMatch(/^jq evaluation error: /); + }); + + it("reads $root from nested locations", () => { + const ajv = newAjv(); + const data = { max: 2, items: [1, 3] }; + const validate = ajv.compile({ properties: { items: { items: { assert: ". <= $root.max" } } } }); + expect(validate(data)).toBe(false); + expect(validate.errors).toMatchObject([ + { keyword: "assert", instancePath: "/items/1", message: ". <= $root.max" }, + ]); + }); + + it("checks a lone let at compile time without evaluating it", () => { + const ajv = newAjv(); + const validate = ajv.compile({ let: { x: 'error("never")' } }); + expect(validate({})).toBe(true); + expect(() => ajv.compile({ let: { x: ".a |" } })).toThrow(/Invalid jq in 'let\.x'/); + }); + + it("rejects invalid keyword values and jq when compiling", () => { + const ajv = newAjv(); + expect(() => ajv.compile({ assert: { test: "true", flag: "a", role: "b" } })).toThrow(JsontronSchemaError); + expect(() => ajv.compile({ rules: [{ context: "." }] })).toThrow(/Invalid 'rules'/); + expect(() => ajv.compile({ assert: "true) , (false" })).toThrow(/Invalid jq in 'rules\[0\]\.asserts\[0\]\.test'/); + expect(() => ajv.compile({ assert: "no_such_function" })).toThrow(/Invalid jq in 'rules\[0\]\.asserts\[0\]\.test'/); + }); + + it("keeps a comment that ends in a backslash from swallowing the program", () => { + const ajv = newAjv(); + // jq 1.8 continues a comment onto the next line after a trailing backslash. + const validate = ajv.compile({ assert: ". > 0 # comment \\" }); + expect(validate(1)).toBe(true); + expect(validate(0)).toBe(false); + }); + + it("keeps strict mode on for other unknown keywords", () => { + const ajv = newAjv(); + expect(() => ajv.compile({ assert: "true", asert: "typo" })).toThrow(/unknown keyword/); + }); + + it("takes part in applicators as an assertion", () => { + const ajv = newAjv(); + const validate = ajv.compile({ if: { assert: '.kind == "a"' }, then: { required: ["x"] } }); + expect(validate({ kind: "a" })).toBe(false); + expect(validate({ kind: "b" })).toBe(true); + expect(validate({ kind: "a", x: 1 })).toBe(true); + }); +}); diff --git a/js/test/lowering.test.ts b/js/test/lowering.test.ts new file mode 100644 index 0000000..ba76dc3 --- /dev/null +++ b/js/test/lowering.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, it } from "vitest"; +import { expressions, lowerRuleSet } from "../src/lowering.js"; +import { messageExpression, messagePrefix } from "../src/messages.js"; +import { buildRuleSet } from "../src/ruleset.js"; + +describe("messageExpression", () => { + it("wraps plain text as a jq string, escaping quotes and control characters", () => { + expect(messageExpression('field "a" is\nrequired\tnow\r')).toBe('"field \\"a\\" is\\nrequired\\tnow\\r"'); + }); + + it("keeps backslashes so interpolation works", () => { + expect(messageExpression("Line \\(.sku) costs \\\\ 2")).toBe('"Line \\(.sku) costs \\\\ 2"'); + }); + + it("uses a message that starts with a quote as is, ignoring leading whitespace", () => { + expect(messageExpression('"got " + .b')).toBe('"got " + .b'); + expect(messageExpression(' "x" + "y"')).toBe(' "x" + "y"'); + }); + + it("wraps the empty message", () => { + expect(messageExpression("")).toBe('""'); + }); +}); + +describe("messagePrefix", () => { + it("joins the labels that are set, then one space", () => { + expect(messagePrefix("orders", { id: "high-value", flag: "warning" })).toBe("[orders][high-value][flag=warning] "); + expect(messagePrefix(undefined, { id: "i" })).toBe("[i] "); + expect(messagePrefix("r", {})).toBe("[r] "); + expect(messagePrefix(undefined, { flag: "info" })).toBe("[flag=info] "); + }); + + it("is empty without labels", () => { + expect(messagePrefix(undefined, {})).toBe(""); + }); +}); + +describe("lowerRuleSet", () => { + it("produces the program of the spec example", () => { + const { program, usesRoot } = lowerRuleSet( + buildRuleSet({ + let: { cap: ".policy.cap" }, + rules: [ + { + id: "orders", + context: ".orders[]", + asserts: [{ test: ".lines <= $cap", message: "order \\(.id) over cap" }], + }, + ], + report: ".locked", + }), + ); + const STR = 'if type == "string" then . elif . == null then "" else tojson end'; + expect(program).toBe( + ".root as $root | .node | first((.policy.cap\n\n), null) as $cap | [ " + + "((.orders[]\n\n) | ((if ([(.lines <= $cap\n\n)] | length > 0 and all(.[]; . != null and . != false)) " + + `then empty else ("[orders] " + (try first((("order \\(.id) over cap"\n\n) | ${STR}), "") catch "")) end))), ` + + "((.\n\n) | ((if ([(.locked\n\n)] | length > 0 and all(.[]; . != null and . != false)) " + + 'then ".locked" else empty end))) ]', + ); + expect(usesRoot).toBe(false); + }); + + it("puts asserts before reports and rule-level let after the context", () => { + const { program } = lowerRuleSet( + buildRuleSet({ + rules: [{ context: ".a", let: { n: ".n" }, reports: [{ test: "R" }], asserts: [{ test: "A" }] }], + }), + ); + expect(program).toContain("((.a\n\n) | first((.n\n\n), null) as $n | ((if ([(A\n\n)]"); + expect(program.indexOf("(A\n\n)")).toBeLessThan(program.indexOf("(R\n\n)")); + }); + + it("uses the prefixed test text, as a JSON string, when there is no message", () => { + const { program } = lowerRuleSet(buildRuleSet({ assert: { id: "x", test: '"\\(.a)" == "x"' } })); + expect(program).toContain(`else ${JSON.stringify('[x] "\\(.a)" == "x"')} end`); + }); + + it("detects $root in any expression, but not a longer name", () => { + expect(lowerRuleSet(buildRuleSet({ assert: { test: "true", message: "\\($root.a)" } })).usesRoot).toBe(true); + expect(lowerRuleSet(buildRuleSet({ let: { r: "$root" }, assert: "$r" })).usesRoot).toBe(true); + expect(lowerRuleSet(buildRuleSet({ let: { rootx: "1" }, assert: "$rootx" })).usesRoot).toBe(false); + }); +}); + +describe("expressions", () => { + it("declares the variables in scope for each expression", () => { + const scoped = expressions( + buildRuleSet({ + let: { a: "1", b: "$a" }, + rules: [ + { context: "C1", let: { x: "X", a: "A2" }, asserts: [{ test: "T1", message: "M1" }] }, + { context: "C2", reports: [{ test: "T2" }] }, + ], + }), + ); + expect(scoped.map((s) => [s.where, s.expression, s.variables])).toEqual([ + ["let.a", "1", ["root"]], + ["let.b", "$a", ["root", "a"]], + ["rules[0].context", "C1", ["root", "a", "b"]], + ["rules[0].let.x", "X", ["root", "a", "b"]], + ["rules[0].let.a", "A2", ["root", "a", "b", "x"]], + ["rules[0].asserts[0].test", "T1", ["root", "a", "b", "x"]], + ["rules[0].asserts[0].message", '"M1"', ["root", "a", "b", "x"]], + ["rules[1].context", "C2", ["root", "a", "b"]], + ["rules[1].reports[0].test", "T2", ["root", "a", "b"]], + ]); + }); +}); diff --git a/js/test/ruleset.test.ts b/js/test/ruleset.test.ts new file mode 100644 index 0000000..926119e --- /dev/null +++ b/js/test/ruleset.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from "vitest"; +import { buildRuleSet } from "../src/ruleset.js"; +import { JsontronSchemaError } from "../src/types.js"; + +describe("buildRuleSet", () => { + it("has no rules without rules, assert or report", () => { + expect(buildRuleSet({ type: "object" })).toEqual({ let: [], rules: [] }); + expect(buildRuleSet({ let: { x: "1" } })).toEqual({ let: [{ name: "x", expression: "1" }], rules: [] }); + }); + + it("turns sugar strings into items and merges assert and report into one rule", () => { + expect(buildRuleSet({ assert: ".a", report: [".b", { test: ".c", message: "m" }] })).toEqual({ + let: [], + rules: [ + { + context: ".", + let: [], + asserts: [{ test: ".a" }], + reports: [{ test: ".b" }, { test: ".c", message: "m" }], + }, + ], + }); + }); + + it("appends sugar to the first rule whose context is exactly '.'", () => { + const ruleSet = buildRuleSet({ + rules: [ + { context: " . ", asserts: [{ test: "1" }] }, + { id: "first", context: ".", let: { n: ".n" }, asserts: [{ test: "2" }], reports: [{ test: "3" }] }, + { context: ".", asserts: [{ test: "4" }] }, + ], + assert: "5", + report: { test: "6" }, + }); + expect(ruleSet.rules.map((r) => [r.context, r.asserts.map((a) => a.test), r.reports.map((a) => a.test)])).toEqual([ + [" . ", ["1"], []], + [".", ["2", "5"], ["3", "6"]], + [".", ["4"], []], + ]); + expect(ruleSet.rules[1]?.let).toEqual([{ name: "n", expression: ".n" }]); + }); + + it("adds a new '.' rule after the others when none exists", () => { + const ruleSet = buildRuleSet({ rules: [{ context: ".items[]", asserts: [{ test: "1" }] }], assert: "2" }); + expect(ruleSet.rules.map((r) => r.context)).toEqual([".items[]", "."]); + expect(ruleSet.rules[1]).toEqual({ context: ".", let: [], asserts: [{ test: "2" }], reports: [] }); + }); + + it("keeps let bindings in document order", () => { + expect(buildRuleSet({ let: { b: "1", a: "2", _c: "3" }, assert: "true" }).let.map((b) => b.name)).toEqual([ + "b", + "a", + "_c", + ]); + }); + + it("trims labels and reads role as flag", () => { + const ruleSet = buildRuleSet({ + rules: [{ id: " r ", context: ".", asserts: [{ test: "1", id: " i ", role: " error " }] }], + }); + expect(ruleSet.rules[0]).toMatchObject({ id: "r", asserts: [{ test: "1", id: "i", flag: "error" }] }); + }); + + it.each([ + ["assert must be a string, object or array", { assert: 5 }], + ["assert string must not be empty", { assert: "" }], + ["rules must not be empty", { rules: [] }], + ["rule requires asserts or reports", { rules: [{ context: "." }] }], + ["rule items must be objects", { rules: [{ context: ".", asserts: ["true"] }] }], + ["flag and role together", { assert: { test: "1", flag: "a", role: "b" } }], + ["blank id", { assert: { test: "1", id: " " } }], + ["blank flag", { rules: [{ context: ".", reports: [{ test: "1", flag: "\t" }] }] }], + ["let binds root", { let: { root: "1" } }], + ["let name not an identifier", { let: { "my-var": "1" } }], + ["let value not a string", { let: { x: 1 } }], + ["unknown item property", { assert: { test: "1", severity: "x" } }], + ])("rejects %s", (_, schema) => { + expect(() => buildRuleSet(schema)).toThrow(JsontronSchemaError); + }); +}); diff --git a/js/test/suite.test.ts b/js/test/suite.test.ts new file mode 100644 index 0000000..8a8cb5f --- /dev/null +++ b/js/test/suite.test.ts @@ -0,0 +1,65 @@ +// Runs every file of the language-neutral conformance suite (../../tests/*.json) as +// tests/readme.md describes: Ajv 2020-12, strict mode on, allErrors. +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import Ajv2020, { type ValidateFunction } from "ajv/dist/2020.js"; +import { describe, expect, it } from "vitest"; +import { addJsontron, JsontronSchemaError } from "../src/index.js"; + +interface SuiteTest { + description: string; + data: unknown; + valid: boolean; + errors?: string[]; +} + +interface SuiteGroup { + description: string; + schema: unknown; + buildError?: boolean; + tests?: SuiteTest[]; +} + +const suiteDir = fileURLToPath(new URL("../../tests/", import.meta.url)); +const files = readdirSync(suiteDir).filter((f) => f.endsWith(".json") && f !== "schema.json"); +const JSONTRON_KEYWORDS = new Set(["rules", "assert", "report"]); + +// Ajv's default strict mode (unknown keywords are errors), with every error collected. +const newAjv = () => addJsontron(new Ajv2020({ allErrors: true, logger: false })); + +it("finds the suite files", () => { + expect(files.length).toBeGreaterThan(0); +}); + +for (const file of files) { + const groups = JSON.parse(readFileSync(join(suiteDir, file), "utf8")) as SuiteGroup[]; + describe(file, () => { + for (const group of groups) { + describe(group.description, () => { + if (group.buildError) { + it("fails to compile", () => { + expect(() => newAjv().compile(group.schema as object)).toThrow(JsontronSchemaError); + }); + return; + } + + let compiled: ValidateFunction | undefined; + const getValidate = () => (compiled ??= newAjv().compile(group.schema as object)); + for (const test of group.tests ?? []) { + it(test.description, () => { + const validate = getValidate(); + const valid = validate(test.data); + const messages = (validate.errors ?? []) + .filter((e) => JSONTRON_KEYWORDS.has(e.keyword)) + .map((e) => e.message ?? ""); + expect({ valid, messages: valid ? [] : messages.sort() }).toEqual({ + valid: test.valid, + messages: test.errors ? [...test.errors].sort() : valid ? [] : messages.sort(), + }); + }); + } + }); + } + }); +} diff --git a/js/tsconfig.json b/js/tsconfig.json new file mode 100644 index 0000000..9666a1f --- /dev/null +++ b/js/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM"], + "types": ["node"], + "strict": true, + "noUncheckedIndexedAccess": true, + "esModuleInterop": true, + "resolveJsonModule": true, + "isolatedModules": true, + "skipLibCheck": true, + "noEmit": true + }, + "include": ["src", "test", "tsup.config.ts", "vitest.config.ts"] +} diff --git a/js/tsup.config.ts b/js/tsup.config.ts new file mode 100644 index 0000000..3ee8743 --- /dev/null +++ b/js/tsup.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from "tsup"; + +// The meta-schema `../schemas/jsontron-0.2.json` is imported by `src/schema.ts` +// and bundled into both outputs: it is copied into the package at build time, +// never duplicated in the source tree. +export default defineConfig({ + entry: ["src/index.ts"], + format: ["esm"], + dts: true, + clean: true, + sourcemap: true, + target: "node20", + external: ["ajv", "@devlooped/jqlite"], +}); diff --git a/js/vitest.config.ts b/js/vitest.config.ts new file mode 100644 index 0000000..0e37b73 --- /dev/null +++ b/js/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["test/**/*.test.ts"], + testTimeout: 30000, + }, +}); diff --git a/python/.gitignore b/python/.gitignore new file mode 100644 index 0000000..5108750 --- /dev/null +++ b/python/.gitignore @@ -0,0 +1,12 @@ +.venv*/ +venv/ +__pycache__/ +*.py[cod] +.pytest_cache/ +.ruff_cache/ +.mypy_cache/ +build/ +dist/ +*.egg-info/ +# copied from ../schemas at build time +src/jsontron/jsontron-*.json diff --git a/python/hatch_build.py b/python/hatch_build.py new file mode 100644 index 0000000..781112b --- /dev/null +++ b/python/hatch_build.py @@ -0,0 +1,37 @@ +"""Packages files the repository keeps once, outside `python/`: the meta-schema and the license. + +From a checkout they come from `../schemas` and `../license.txt`; the sdist holds copies, which +a wheel built from it uses. +""" + +from pathlib import Path +from typing import Any + +from hatchling.builders.hooks.plugin.interface import BuildHookInterface + +META_SCHEMA = "jsontron-0.2.json" +LICENSE = "license.txt" + + +class SharedFilesHook(BuildHookInterface): # type: ignore[type-arg] + def initialize(self, version: str, build_data: dict[str, Any]) -> None: + project = Path(self.root) + meta_schema = self._find( + project.parent / "schemas" / META_SCHEMA, project / "src" / "jsontron" / META_SCHEMA + ) + license_file = self._find(project.parent / LICENSE, project / LICENSE) + include = build_data["force_include"] + if self.target_name == "wheel": + include[str(meta_schema)] = f"jsontron/{META_SCHEMA}" + if license_file.parent != project: # a copy in the project is found as a license file + build_data.setdefault("extra_metadata", {})[str(license_file)] = LICENSE + else: + include[str(meta_schema)] = f"src/jsontron/{META_SCHEMA}" + include[str(license_file)] = LICENSE + + @staticmethod + def _find(repository: Path, copy: Path) -> Path: + for path in (repository, copy): + if path.is_file(): + return path + raise FileNotFoundError(f"Not found: {repository}") diff --git a/python/pyproject.toml b/python/pyproject.toml new file mode 100644 index 0000000..c3f6b78 --- /dev/null +++ b/python/pyproject.toml @@ -0,0 +1,53 @@ +[build-system] +requires = ["hatchling>=1.24"] +build-backend = "hatchling.build" + +[project] +name = "jsontron" +version = "0.0.0" +description = "Schematron-style business rules for JSON Schema (jsonschema), with jq expressions." +readme = "readme.md" +license = "MIT" +requires-python = ">=3.11" +authors = [{ name = "Daniel Cazzulino and Contributors" }] +keywords = ["json-schema", "jsonschema", "jq", "jqlite", "schematron", "validation", "rules"] +classifiers = [ + "Programming Language :: Python :: 3", + "Topic :: Software Development :: Libraries", + "Typing :: Typed", +] +dependencies = [ + # descend and the if/not/contains/unevaluated* applicators derive validators through + # evolve(), which Jsontron hooks to find the root document; tested down to 4.18.0. + "jsonschema>=4.18", + # field aliases, used to keep the extended class for subschemas that declare `$schema` + "attrs>=22.2", + # Pure-Python portable jq engine shared across all Jsontron implementations + "devlooped-jqlite>=1.0.0", +] + +[project.optional-dependencies] +test = ["pytest>=8", "ruff>=0.6"] + +[project.urls] +Homepage = "https://github.com/devlooped/jsontron" +Specification = "https://github.com/devlooped/jsontron/blob/main/spec/jsontron.md" + +[tool.hatch.build.targets.wheel] +packages = ["src/jsontron"] + +[tool.hatch.build.targets.sdist] +include = ["src/jsontron", "tests", "readme.md", "hatch_build.py"] + +[tool.hatch.build.hooks.custom] +path = "hatch_build.py" + +[tool.pytest.ini_options] +testpaths = ["tests"] + +[tool.ruff] +line-length = 100 +target-version = "py311" + +[tool.ruff.lint] +select = ["E", "F", "W", "I", "UP", "B", "SIM", "RUF"] diff --git a/python/readme.md b/python/readme.md new file mode 100644 index 0000000..00214a9 --- /dev/null +++ b/python/readme.md @@ -0,0 +1,89 @@ +# Jsontron for Python + +Schematron-style business rules for JSON Schema, with [jq](https://jqlang.org) expressions: +the `rules`, `assert`, `report` and `let` keywords of the +[Jsontron specification](https://github.com/devlooped/jsontron/blob/main/spec/jsontron.md) +(version 0.2) for [jsonschema](https://pypi.org/project/jsonschema/) (draft 2020-12), +evaluated in-process by [devlooped-jqlite](https://pypi.org/project/devlooped-jqlite/) +(pure Python, no native extensions). + +- Structural validation stays with JSON Schema. +- Cross-cutting rules stay in the schema, next to the data they describe. +- jq expressions are checked when the schema is checked, and compiled once. + +## Quick start + +```python +from jsontron import JsontronValidator + +schema = { + "type": "object", + "required": ["orders", "policy", "approvedCustomers"], + "rules": [ + { + "context": ".orders[] | select(.total > 1000)", + "asserts": [ + { + "test": ".discount >= ($root.policy.minHighValueDiscount // 0.1)", + "message": "High-value order \\(.id) discount \\(.discount) is below policy", + }, + { + "test": ".customer.id | IN($root.approvedCustomers[])", + "message": "Customer \\(.customer.id) is not on the approved list", + }, + ], + } + ], +} + +document = { + "policy": {"minHighValueDiscount": 0.15}, + "approvedCustomers": ["acme", "globex"], + "orders": [ + {"id": "O-1001", "total": 2500, "discount": 0.05, "customer": {"id": "initech"}}, + {"id": "O-1002", "total": 80, "discount": 0, "customer": {"id": "unknown"}}, + ], +} + +JsontronValidator.check_schema(schema) # shape and every jq expression +validator = JsontronValidator(schema) + +# O-1001 fails both asserts (discount + customer). +# O-1002 is ignored by the rule (total <= 1000). +for error in validator.iter_errors(document): + print(error.message) +# High-value order O-1001 discount 0.05 is below policy +# Customer initech is not on the approved list + +print(validator.is_valid(document)) # False +``` + +`JsontronValidator` is `jsonschema.Draft202012Validator` with the four keywords, and is used +like any jsonschema validator class: `iter_errors`, `validate`, `is_valid`, `check_schema`, and +`jsonschema.validate(document, schema, cls=JsontronValidator)`. + +`jsontron.extend(validator_class)` adds the keywords to another validator class. To combine +them with keywords of your own, extend last: +`jsontron.extend(validators.extend(Draft202012Validator, {...}))`. A class made with +`validators.extend(JsontronValidator, ...)` loses what tracks the document for `$root`. + +## Behaviour + +- Each failed assert or report is one `ValidationError` whose message is the failure text + (with its `[rule-id][item-id][flag=...]` prefix), at the location of the instance the schema + object applies to. Its `validator` is the keyword that owns the rule set: `rules`, else + `assert`, else `report`. +- A jq runtime error in a `let`, `context` or `test` is one `ValidationError` for the rule set. +- `check_schema` rejects invalid keyword values and invalid jq in any expression. A schema used + without `check_schema` raises the same `SchemaError` when its invalid schema object is first + applied. +- `$root` is the whole document, also under `properties`, `items`, `$ref` and applicators. +- A schema object is compiled once, on first use: changing it in place afterwards has no effect. + +## Performance + +Each schema object with a rule set compiles to one `jqlite` expression on first use (cached), +and runs it once per instance it applies to. Every run converts its input to `jqlite` values: +the instance, and the whole document when an expression reads `$root`. For large arrays, prefer +a rule at the parent with a `context` that selects the items over a rule set under `items` that +reads `$root`, so the document is converted once rather than per item. diff --git a/python/src/jsontron/__init__.py b/python/src/jsontron/__init__.py new file mode 100644 index 0000000..5e5f7b9 --- /dev/null +++ b/python/src/jsontron/__init__.py @@ -0,0 +1,13 @@ +"""Jsontron: Schematron-style business rules in JSON Schema, with jq expressions. + +`JsontronValidator` is `jsonschema.Draft202012Validator` with the Jsontron keywords `rules`, +`assert`, `report` and `let`; `extend` adds them to another validator class. +""" + +from ._compiler import meta_schema +from ._validator import JsontronValidator, check_jsontron, extend + +SPEC_VERSION = "0.2" +"""The version of the Jsontron specification this package implements.""" + +__all__ = ["SPEC_VERSION", "JsontronValidator", "check_jsontron", "extend", "meta_schema"] diff --git a/python/src/jsontron/_compiler.py b/python/src/jsontron/_compiler.py new file mode 100644 index 0000000..46f49b3 --- /dev/null +++ b/python/src/jsontron/_compiler.py @@ -0,0 +1,129 @@ +"""Build time (spec section 6): shape checks, jq checks in isolation, lowering and caches.""" + +from __future__ import annotations + +import json +import threading +from collections import OrderedDict +from collections.abc import Mapping +from dataclasses import dataclass +from functools import lru_cache +from importlib import resources +from pathlib import Path +from typing import Any + +import jqlite +from jqlite import Expression, JqParseError +from jsonschema import Draft202012Validator +from jsonschema.exceptions import SchemaError, best_match + +from ._lowering import KEYWORDS, RuleSet, ShapeError, expressions, lower, normalize, references_root + +META_SCHEMA_FILE = "jsontron-0.2.json" + + +def _read_meta_schema() -> Any: + packaged = resources.files("jsontron") / META_SCHEMA_FILE + if packaged.is_file(): + return json.loads(packaged.read_text(encoding="utf-8")) + # Running from a source checkout (editable install, tests): the repository's single copy. + repository = Path(__file__).resolve().parents[3] / "schemas" / META_SCHEMA_FILE + return json.loads(repository.read_text(encoding="utf-8")) + + +@lru_cache(maxsize=1) +def meta_schema() -> Any: + """The Jsontron 0.2 meta-schema (`schemas/jsontron-0.2.json`).""" + return _read_meta_schema() + + +@lru_cache(maxsize=1) +def _shape_validator() -> Draft202012Validator: + return Draft202012Validator(meta_schema()) + + +@dataclass(frozen=True) +class Compiled: + """What a schema object compiles to. `program` is None when it has no rule set.""" + + rule_set: RuleSet | None + program: Expression | None + reads_root: bool + + +@lru_cache(maxsize=4096) +def _check(expression: str) -> None: + jqlite.parse(expression) + + +@lru_cache(maxsize=1024) +def _program(text: str) -> Expression: + return jqlite.parse(text) + + +def compile_schema(schema: Mapping[str, Any]) -> Compiled: + """Checks and compiles the Jsontron keywords of one schema object. + + Raises `jsonschema.exceptions.SchemaError` when they are invalid. + """ + keywords = {k: schema[k] for k in KEYWORDS if k in schema} + error = best_match(_shape_validator().iter_errors(keywords)) + if error is not None: + location = "/".join(str(p) for p in error.absolute_path) + raise SchemaError(f"Invalid Jsontron keyword at '{location}': {error.message}") + try: + rule_set = normalize(schema) + except ShapeError as e: + raise SchemaError(f"Invalid Jsontron keyword: {e}") from None + for where, expression, _variables in expressions(schema, rule_set): + try: + _check(expression) + except JqParseError as e: + raise SchemaError(f"Invalid jq in {where}: {expression!r}: {e}") from None + if rule_set is None: + return Compiled(rule_set=None, program=None, reads_root=False) + text = lower(rule_set) + try: + program = _program(text) + except JqParseError as e: # each part compiled on its own, so the whole should too + raise SchemaError(f"Invalid lowered jq program: {e}") from None + return Compiled(rule_set=rule_set, program=program, reads_root=references_root(rule_set)) + + +class SchemaCache: + """Compiled schema objects, by identity. + + Each entry keeps its schema object alive, so its `id()` cannot be reused by another object + while the entry exists; the size bound keeps that from growing without limit. A schema + object changed in place after its first use keeps its first compilation. + """ + + def __init__(self, maxsize: int = 4096) -> None: + self._maxsize = maxsize + self._entries: OrderedDict[int, tuple[Mapping[str, Any], Compiled]] = OrderedDict() + self._lock = threading.Lock() + + def get(self, schema: Mapping[str, Any]) -> Compiled: + key = id(schema) + with self._lock: + entry = self._entries.get(key) + if entry is not None and entry[0] is schema: + self._entries.move_to_end(key) + return entry[1] + compiled = compile_schema(schema) + with self._lock: + self._entries[key] = (schema, compiled) + self._entries.move_to_end(key) + while len(self._entries) > self._maxsize: + self._entries.popitem(last=False) + return compiled + + def __len__(self) -> int: + return len(self._entries) + + def clear(self) -> None: + with self._lock: + self._entries.clear() + + +cache = SchemaCache() diff --git a/python/src/jsontron/_lowering.py b/python/src/jsontron/_lowering.py new file mode 100644 index 0000000..a840964 --- /dev/null +++ b/python/src/jsontron/_lowering.py @@ -0,0 +1,268 @@ +"""Normalization, message preparation and the reference lowering (spec sections 2, 4 and 7). + +Everything here is pure: it takes keyword values that already match the meta-schema and +returns data or jq program text. The jq engine is not used here. +""" + +from __future__ import annotations + +import json +import re +from collections.abc import Iterator, Mapping +from dataclasses import dataclass, field +from typing import Any + +KEYWORDS = ("rules", "assert", "report", "let") + +_ROOT_REFERENCE = re.compile(r"\$root\b") + +STR = 'if type == "string" then . elif . == null then "" else tojson end' +"""Turns the first value of a message expression into its text (spec section 4).""" + + +@dataclass(frozen=True) +class Item: + """An assert or report item, with labels already trimmed.""" + + test: str + message: str | None = None + id: str | None = None + flag: str | None = None + + +@dataclass(frozen=True) +class Rule: + context: str + id: str | None = None + lets: tuple[tuple[str, str], ...] = () + asserts: tuple[Item, ...] = () + reports: tuple[Item, ...] = () + + +@dataclass(frozen=True) +class RuleSet: + """The rule set of one schema object (spec section 2).""" + + rules: tuple[Rule, ...] + lets: tuple[tuple[str, str], ...] = field(default=()) + + +class ShapeError(ValueError): + """A keyword value that the meta-schema accepts but section 1 does not.""" + + +def _label(value: Any, name: str) -> str | None: + if value is None: + return None + trimmed = value.strip() + if not trimmed: + raise ShapeError(f"'{name}' must not be empty or whitespace") + return trimmed + + +def _item(value: Any) -> Item: + if isinstance(value, str): + return Item(test=value) + if "flag" in value and "role" in value: + raise ShapeError("'flag' and 'role' are mutually exclusive") + return Item( + test=value["test"], + message=value.get("message"), + id=_label(value.get("id"), "id"), + flag=_label(value.get("flag", value.get("role")), "flag" if "flag" in value else "role"), + ) + + +def _items(value: Any) -> tuple[Item, ...]: + if value is None: + return () + return tuple(_item(v) for v in (value if isinstance(value, list) else [value])) + + +def _lets(value: Mapping[str, str] | None) -> tuple[tuple[str, str], ...]: + return tuple(value.items()) if value else () + + +def normalize(schema: Mapping[str, Any]) -> RuleSet | None: + """Builds the rule set of a schema object, or None when it has none. + + The keyword values must already match the meta-schema; section 1 constraints the + meta-schema cannot express (flag with role, blank labels) raise ShapeError. + """ + rules = [ + Rule( + context=r["context"], + id=_label(r.get("id"), "id"), + lets=_lets(r.get("let")), + asserts=_items(r.get("asserts")), + reports=_items(r.get("reports")), + ) + for r in schema.get("rules", ()) + ] + asserts = _items(schema.get("assert")) + reports = _items(schema.get("report")) + if not rules and not asserts and not reports: + return None # `let` alone: checked at build time, never evaluated + if asserts or reports: + for i, rule in enumerate(rules): + if rule.context == ".": + rules[i] = Rule( + context=rule.context, + id=rule.id, + lets=rule.lets, + asserts=rule.asserts + asserts, + reports=rule.reports + reports, + ) + break + else: + rules.append(Rule(context=".", asserts=asserts, reports=reports)) + return RuleSet(rules=tuple(rules), lets=_lets(schema.get("let"))) + + +def message_expression(message: str) -> str: + """The jq expression of a `message` (spec section 4).""" + if message.lstrip().startswith('"'): + return message + out = ['"'] + i = 0 + while i < len(message): + c = message[i] + if c == "\\" and i + 1 < len(message): + # A backslash keeps the character after it; `\(...)` is copied unchanged. + end = _interpolation_end(message, i + 2) if message[i + 1] == "(" else i + 2 + out.append(message[i:end]) + i = end + else: + out.append(_ESCAPES.get(c, c)) + i += 1 + out.append('"') + return "".join(out) + + +_ESCAPES = {'"': '\\"', "\n": "\\n", "\r": "\\r", "\t": "\\t"} + + +def _interpolation_end(s: str, i: int) -> int: + """The index after the `)` that closes an interpolation whose content starts at `i`.""" + depth = 1 + while i < len(s) and depth > 0: + c = s[i] + if c == '"': + i = _string_end(s, i + 1) + continue + if c == "(": + depth += 1 + elif c == ")": + depth -= 1 + i += 1 + return i + + +def _string_end(s: str, i: int) -> int: + """The index after the `"` that closes a jq string literal whose content starts at `i`.""" + while i < len(s): + c = s[i] + if c == "\\" and i + 1 < len(s): + i = _interpolation_end(s, i + 2) if s[i + 1] == "(" else i + 2 + continue + i += 1 + if c == '"': + break + return i + + +def prefix(rule: Rule, item: Item) -> str: + """The label prefix of a failure text, with its trailing space, or the empty string.""" + labels = "".join( + [ + f"[{rule.id}]" if rule.id else "", + f"[{item.id}]" if item.id else "", + f"[flag={item.flag}]" if item.flag else "", + ] + ) + return labels + " " if labels else "" + + +def _literal(text: str) -> str: + # A JSON string literal is a jq string literal: JSON escapes every backslash, so no `\(`. + return json.dumps(text, ensure_ascii=False) + + +def _expr(text: str) -> str: + # โŸจxโŸฉ: the text followed by two newlines, so a trailing comment cannot swallow what + # follows, even one that a final backslash continues onto the next line. + return f"({text}\n\n)" + + +def _bindings(lets: tuple[tuple[str, str], ...]) -> str: + return "".join(f"first({_expr(expr)}, null) as ${name} | " for name, expr in lets) + + +def _text(rule: Rule, item: Item) -> str: + if item.message is None: + return _literal(prefix(rule, item) + item.test) + message = _expr(message_expression(item.message)) + return f'({_literal(prefix(rule, item))} + (try first(({message} | {STR}), "") catch ""))' + + +def _truthy(item: Item) -> str: + return f"([{_expr(item.test)}] | length > 0 and all(.[]; . != null and . != false))" + + +def lower(rule_set: RuleSet) -> str: + """The jq program of a rule set (spec section 7). + + Input `{"root": , "node": }`, output the array of failure texts. + """ + rules = [] + for rule in rule_set.rules: + items = [f"(if {_truthy(a)} then empty else {_text(rule, a)} end)" for a in rule.asserts] + items += [f"(if {_truthy(r)} then {_text(rule, r)} else empty end)" for r in rule.reports] + rules.append(f"({_expr(rule.context)} | {_bindings(rule.lets)}({', '.join(items)}))") + return f".root as $root | .node | {_bindings(rule_set.lets)}[ {', '.join(rules)} ]" + + +def expressions( + schema: Mapping[str, Any], rule_set: RuleSet | None +) -> Iterator[tuple[str, str, frozenset[str]]]: + """Every jq expression of a schema object with the variables in scope (spec section 6). + + Yields `(where, expression, variables)`; `variables` always includes `root`. + """ + scope = {"root"} + schema_lets = _lets(schema.get("let")) + for name, expr in schema_lets: + yield f"let.{name}", expr, frozenset(scope) + scope.add(name) + if rule_set is None: + return + for index, rule in enumerate(rule_set.rules): + where = f"rules[{index}]" if index < len(schema.get("rules", ())) else "assert/report" + yield f"{where}.context", rule.context, frozenset(scope) + rule_scope = set(scope) + for name, expr in rule.lets: + yield f"{where}.let.{name}", expr, frozenset(rule_scope) + rule_scope.add(name) + variables = frozenset(rule_scope) + for kind, items in (("asserts", rule.asserts), ("reports", rule.reports)): + for i, item in enumerate(items): + yield f"{where}.{kind}[{i}].test", item.test, variables + if item.message is not None: + yield ( + f"{where}.{kind}[{i}].message", + message_expression(item.message), + variables, + ) + + +def references_root(rule_set: RuleSet) -> bool: + """Whether any expression of the rule set may read `$root` (a textual, conservative check).""" + texts: list[str] = [expr for _, expr in rule_set.lets] + for rule in rule_set.rules: + texts.append(rule.context) + texts += [expr for _, expr in rule.lets] + for item in rule.asserts + rule.reports: + texts.append(item.test) + if item.message is not None: + texts.append(item.message) + return any(_ROOT_REFERENCE.search(text) for text in texts) diff --git a/python/src/jsontron/_validator.py b/python/src/jsontron/_validator.py new file mode 100644 index 0000000..62746b3 --- /dev/null +++ b/python/src/jsontron/_validator.py @@ -0,0 +1,208 @@ +"""The Jsontron keywords for `jsonschema` validator classes.""" + +from __future__ import annotations + +import copy +import weakref +from collections.abc import Iterator, Mapping +from typing import Any, TypeVar, cast + +import attrs +from jqlite import JqError +from jsonschema import Draft202012Validator, validators +from jsonschema.exceptions import SchemaError, ValidationError +from jsonschema.protocols import Validator + +from ._compiler import cache +from ._lowering import KEYWORDS + +V = TypeVar("V", bound=type[Validator]) + +# The root document of a validation. +# +# jsonschema gives keyword callbacks the validator and the instance at hand, not the document. +# The outermost `iter_errors` call works on a copy of the validator that it registers here with +# the document; `evolve`, which jsonschema calls for every subschema it applies (`descend`, +# `if`, `not`, `contains`, ...), registers each derived validator with the same document. A +# callback then finds the document from the validator it receives. +# +# Tying the document to the validator lineage, rather than to a ContextVar set around the +# outermost call, keeps it right when validations interleave: `iter_errors` is a generator, so a +# ContextVar set in its body would stay set in the caller's context between two errors and leak +# into another validation started meanwhile. +# +# Entries are keyed by id() and dropped by a weakref callback when the validator is collected, +# before its id can be reused. No lock: single dict operations are atomic, and a lock taken here +# could deadlock when garbage collection runs the callback on a thread that holds it. +_roots: dict[int, tuple[weakref.ref[Any], list[Any]]] = {} + + +def _register(validator: Any, root: list[Any]) -> None: + key = id(validator) + + def drop(ref: weakref.ref[Any]) -> None: + entry = _roots.get(key) + if entry is not None and entry[0] is ref: + _roots.pop(key, None) + + _roots[key] = (weakref.ref(validator, drop), root) + + +def _root_of(validator: Any) -> list[Any] | None: + entry = _roots.get(id(validator)) + if entry is not None and entry[0]() is validator: + return entry[1] + return None + + +def _owner(schema: Mapping[str, Any]) -> str: + # `rules` owns the evaluation of the rule set; without it `assert`, else `report`. + return "rules" if "rules" in schema else "assert" if "assert" in schema else "report" + + +def _evaluating(keyword: str) -> Any: + def evaluate( + validator: Any, value: Any, instance: Any, schema: Mapping[str, Any] + ) -> Iterator[ValidationError]: + compiled = cache.get(schema) + if compiled.program is None or _owner(schema) != keyword: + return + root = None + if compiled.reads_root: + box = _root_of(validator) + root = box[0] if box is not None else instance + try: + results = compiled.program.evaluate({"root": root, "node": instance}) + except JqError as e: + yield ValidationError(f"Jsontron evaluation error: {e}") + return + texts = results[0] if results else [] + for text in texts: + yield ValidationError(text) + + evaluate.__name__ = f"jsontron_{keyword}" + return evaluate + + +def _let(validator: Any, value: Any, instance: Any, schema: Mapping[str, Any]) -> None: + # Never evaluates on its own; compiling reports an invalid `let` on first use. + cache.get(schema) + + +_APPLICATORS_ONE = ( + "additionalProperties", + "items", + "additionalItems", + "contains", + "propertyNames", + "if", + "then", + "else", + "not", + "unevaluatedItems", + "unevaluatedProperties", + "contentSchema", +) +_APPLICATORS_MANY = ("allOf", "anyOf", "oneOf", "prefixItems", "items") +_APPLICATORS_MAP = ( + "properties", + "patternProperties", + "$defs", + "definitions", + "dependentSchemas", + "dependencies", +) + + +def _subschemas(schema: Mapping[str, Any]) -> Iterator[tuple[tuple[str | int, ...], Any]]: + for keyword in _APPLICATORS_ONE: + if keyword in schema: + yield (keyword,), schema[keyword] + for keyword in _APPLICATORS_MANY: + value = schema.get(keyword) + if isinstance(value, list): + for index, item in enumerate(value): + yield (keyword, index), item + for keyword in _APPLICATORS_MAP: + value = schema.get(keyword) + if isinstance(value, Mapping): + for name, item in value.items(): + yield (keyword, name), item + + +def check_jsontron(schema: Any) -> None: + """Checks the Jsontron keywords of every schema object in `schema` (spec section 6). + + Raises `jsonschema.exceptions.SchemaError` for the first invalid one; on success the compiled + rule sets are cached for validation. + """ + seen: set[int] = set() + pending: list[tuple[tuple[str | int, ...], Any]] = [((), schema)] + while pending: + path, node = pending.pop() + if not isinstance(node, Mapping) or id(node) in seen: + continue + seen.add(id(node)) + if any(k in node for k in KEYWORDS): + try: + cache.get(node) + except SchemaError as e: + pointer = "/" + "/".join(str(p) for p in path) + raise SchemaError(f"{e.message} (schema location '{pointer}')", path=path) from None + pending.extend((path + sub, child) for sub, child in _subschemas(node)) + + +def _same_dialect(one: Any, other: Any) -> bool: + return bool(one.ID_OF(one.META_SCHEMA) == other.ID_OF(other.META_SCHEMA)) + + +def extend(validator_class: V) -> V: + """Returns a new validator class: `validator_class` with the Jsontron keywords.""" + extended: Any = validators.extend( + validator_class, + { + "rules": _evaluating("rules"), + "assert": _evaluating("assert"), + "report": _evaluating("report"), + "let": _let, + }, + ) + base_iter_errors = extended.iter_errors + base_evolve = extended.evolve + base_check_schema = extended.check_schema.__func__ + + def iter_errors(self: Any, instance: Any, *args: Any, **kwargs: Any) -> Iterator[Any]: + if _root_of(self) is not None: + yield from base_iter_errors(self, instance, *args, **kwargs) + return + top = copy.copy(self) + _register(top, [instance]) + yield from base_iter_errors(top, instance, *args, **kwargs) + + def evolve(self: Any, **changes: Any) -> Any: + child = base_evolve(self, **changes) + child_class = type(child) + if child_class is not extended and _same_dialect(child_class, extended): + # A subschema that declares its `$schema` gets jsonschema's own class for that + # dialect, without the Jsontron keywords: keep this class for the same dialect. + child = extended( + **{f.alias: getattr(child, f.name) for f in attrs.fields(child_class) if f.init} + ) + root = _root_of(self) + if root is not None and child is not self: + _register(child, root) + return child + + def check_schema(cls: Any, schema: Any, *args: Any, **kwargs: Any) -> None: + base_check_schema(cls, schema, *args, **kwargs) + check_jsontron(schema) + + extended.iter_errors = iter_errors + extended.evolve = evolve + extended.check_schema = classmethod(check_schema) + return cast(V, extended) + + +JsontronValidator = extend(Draft202012Validator) +"""`Draft202012Validator` with the Jsontron keywords.""" +JsontronValidator.__name__ = JsontronValidator.__qualname__ = "JsontronValidator" diff --git a/python/src/jsontron/py.typed b/python/src/jsontron/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/python/tests/test_lowering.py b/python/tests/test_lowering.py new file mode 100644 index 0000000..d1043bb --- /dev/null +++ b/python/tests/test_lowering.py @@ -0,0 +1,210 @@ +"""Normalization, merge, message preparation and the lowering, without a validator.""" + +from __future__ import annotations + +import jqlite +import pytest + +from jsontron._lowering import ( + Item, + Rule, + RuleSet, + ShapeError, + expressions, + lower, + message_expression, + normalize, + prefix, + references_root, +) + + +def run(schema: dict, node: object, root: object = None) -> list[str]: + rule_set = normalize(schema) + assert rule_set is not None + return jqlite.parse(lower(rule_set)).evaluate({"root": root, "node": node})[0] + + +class TestNormalize: + def test_no_rule_set_without_rules_assert_report(self) -> None: + assert normalize({"let": {"x": "1"}}) is None + assert normalize({"type": "object"}) is None + + def test_sugar_forms(self) -> None: + rule_set = normalize({"assert": ".a", "report": [".b", {"test": ".c", "message": "m"}]}) + assert rule_set == RuleSet( + rules=( + Rule( + context=".", + asserts=(Item(test=".a"),), + reports=(Item(test=".b"), Item(test=".c", message="m")), + ), + ) + ) + + def test_sugar_appends_to_first_dot_rule(self) -> None: + rule_set = normalize( + { + "rules": [ + {"context": ".x", "asserts": [{"test": "1"}]}, + {"id": "r", "context": ".", "let": {"v": "2"}, "reports": [{"test": "3"}]}, + {"context": ".", "asserts": [{"test": "4"}]}, + ], + "assert": "5", + "report": "6", + } + ) + assert rule_set is not None + assert [r.context for r in rule_set.rules] == [".x", ".", "."] + merged = rule_set.rules[1] + assert merged.id == "r" + assert merged.lets == (("v", "2"),) + assert merged.asserts == (Item(test="5"),) + assert merged.reports == (Item(test="3"), Item(test="6")) + assert rule_set.rules[2].asserts == (Item(test="4"),) + + def test_context_must_be_exactly_dot(self) -> None: + rule_set = normalize( + {"rules": [{"context": " .", "asserts": [{"test": "1"}]}], "assert": "2"} + ) + assert rule_set is not None + assert [r.context for r in rule_set.rules] == [" .", "."] + assert rule_set.rules[1] == Rule(context=".", asserts=(Item(test="2"),)) + + def test_schema_let_is_kept_in_order(self) -> None: + rule_set = normalize({"let": {"b": "1", "a": "2"}, "assert": "true"}) + assert rule_set is not None + assert rule_set.lets == (("b", "1"), ("a", "2")) + + def test_labels_are_trimmed_and_role_is_flag(self) -> None: + rule_set = normalize({"assert": {"test": "1", "id": " a ", "role": "\twarn "}}) + assert rule_set is not None + assert rule_set.rules[0].asserts == (Item(test="1", id="a", flag="warn"),) + + @pytest.mark.parametrize( + "item", + [ + {"test": "1", "flag": "a", "role": "b"}, + {"test": "1", "id": " "}, + {"test": "1", "flag": " "}, + ], + ) + def test_invalid_items(self, item: dict) -> None: + with pytest.raises(ShapeError): + normalize({"assert": item}) + + def test_blank_rule_id(self) -> None: + with pytest.raises(ShapeError): + normalize({"rules": [{"context": ".", "id": " ", "asserts": [{"test": "1"}]}]}) + + +class TestMessages: + @pytest.mark.parametrize( + ("message", "expression"), + [ + ("plain", '"plain"'), + ('say "hi"', '"say \\"hi\\""'), + ("a\nb\rc\td", '"a\\nb\\rc\\td"'), + ("\\(.x) kept", '"\\(.x) kept"'), + ('"already" + "jq"', '"already" + "jq"'), + (' "leading space"', ' "leading space"'), + ], + ) + def test_message_expression(self, message: str, expression: str) -> None: + assert message_expression(message) == expression + + def test_prefix(self) -> None: + assert prefix(Rule(context="."), Item(test="t")) == "" + assert ( + prefix(Rule(context=".", id="r"), Item(test="t", id="i", flag="f")) == "[r][i][flag=f] " + ) + assert prefix(Rule(context="."), Item(test="t", flag="f")) == "[flag=f] " + + +class TestLower: + def test_spec_example(self) -> None: + schema = { + "let": {"cap": ".policy.cap"}, + "rules": [ + { + "id": "orders", + "context": ".orders[]", + "asserts": [{"test": ".lines <= $cap", "message": "order \\(.id) over cap"}], + } + ], + "report": ".locked", + } + node = {"policy": {"cap": 2}, "orders": [{"id": 1, "lines": 1}, {"id": 2, "lines": 3}]} + assert run(schema, node) == ["[orders] order 2 over cap"] + assert run(schema, {**node, "locked": True}) == ["[orders] order 2 over cap", ".locked"] + + def test_message_text_without_message_is_literal(self) -> None: + assert run({"assert": '"\\(.a)" == "x"'}, {"a": "y"}) == ['"\\(.a)" == "x"'] + + def test_trailing_comment_does_not_swallow(self) -> None: + schema = { + "let": {"x": "1 # one"}, + "assert": {"test": "$x == 2 # never", "message": "m # c"}, + } + assert run(schema, {}) == ["m # c"] + + def test_truthiness(self) -> None: + schema = {"report": ["empty", "null", "false", "true, false", "1, 2", "0", '""']} + assert run(schema, {}) == ["1, 2", "0", '""'] + + def test_root_is_bound(self) -> None: + assert run({"assert": ". == $root.n"}, 1, {"n": 2}) == [". == $root.n"] + + def test_runtime_error_escapes(self) -> None: + with pytest.raises(jqlite.JqError): + run({"assert": ".a.b"}, {"a": "text"}) + + def test_message_error_is_empty(self) -> None: + assert run({"assert": {"test": "false", "message": '"x" | error'}}, {}) == [""] + + +class TestExpressions: + def test_scopes(self) -> None: + schema = { + "let": {"a": "1", "b": "$a"}, + "rules": [ + { + "context": ".", + "let": {"c": "$b"}, + "asserts": [{"test": "$c", "message": "\\($c)"}], + } + ], + } + found = { + where: (expr, sorted(scope)) + for where, expr, scope in expressions(schema, normalize(schema)) + } + assert found == { + "let.a": ("1", ["root"]), + "let.b": ("$a", ["a", "root"]), + "rules[0].context": (".", ["a", "b", "root"]), + "rules[0].let.c": ("$b", ["a", "b", "root"]), + "rules[0].asserts[0].test": ("$c", ["a", "b", "c", "root"]), + "rules[0].asserts[0].message": ('"\\($c)"', ["a", "b", "c", "root"]), + } + + def test_let_alone(self) -> None: + assert list(expressions({"let": {"x": ".a"}}, None)) == [ + ("let.x", ".a", frozenset({"root"})) + ] + + @pytest.mark.parametrize( + ("schema", "reads"), + [ + ({"assert": ". > 1"}, False), + ({"assert": "$rootx"}, False), + ({"assert": ". > $root.n"}, True), + ({"let": {"r": "$root"}, "assert": "$r"}, True), + ({"assert": {"test": "true", "message": "\\($root)"}}, True), + ({"rules": [{"context": "$root", "asserts": [{"test": "1"}]}]}, True), + ], + ) + def test_references_root(self, schema: dict, reads: bool) -> None: + rule_set = normalize(schema) + assert rule_set is not None + assert references_root(rule_set) is reads diff --git a/python/tests/test_suite.py b/python/tests/test_suite.py new file mode 100644 index 0000000..c70f404 --- /dev/null +++ b/python/tests/test_suite.py @@ -0,0 +1,71 @@ +"""Runs the language-neutral conformance suite (`../tests/*.json`) as `tests/readme.md` says.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest +from jsonschema.exceptions import SchemaError + +from jsontron import JsontronValidator + +SUITE = Path(__file__).resolve().parents[2] / "tests" +JSONTRON = {"rules", "assert", "report"} + + +def _files() -> list[Path]: + files = sorted(p for p in SUITE.glob("*.json") if p.name != "schema.json") + assert files, f"no suite files under {SUITE}" + return files + + +def _cases() -> tuple[list[Any], list[Any]]: + builds, tests = [], [] + for path in _files(): + for group in json.loads(path.read_text(encoding="utf-8")): + name = f"{path.stem}: {group['description']}" + if group.get("buildError"): + builds.append(pytest.param(group["schema"], id=name)) + continue + for test in group["tests"]: + test_id = f"{name}: {test['description']}" + tests.append(pytest.param(group["schema"], test, id=test_id)) + return builds, tests + + +BUILD_ERRORS, TESTS = _cases() + + +def _jsontron_messages(errors: list[Any]) -> list[str]: + """Messages of the errors the Jsontron keywords raised, at any depth.""" + messages: list[str] = [] + pending = list(errors) + while pending: + error = pending.pop() + if error.validator in JSONTRON: + messages.append(error.message) + pending.extend(error.context) + return messages + + +@pytest.mark.parametrize("schema", BUILD_ERRORS) +def test_build_error(schema: Any) -> None: + with pytest.raises(SchemaError): + JsontronValidator.check_schema(schema) + + +@pytest.mark.parametrize("schema", BUILD_ERRORS) +def test_build_error_without_check_schema(schema: Any) -> None: + with pytest.raises(SchemaError): + list(JsontronValidator(schema).iter_errors({})) + + +@pytest.mark.parametrize(("schema", "test"), TESTS) +def test_case(schema: Any, test: Any) -> None: + JsontronValidator.check_schema(schema) + errors = list(JsontronValidator(schema).iter_errors(test["data"])) + assert (not errors) == test["valid"], [e.message for e in errors] + if "errors" in test: + assert sorted(_jsontron_messages(errors)) == sorted(test["errors"]) diff --git a/python/tests/test_validator.py b/python/tests/test_validator.py new file mode 100644 index 0000000..859d65f --- /dev/null +++ b/python/tests/test_validator.py @@ -0,0 +1,259 @@ +"""The jsonschema integration: root document, re-entrancy, caching, build time, errors.""" + +from __future__ import annotations + +import contextlib +import gc +import io +import re +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import jsonschema +import pytest +from jsonschema import Draft7Validator, Draft202012Validator, validators +from jsonschema.exceptions import SchemaError, ValidationError +from referencing import Registry, Resource + +import jsontron +from jsontron import JsontronValidator, extend +from jsontron._compiler import SchemaCache, cache + +ROOT_SCHEMA: dict[str, Any] = { + "$defs": {"item": {"assert": {"test": ". <= $root.max", "message": "\\(.) > \\($root.max)"}}}, + "properties": { + "items": {"items": {"$ref": "#/$defs/item"}}, + "nested": { + "properties": { + "deep": {"items": {"assert": {"test": ". <= $root.max", "message": "deep \\(.)"}}} + } + }, + }, +} + + +def messages(validator: Any, document: Any) -> list[str]: + return sorted(e.message for e in validator.iter_errors(document)) + + +class TestRoot: + def test_nested_properties_items_and_ref(self) -> None: + document = {"max": 3, "items": [1, 5], "nested": {"deep": [2, 9]}} + assert messages(JsontronValidator(ROOT_SCHEMA), document) == ["5 > 3", "deep 9"] + + @pytest.mark.parametrize( + ("keywords", "valid", "invalid"), + [ + ({"if": {"assert": ". == $root.k"}, "then": {"const": 1}}, "y", "x"), + ({"not": {"report": ". == $root.k"}}, "x", "y"), + ({"anyOf": [{"assert": ". == $root.k"}, {"const": 1}]}, "x", "y"), + ({"contains": {"assert": ". == $root.k"}}, ["y", "x"], ["y"]), + ({"unevaluatedItems": {"assert": ". != $root.k"}}, ["y"], ["x"]), + ], + ) + def test_applicators_see_the_document(self, keywords: Any, valid: Any, invalid: Any) -> None: + # `if`, `not`, `contains` and the unevaluated keywords derive validators with evolve() + # and call is_valid() on them, with the nested value as instance. + validator = JsontronValidator({"properties": {"a": keywords}}) + assert validator.is_valid({"k": "x", "a": valid}) + assert not validator.is_valid({"k": "x", "a": invalid}) + + def test_two_validations_interleaved(self) -> None: + first = JsontronValidator(ROOT_SCHEMA).iter_errors({"max": 1, "items": [2, 3, 4]}) + second = JsontronValidator(ROOT_SCHEMA).iter_errors({"max": 3, "items": [2, 3, 4]}) + got = [ + next(first).message, + next(second).message, + next(first).message, + *[e.message for e in second], + *[e.message for e in first], + ] + assert got == ["2 > 1", "4 > 3", "3 > 1", "4 > 1"] + + def test_same_validator_interleaved(self) -> None: + validator = JsontronValidator(ROOT_SCHEMA) + first = validator.iter_errors({"max": 1, "items": [2, 3]}) + second = validator.iter_errors({"max": 2, "items": [2, 3]}) + got = [next(first).message, next(second).message, next(first).message] + assert got == ["2 > 1", "3 > 2", "3 > 1"] + + def test_validation_started_inside_another(self) -> None: + inner_schema = { + "properties": { + "v": {"assert": {"test": ". == $root.want", "message": "inner \\($root.want)"}} + } + } + + def other( + validator: Any, value: Any, instance: Any, schema: Any + ) -> Iterator[ValidationError]: + # A fresh validation of another document, while the outer one is in progress. + for error in JsontronValidator(inner_schema).iter_errors({"want": 1, "v": 2}): + yield ValidationError(error.message) + + outer = extend(validators.extend(Draft202012Validator, {"other": other})) + schema = { + "properties": { + "x": { + "other": True, + "assert": {"test": ". == $root.want", "message": "outer \\($root.want)"}, + } + } + } + assert messages(outer(schema), {"want": "w", "x": "z"}) == ["inner 1", "outer w"] + + def test_root_is_not_kept_after_validation(self) -> None: + validator = JsontronValidator(ROOT_SCHEMA) + before = len(jsontron._validator._roots) + assert not validator.is_valid({"max": 1, "items": [2]}) + gc.collect() + assert len(jsontron._validator._roots) == before + + +class TestDialect: + SCHEMA_2020 = "https://json-schema.org/draft/2020-12/schema" + + def test_subschema_declaring_the_same_dialect_keeps_the_keywords(self) -> None: + schema = { + "$schema": self.SCHEMA_2020, + "properties": {"a": {"$schema": self.SCHEMA_2020, "assert": ". < $root.max"}}, + } + assert messages(JsontronValidator(schema), {"max": 1, "a": 2}) == [". < $root.max"] + + def test_ref_to_a_resource_declaring_its_dialect(self) -> None: + item = { + "$schema": self.SCHEMA_2020, + "$id": "urn:example:item", + "assert": {"test": ". < $root.max", "message": "\\(.) too big"}, + } + registry = Registry().with_resource("urn:example:item", Resource.from_contents(item)) + schema = {"properties": {"items": {"items": {"$ref": "urn:example:item"}}}} + validator = JsontronValidator(schema, registry=registry) + assert messages(validator, {"max": 2, "items": [1, 3]}) == ["3 too big"] + + +class TestErrors: + def test_one_error_per_failure_at_the_instance_location(self) -> None: + schema = { + "properties": { + "a": { + "rules": [ + {"context": ".[]", "asserts": [{"test": ". > 0", "message": "\\(.)"}]} + ] + } + } + } + errors = list(JsontronValidator(schema).iter_errors({"a": [0, -1, 2]})) + assert [(e.message, e.validator, list(e.absolute_path)) for e in errors] == [ + ("0", "rules", ["a"]), + ("-1", "rules", ["a"]), + ] + + @pytest.mark.parametrize( + ("schema", "owner"), + [ + ( + { + "rules": [{"context": ".", "asserts": [{"test": "false"}]}], + "assert": "false", + "report": "true", + }, + "rules", + ), + ({"assert": "false", "report": "true", "let": {"x": "1"}}, "assert"), + ({"report": "true", "let": {"x": "1"}}, "report"), + ], + ) + def test_owner_keyword(self, schema: dict[str, Any], owner: str) -> None: + errors = list(JsontronValidator(schema).iter_errors({})) + assert errors + assert {e.validator for e in errors} == {owner} + + def test_evaluation_error_is_one_error(self) -> None: + schema = {"assert": [".a.b", "false"]} + errors = list(JsontronValidator(schema).iter_errors({"a": "text"})) + assert len(errors) == 1 + assert errors[0].message.startswith("Jsontron evaluation error:") + + def test_validate_raises(self) -> None: + with pytest.raises(ValidationError, match="too small"): + jsonschema.validate( + {"n": 1}, + {"assert": {"test": ".n > 1", "message": "too small"}}, + cls=JsontronValidator, + ) + + +class TestBuild: + def test_check_schema_points_at_the_schema_object(self) -> None: + schema = {"properties": {"a": {"items": {}, "prefixItems": [{}, {"assert": ".a |"}]}}} + with pytest.raises(SchemaError) as raised: + JsontronValidator.check_schema(schema) + assert list(raised.value.path) == ["properties", "a", "prefixItems", 1] + assert "/properties/a/prefixItems/1" in raised.value.message + + def test_check_schema_still_checks_standard_keywords(self) -> None: + with pytest.raises(SchemaError): + JsontronValidator.check_schema({"type": 5}) + + def test_values_that_are_not_schemas_are_not_checked(self) -> None: + JsontronValidator.check_schema({"const": {"assert": 5}, "examples": [{"rules": []}]}) + + def test_invalid_schema_fails_on_first_use(self) -> None: + validator = JsontronValidator({"properties": {"a": {"assert": ".a |"}}}) + assert validator.is_valid({"b": 1}) # not applied yet + with pytest.raises(SchemaError): + validator.is_valid({"a": 1}) + + def test_id_reuse_after_collection(self) -> None: + # Schema objects created and dropped in turn often get the same id(); each must get its + # own compilation. + for i in range(50): + schema = {"assert": {"test": f". == {i}", "message": f"not {i}"}} + assert messages(JsontronValidator(schema), -1) == [f"not {i}"] + del schema + + def test_schema_cache_is_bounded(self) -> None: + small = SchemaCache(maxsize=2) + schemas = [{"assert": f". == {i}"} for i in range(3)] + compiled = [small.get(s) for s in schemas] + assert len(small) == 2 + assert small.get(schemas[2]) is compiled[2] + assert small.get(schemas[0]) is not compiled[0] + + def test_check_schema_fills_the_cache(self) -> None: + cache.clear() + JsontronValidator.check_schema( + {"properties": {"a": {"assert": "true"}, "b": {"report": "false"}}} + ) + assert len(cache) == 2 + + +class TestExtend: + def test_other_draft(self) -> None: + validator_class = extend(Draft7Validator) + schema = {"properties": {"a": {"assert": {"test": ". == $root.k", "message": "no"}}}} + validator_class.check_schema(schema) + assert messages(validator_class(schema), {"k": 1, "a": 2}) == ["no"] + assert validator_class(schema).is_valid({"k": 1, "a": 1}) + + def test_meta_schema_is_packaged(self) -> None: + assert jsontron.meta_schema()["$id"] == "https://www.schemastore.org/jsontron-0.2.json" + assert jsontron.SPEC_VERSION == "0.2" + + +def test_readme_quick_start() -> None: + readme = (Path(__file__).resolve().parents[1] / "readme.md").read_text(encoding="utf-8") + code = re.search(r"```python\n(.*?)```", readme, re.S) + assert code is not None + printed = io.StringIO() + with contextlib.redirect_stdout(printed): + exec(code.group(1), {}) + expected = [ + line.strip()[2:] + for line in code.group(1).splitlines() + if line.startswith("# ") and not line.startswith("# O-") + ] + expected.append("False") + assert printed.getvalue().splitlines() == expected diff --git a/readme.md b/readme.md index 7649e7c..873b90a 100644 --- a/readme.md +++ b/readme.md @@ -29,12 +29,25 @@ the document root, or select a subset of nodes and assert something about each. [JsonSchema.Net](https://www.nuget.org/packages/JsonSchema.Net): Schematron-style `rules`, `assert`, `report`, and `let` keywords whose `context` and `test` expressions are [jq](https://jqlang.org), evaluated by -[Devlooped.JQSharp](https://www.nuget.org/packages/Devlooped.JQSharp). +[JQLite](https://github.com/devlooped/jqlite). - Structural validation stays with JSON Schema. - Cross-cutting rules stay in the schema, next to the data they describe. - jq expressions are parsed once when the schema is built, then reused. +## Implementations + +The keywords and their semantics are defined by the [specification](spec/jsontron.md) and +checked by a shared [conformance suite](tests/readme.md) that every implementation runs. + +| Language | Package | JSON Schema library | jq engine | +|----------|---------|---------------------|-----------| +| .NET | [Jsontron](https://www.nuget.org/packages/Jsontron) ([source](dotnet)) | [JsonSchema.Net](https://www.nuget.org/packages/JsonSchema.Net) | [JQLite](https://www.nuget.org/packages/JQLite) | +| JavaScript / TypeScript | [@devlooped/jsontron](js/readme.md) | [Ajv](https://ajv.js.org) | [@devlooped/jqlite](https://www.npmjs.com/package/@devlooped/jqlite) | +| Python | [jsontron](python/readme.md) | [jsonschema](https://python-jsonschema.readthedocs.io) | [devlooped-jqlite](https://pypi.org/project/devlooped-jqlite/) | + +The rest of this page uses .NET for its examples; the schemas are the same in every language. + ## Quick start ```csharp @@ -157,7 +170,7 @@ Forms accepted: | JSON | Meaning | |------|---------| -| `"assert": ""` | One assert; test and message source are that expression | +| `"assert": ""` | One assert; the failure message is the expression text | | `"assert": { "test", "message" }` | Explicit message (still a jq string expression) | | `"assert": [ ... ]` | Several asserts, all on the same `context: "."` rule | @@ -363,7 +376,9 @@ Keyword syntax is also published as [`schemas/jsontron-0.2.json`](schemas/jsontr - **Build-time compile**: invalid keyword shape or invalid jq fails when the schema is built, not on the first instance. - **No rule shadowing** (v1): every rule runs (closer to Schematron 2025 `group` than classic pattern shadowing). - **Empty context**: if `context` matches nothing, asserts do not run โ€” vacuously valid. -- **Stack**: JsonSchema.Net 9.x + Devlooped.JQSharp 1.0.2+ (evaluation-time variables for `$root`). +- **One error per failure**: each failed assert or report is its own error. In .NET they are + child results of the schema object (`Details`), at `/`. +- **Stack**: JsonSchema.Net 9.x + JQLite 1.0+ (evaluation-time variables for `$root`). --- diff --git a/spec/jsontron.md b/spec/jsontron.md new file mode 100644 index 0000000..2143cec --- /dev/null +++ b/spec/jsontron.md @@ -0,0 +1,225 @@ +# Jsontron 0.2 specification + +Jsontron is a JSON Schema vocabulary for Schematron-style business rules whose expressions +are [jq](https://jqlang.org). This document defines what a conforming implementation does. +The syntax of the keywords is defined by the meta-schema +[`schemas/jsontron-0.2.json`](../schemas/jsontron-0.2.json); the conformance suite in +[`tests/`](../tests/readme.md) is the executable form of this document. + +The words MUST, SHOULD and MAY are used as in RFC 2119. + +## 1. Keywords + +Jsontron adds four keywords to a schema object: + +| Keyword | Value | Role | +|---------|-------|------| +| `rules` | non-empty array of rule objects | assertion | +| `assert` | assert item, or non-empty array of them | assertion, sugar for a `context: "."` rule | +| `report` | same shape as `assert` | assertion, inverse of `assert` | +| `let` | non-empty object of name โ†’ jq expression | bindings for the three above | + +A **rule object** has a string `context`, at least one of `asserts` / `reports` (non-empty +arrays of objects), and optional `let` and `id`. + +An **assert item** is an object with a string `test` and optional `message`, `id`, and one of +`flag` or `role` (setting both is an error). In the `assert` / `report` sugar, an item may also +be a bare string `""`, which stands for `{ "test": "" }`. + +When `message` is absent, the failure message is the text of `test`, taken literally. + +`id`, `flag` and `role` are strings with at least one non-whitespace character, trimmed of +surrounding whitespace. `role` is an +alias of `flag`. `let` names match `[A-Za-z_][A-Za-z0-9_]*` and `root` is reserved. +`context`, `test` and `let` expressions are non-empty. + +## 2. The rule set of a schema object + +The four keywords on one schema object form a single **rule set**, built when the schema is +compiled: + +1. Start with the rules of `rules`, in order (none when `rules` is absent). +2. Collect the items of `assert` as asserts and the items of `report` as reports. +3. If there are any, append them to the first rule whose `context` is exactly the string `"."`: + asserts after that rule's asserts, reports after its reports. If no such rule exists, append + a new rule `{ "context": "." }` holding them, with no `id` and no `let`. +4. The schema-level `let` bindings apply to the whole rule set. + +A schema object that has `let` and none of `rules`, `assert`, `report` has no rule set: its +`let` is checked at build time and never evaluated. + +The rule set is evaluated once per instance the schema object is applied to, and produces +either a list of **failures** (possibly empty) or one **evaluation error**. It is an assertion: +the schema object is invalid for that instance when the list is non-empty or there is an error, +and it takes part in `allOf`, `anyOf`, `oneOf`, `not`, `if` and `$ref` like any other assertion +keyword. + +## 3. Evaluation + +Let *instance* be the value the schema object is applied to and *root* the whole document +being validated. + +1. `$root` is bound to *root* in every expression. +2. **Schema-level `let`**: for each binding in document order, evaluate its expression with + `.` = *instance*; bind `$name` to the first value it produces, or to `null` when it produces + none. A binding sees `$root` and the bindings before it. +3. For each rule, in order: + 1. Evaluate `context` with `.` = *instance*. Each value it produces is a **context node**. + No values means the rule is vacuously satisfied. + 2. For each context node, in order: + 1. **Rule-level `let`**: as in step 2, with `.` = the context node. These bindings are + visible to this rule only and shadow schema-level bindings of the same name. + 2. For each assert, then each report, in order: evaluate `test` with `.` = the context + node. The test is **truthy** when it produces at least one value and none of its + values is `false` or `null`. An assert fails when its test is not truthy; a report + fails when its test is truthy. + 3. Each failing item adds one failure whose text is its message (section 4). + +Rule-level bindings are not visible in `context`. Every rule runs: there is no shadowing +between rules. + +**Evaluation error.** If evaluating a `let`, `context` or `test` expression raises a jq error, +evaluation of the rule set stops, failures collected so far are discarded, and the result is a +single error carrying the engine's error text. That text is not normative. + +## 4. Messages + +An item without `message` has the text of its `test` as message: it is not evaluated, so +quotes and `\(...)` in it are kept as written. + +Otherwise the `message` string is turned into a jq expression: + +- If, ignoring leading whitespace, it starts with `"`, it is used as is. +- Otherwise it is wrapped as a jq string literal, reading it left to right: + - a backslash and the character after it are copied unchanged, except that + - `\(` starts an interpolation, which is copied unchanged up to its matching `)`. Matching + counts nested parentheses and skips jq string literals inside the interpolation (which may + contain interpolations of their own); + - elsewhere, `"` becomes `\"`, and newline, carriage return and tab become `\n`, `\r`, `\t`. + + So `\(...)` interpolation works in plain text, and quotes inside it are jq's own: + `order \(.id // "?") is "late"` becomes `"order \(.id // "?") is \"late\""`. + +It is evaluated with `.` = the context node and all bindings of the rule in scope. The first +value it produces is the message: a string as is, `null` as the empty string, any other value +as its JSON text. If it produces no value or raises an error, the message is the empty string. + +The failure text is the message with a prefix built from the labels that are set, in this +order, followed by one space: `[]`, `[]`, `[flag=]`. With no +label set there is no prefix and no space. + +``` +[orders][high-value-discount][flag=warning] order O-1 discount is below policy +``` + +## 5. Reporting + +- Each failure is reported as its own validation error, in the order produced. An evaluation + error is reported as one validation error. +- The instance location of these errors is the location of *instance*, the value the schema + object is applied to (not the context node). +- How errors are surfaced otherwise (types, keyword name, schema location) follows the host + JSON Schema library. + +## 6. Build time + +An implementation MUST reject, when the schema is compiled and before any instance is +validated: + +- keyword values that do not match section 1, and +- any `context`, `test`, `let` or message expression that is not a valid jq program on its own + (syntax errors, unknown functions, unknown labels). + +Each expression MUST be checked in isolation. Checking only a program assembled from several +expressions is not enough, since unbalanced text such as `true) , (false` can be valid once +embedded. An implementation that runs an assembled program (section 7) MUST compile that +program at build time as well. + +A reference to a variable that is not in scope (`$root`, an in-scope `let`, or a binding in +the expression itself) fails as an evaluation error under [jqlite](https://github.com/devlooped/jqlite) +(which treats unbound `$name` as a host variable); an implementation backed by an engine that +checks variable scope at compile time MAY reject it at build time instead. + +## 7. Reference lowering + +The semantics above are equivalent to running one jq program per rule set, with input +`{ "root": , "node": }` and a single output: the array of failure texts. +Implementations MAY run this lowered program or evaluate expression by expression with host +variables, as long as they pass the suite. + +In the templates, `โŸจxโŸฉ` is the text of an expression followed by two newlines, so that a +trailing jq comment cannot swallow what follows (the second newline ends a comment that a +final backslash continues onto the next line), and `โŸชsโŸซ` is `s` as a JSON string literal. + +``` +PROGRAM := .root as $root | .node | LETS [ RULE , RULE , ... ] +LETS := first((โŸจlet exprโŸฉ), null) as $name | (once per binding, in order; may be empty) +RULE := ((โŸจcontextโŸฉ) | LETS (ITEM , ITEM , ...)) +ITEM := (if TRUTHY then empty else TEXT end) (assert) + (if TRUTHY then TEXT else empty end) (report) +TRUTHY := ([(โŸจtestโŸฉ)] | length > 0 and all(.[]; . != null and . != false)) +TEXT := (โŸชprefixโŸซ + (try first(((โŸจmessage exprโŸฉ) | STR), "") catch "")) (item with message) + โŸชprefix + test textโŸซ (item without message) +STR := if type == "string" then . elif . == null then "" else tojson end +``` + +For this schema object: + +```json +{ + "let": { "cap": ".policy.cap" }, + "rules": [ { "id": "orders", "context": ".orders[]", + "asserts": [ { "test": ".lines <= $cap", "message": "order \\(.id) over cap" } ] } ], + "report": ".locked" +} +``` + +the program is (line breaks inside `โŸจxโŸฉ` omitted): + +``` +.root as $root | .node | first((.policy.cap), null) as $cap | +[ ((.orders[]) | ((if ([(.lines <= $cap)] | length > 0 and all(.[]; . != null and . != false)) + then empty + else ("[orders] " + (try first((("order \(.id) over cap") | STR), "") catch "")) end))), + ((.) | ((if ([(.locked)] | length > 0 and all(.[]; . != null and . != false)) + then ".locked" + else empty end))) ] +``` + +A jq error escaping this program is the evaluation error of section 3. + +## 8. Portable jq profile + +The reference for expression semantics is **[jqlite](https://github.com/devlooped/jqlite)**, +the portable profile of jq 1.8. Schema authors can rely on the following in every conforming +implementation; the suite file `tests/jq-profile.json` tests them. + +- Paths and iteration: `.`, `.a`, `.a.b`, `.["a"]`, `.[n]`, slices, `.[]`, `..`, optional `?`. +- Operators: `|`, `,`, arithmetic, comparisons, `and` / `or` / `not`, `//`. +- Construction: arrays, objects, string interpolation `"\(...)"`. +- Control: `if` / `elif` / `else`, `try` / `catch`, `reduce`, `foreach`, `... as $x`, + destructuring, `def`. +- Builtins: `length`, `keys`, `has`, `in`, `type`, `select`, `empty`, `error`, `map`, + `map_values`, `to_entries`, `from_entries`, `with_entries`, `add`, `any`, `all`, `range`, + `first`, `last`, `limit`, `unique`, `unique_by`, `group_by`, `sort`, `sort_by`, `min`, `max`, + `min_by`, `max_by`, `contains`, `inside`, `index`, `indices`, `IN`, `INDEX`, `tostring`, + `tonumber`, `tojson`, `fromjson`, `startswith`, `endswith`, `ltrimstr`, `rtrimstr`, `split`, + `join`, `ascii_downcase`, `ascii_upcase`, `test`, `match`, `capture`, `sub`, `gsub`, `floor`, + `ceil`, `round`, `sqrt`, `abs`, `paths`, `getpath`, `flatten`, `reverse`, `not`, `isempty`, + `values`, `nulls`, `strings`, `numbers`, `booleans`, `arrays`, `objects`, `scalars`. + +Outside the profile, and not to be relied on: + +- Input, output and environment: `input`, `inputs`, `debug`, `stderr`, `input_filename`, + `$ENV`, `env`, `halt`, `halt_error`, `$__loc__`, modules (`import`, `include`), `now` and the + date functions. +- Regular expression features outside the jqlite regex flavor (no lookaround, backreferences + or inline flags; ASCII character classes). +- Numbers that are not exactly representable as IEEE 754 doubles, and the exact text `tojson` + gives a non-integer number. +- The text of jq error messages. + +## 9. Versioning + +The version of this specification is the version of the meta-schema. Implementations state +which specification version they implement; their own package versions are independent of it. diff --git a/src/Jsontron/Model/AssertSpec.cs b/src/Jsontron/Model/AssertSpec.cs deleted file mode 100644 index f64b285..0000000 --- a/src/Jsontron/Model/AssertSpec.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Jsontron; - -/// -/// Uncompiled assert specification (test and message source text). -/// -readonly record struct AssertSpec(string Test, string Message, string? Id = null, string? Flag = null); diff --git a/src/Tests/AssertSugarTests.cs b/src/Tests/AssertSugarTests.cs deleted file mode 100644 index 3efdc67..0000000 --- a/src/Tests/AssertSugarTests.cs +++ /dev/null @@ -1,93 +0,0 @@ -using Json.Schema; - -namespace Jsontron.Tests; - -public class AssertSugarTests : JsontronFixture -{ - [Fact] - public void String_assert_passes_when_test_is_truthy() - { - var result = Evaluate( - """ - { - "type": "object", - "assert": ".value > 0" - } - """, - """{ "value": 1 }"""); - - Assert.True(result.IsValid); - } - - [Fact] - public void String_assert_fails_when_test_is_falsey() - { - var result = Evaluate( - """ - { - "type": "object", - "assert": ".value > 0" - } - """, - """{ "value": 0 }"""); - - Assert.False(result.IsValid); - } - - [Fact] - public void Object_assert_uses_custom_message() - { - var result = Evaluate( - """ - { - "type": "object", - "assert": { - "test": ".value > 0", - "message": "value must be positive" - } - } - """, - """{ "value": -1 }"""); - - Assert.False(result.IsValid); - Assert.Contains("value must be positive", CollectErrors(result)); - } - - [Fact] - public void Array_assert_appends_to_single_root_context_rule() - { - var result = Evaluate( - """ - { - "type": "object", - "assert": [ - ".a > 0", - { "test": ".b > 0", "message": "b must be positive" } - ] - } - """, - """{ "a": -1, "b": -1 }"""); - - Assert.False(result.IsValid); - Assert.Contains("b must be positive", CollectErrors(result)); - } - - [Fact] - public void Message_supports_jq_string_interpolation() - { - var result = Evaluate( - """ - { - "type": "object", - "assert": { - "test": ".value > 0", - "message": "bad value: \\(.value)" - } - } - """, - """{ "value": -5 }"""); - - Assert.False(result.IsValid); - Assert.Contains("bad value: -5", CollectErrors(result)); - } -} diff --git a/src/Tests/BuildErrorTests.cs b/src/Tests/BuildErrorTests.cs deleted file mode 100644 index 2291a59..0000000 --- a/src/Tests/BuildErrorTests.cs +++ /dev/null @@ -1,46 +0,0 @@ -using Json.Schema; - -namespace Jsontron.Tests; - -public class BuildErrorTests : JsontronFixture -{ - [Fact] - public void Invalid_assert_shape_throws_at_build() - { - Assert.ThrowsAny(() => Schema( - """ - { - "assert": 42 - } - """)); - } - - [Fact] - public void Invalid_jq_test_throws_at_build() - { - Assert.ThrowsAny(() => Schema( - """ - { - "assert": { - "test": "(((", - "message": "x" - } - } - """)); - } - - [Fact] - public void Rules_without_context_throws_at_build() - { - Assert.ThrowsAny(() => Schema( - """ - { - "rules": [ - { - "asserts": [ { "test": "true" } ] - } - ] - } - """)); - } -} diff --git a/src/Tests/JsontronFixture.cs b/src/Tests/JsontronFixture.cs deleted file mode 100644 index 7e54ad4..0000000 --- a/src/Tests/JsontronFixture.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Text.Json; -using Json.Schema; - -namespace Jsontron.Tests; - -public abstract class JsontronFixture -{ - static JsontronFixture() => MetaSchemas.Register(); - - protected static JsonSchema Schema(string json) => JsonSchema.FromText(json); - - protected static JsonElement Instance(string json) => JsonDocument.Parse(json).RootElement; - - protected static EvaluationResults Evaluate(string schemaJson, string instanceJson) - => Schema(schemaJson).Evaluate( - Instance(instanceJson), - new EvaluationOptions { OutputFormat = OutputFormat.List }); - - protected static string CollectErrors(EvaluationResults result) - { - List errors = []; - CollectErrors(result, errors); - return string.Join("; ", errors); - } - - static void CollectErrors(EvaluationResults result, List errors) - { - if (result.Errors is not null) - errors.AddRange(result.Errors.Values); - - if (result.Details is null) - return; - - foreach (var detail in result.Details) - CollectErrors(detail, errors); - } -} diff --git a/src/Tests/LetTests.cs b/src/Tests/LetTests.cs deleted file mode 100644 index c451bb0..0000000 --- a/src/Tests/LetTests.cs +++ /dev/null @@ -1,261 +0,0 @@ -using Json.Schema; - -namespace Jsontron.Tests; - -public class LetTests : JsontronFixture -{ - [Fact] - public void Schema_level_let_is_visible_in_rule_context() - { - var result = Evaluate( - """ - { - "let": { "threshold": ".policy.min" }, - "rules": [ - { - "context": ".items[] | select(.n < $threshold)", - "asserts": [ - { "test": "false", "message": "value \\(.n) below threshold" } - ] - } - ] - } - """, - """{ "policy": { "min": 10 }, "items": [ { "n": 5 }, { "n": 20 } ] }"""); - - Assert.False(result.IsValid); - Assert.Contains("value 5 below threshold", CollectErrors(result)); - } - - [Fact] - public void Schema_level_let_is_visible_in_assert_sugar() - { - var result = Evaluate( - """ - { - "let": { "min": ".limits.min" }, - "assert": { - "test": ".value >= $min", - "message": "value \\(.value) is below \\($min)" - } - } - """, - """{ "limits": { "min": 10 }, "value": 5 }"""); - - Assert.False(result.IsValid); - Assert.Contains("value 5 is below 10", CollectErrors(result)); - } - - [Fact] - public void Schema_level_let_is_visible_in_report_sugar() - { - var result = Evaluate( - """ - { - "let": { "cap": ".limits.max" }, - "report": { - "test": ".value > $cap", - "message": "value \\(.value) exceeds \\($cap)" - } - } - """, - """{ "limits": { "max": 10 }, "value": 15 }"""); - - Assert.False(result.IsValid); - Assert.Contains("value 15 exceeds 10", CollectErrors(result)); - } - - [Fact] - public void Let_bindings_are_evaluated_in_order_and_see_earlier_bindings() - { - var result = Evaluate( - """ - { - "let": { - "base": ".base", - "doubled": "$base * 2" - }, - "assert": { - "test": ".value == $doubled", - "message": "expected \\($doubled), got \\(.value)" - } - } - """, - """{ "base": 7, "value": 10 }"""); - - Assert.False(result.IsValid); - Assert.Contains("expected 14, got 10", CollectErrors(result)); - } - - [Fact] - public void Let_binds_null_when_expression_yields_empty_stream() - { - var result = Evaluate( - """ - { - "let": { "missing": ".notThere[]?" }, - "assert": { - "test": "$missing == null", - "message": "missing was not null: \\($missing)" - } - } - """, - """{ "value": 1 }"""); - - Assert.True(result.IsValid); - } - - [Fact] - public void Rule_level_let_is_visible_to_rule_asserts() - { - var result = Evaluate( - """ - { - "rules": [ - { - "context": ".orders[]", - "let": { "ship": ".shipments[0] // null" }, - "asserts": [ - { - "test": "$ship == null or $ship.weight <= 100", - "message": "order \\(.id) has heavy shipment \\($ship.weight)" - } - ] - } - ] - } - """, - """ - { - "orders": [ - { "id": "o1", "shipments": [ { "weight": 50 } ] }, - { "id": "o2", "shipments": [ { "weight": 200 } ] } - ] - } - """); - - Assert.False(result.IsValid); - Assert.Contains("order o2 has heavy shipment 200", CollectErrors(result)); - } - - [Fact] - public void Rule_level_let_is_not_visible_to_a_later_rule() - { - // Second rule references $local which was only bound inside the first rule. - // Jq variable references are resolved at evaluation time, so the first rule - // passes and the second rule fails (either because the variable is unbound and - // the engine reports an error, or because it resolves to something that makes - // the test falsey). Either way the schema must not be valid against the instance. - var result = Evaluate( - """ - { - "rules": [ - { - "context": ".", - "let": { "local": ".a" }, - "asserts": [ { "test": "$local == 1", "message": "first rule saw local" } ] - }, - { - "context": ".", - "asserts": [ { "test": "$local == 1", "message": "leak: local must not be visible here" } ] - } - ] - } - """, - """{ "a": 1 }"""); - - Assert.False(result.IsValid); - } - - [Fact] - public void Schema_level_let_in_rule_level_rule_with_lets_both_scopes_seen() - { - var result = Evaluate( - """ - { - "let": { "cap": ".cap" }, - "rules": [ - { - "context": ".items[]", - "let": { "doubled": ".n * 2" }, - "asserts": [ - { - "test": "$doubled <= $cap", - "message": "doubled \\($doubled) exceeds cap \\($cap)" - } - ] - } - ] - } - """, - """{ "cap": 10, "items": [ { "n": 3 }, { "n": 8 } ] }"""); - - Assert.False(result.IsValid); - Assert.Contains("doubled 16 exceeds cap 10", CollectErrors(result)); - } - - [Fact] - public void Reserved_root_is_rejected_at_build() - { - Assert.ThrowsAny(() => Schema( - """ - { - "let": { "root": "." }, - "assert": ".x > 0" - } - """)); - } - - [Fact] - public void Invalid_identifier_is_rejected_at_build() - { - Assert.ThrowsAny(() => Schema( - """ - { - "let": { "1bad": "." }, - "assert": ".x > 0" - } - """)); - } - - [Fact] - public void Let_requires_string_expression() - { - Assert.ThrowsAny(() => Schema( - """ - { - "let": { "x": 42 }, - "assert": ".x > 0" - } - """)); - } - - [Fact] - public void Invalid_let_jq_throws_at_build() - { - Assert.ThrowsAny(() => Schema( - """ - { - "let": { "x": "(((" }, - "assert": ".x > 0" - } - """)); - } - - [Fact] - public void Rule_level_let_with_invalid_identifier_throws_at_build() - { - Assert.ThrowsAny(() => Schema( - """ - { - "rules": [ - { - "context": ".", - "let": { "root": "." }, - "asserts": [ { "test": "true" } ] - } - ] - } - """)); - } -} diff --git a/src/Tests/MergeTests.cs b/src/Tests/MergeTests.cs deleted file mode 100644 index 0b9b2a6..0000000 --- a/src/Tests/MergeTests.cs +++ /dev/null @@ -1,84 +0,0 @@ -using Json.Schema; - -namespace Jsontron.Tests; - -public class MergeTests : JsontronFixture -{ - [Fact] - public void Assert_merges_into_existing_root_context_rule() - { - var result = Evaluate( - """ - { - "type": "object", - "assert": { - "test": ".x > 0", - "message": "from assert" - }, - "rules": [ - { - "context": ".", - "asserts": [ - { "test": ".y > 0", "message": "from rules" } - ] - } - ] - } - """, - """{ "x": -1, "y": -1 }"""); - - Assert.False(result.IsValid); - var errors = CollectErrors(result); - Assert.Contains("from assert", errors); - Assert.Contains("from rules", errors); - } - - [Fact] - public void Assert_creates_root_context_rule_when_rules_lack_one() - { - var result = Evaluate( - """ - { - "type": "object", - "assert": { - "test": ".ok == true", - "message": "not ok" - }, - "rules": [ - { - "context": ".items[]", - "asserts": [ - { "test": ".n > 0", "message": "item" } - ] - } - ] - } - """, - """{ "ok": false, "items": [] }"""); - - Assert.False(result.IsValid); - Assert.Contains("not ok", CollectErrors(result)); - } - - [Fact] - public void Assert_is_not_evaluated_twice_when_rules_present() - { - // If both keywords evaluated the same assert, we would still only get one logical failure; - // this checks the merge path produces a single coherent invalid result without throw. - var result = Evaluate( - """ - { - "assert": ".v == 1", - "rules": [ - { - "context": ".", - "asserts": [ { "test": ".v == 1", "message": "v" } ] - } - ] - } - """, - """{ "v": 0 }"""); - - Assert.False(result.IsValid); - } -} diff --git a/src/Tests/ReportTests.cs b/src/Tests/ReportTests.cs deleted file mode 100644 index 5718059..0000000 --- a/src/Tests/ReportTests.cs +++ /dev/null @@ -1,210 +0,0 @@ -using Json.Schema; - -namespace Jsontron.Tests; - -public class ReportTests : JsontronFixture -{ - [Fact] - public void String_report_fails_when_test_is_truthy() - { - var result = Evaluate( - """ - { - "type": "object", - "report": ".value < 0" - } - """, - """{ "value": -1 }"""); - - Assert.False(result.IsValid); - } - - [Fact] - public void String_report_passes_when_test_is_falsey() - { - var result = Evaluate( - """ - { - "type": "object", - "report": ".value < 0" - } - """, - """{ "value": 1 }"""); - - Assert.True(result.IsValid); - } - - [Fact] - public void Object_report_uses_custom_message() - { - var result = Evaluate( - """ - { - "type": "object", - "report": { - "test": ".value < 0", - "message": "value must not be negative" - } - } - """, - """{ "value": -5 }"""); - - Assert.False(result.IsValid); - Assert.Contains("value must not be negative", CollectErrors(result)); - } - - [Fact] - public void Array_report_appends_to_single_root_context_rule() - { - var result = Evaluate( - """ - { - "type": "object", - "report": [ - ".a < 0", - { "test": ".b < 0", "message": "b must not be negative" } - ] - } - """, - """{ "a": 1, "b": -1 }"""); - - Assert.False(result.IsValid); - Assert.Contains("b must not be negative", CollectErrors(result)); - } - - [Fact] - public void Empty_stream_test_does_not_trigger_report() - { - // jq-truthy requires at least one non-false, non-null result; empty stream is falsey, - // so a report with an empty-stream test must NOT fire. - var result = Evaluate( - """ - { - "type": "object", - "report": ".missing[]?" - } - """, - """{ "value": 1 }"""); - - Assert.True(result.IsValid); - } - - [Fact] - public void Rule_with_reports_only() - { - var result = Evaluate( - """ - { - "rules": [ - { - "context": ".items[]", - "reports": [ - { "test": ".qty < 0", "message": "item \\(.id) has negative qty" } - ] - } - ] - } - """, - """{ "items": [ { "id": "a", "qty": 1 }, { "id": "b", "qty": -3 } ] }"""); - - Assert.False(result.IsValid); - Assert.Contains("item b has negative qty", CollectErrors(result)); - } - - [Fact] - public void Rule_with_both_asserts_and_reports() - { - var result = Evaluate( - """ - { - "rules": [ - { - "context": ".items[]", - "asserts": [ - { "test": ".id | type == \"string\"", "message": "id must be a string" } - ], - "reports": [ - { "test": ".qty < 0", "message": "qty must not be negative" } - ] - } - ] - } - """, - """{ "items": [ { "id": "a", "qty": -1 } ] }"""); - - Assert.False(result.IsValid); - Assert.Contains("qty must not be negative", CollectErrors(result)); - } - - [Fact] - public void Top_level_report_merges_into_root_context_rule_alongside_rules() - { - var result = Evaluate( - """ - { - "report": { - "test": ".forbidden == true", - "message": "forbidden" - }, - "rules": [ - { - "context": ".", - "asserts": [ - { "test": ".value > 0", "message": "value must be positive" } - ] - } - ] - } - """, - """{ "forbidden": true, "value": -1 }"""); - - Assert.False(result.IsValid); - var errors = CollectErrors(result); - Assert.Contains("forbidden", errors); - Assert.Contains("value must be positive", errors); - } - - [Fact] - public void Top_level_assert_and_report_merge_into_synthetic_root_rule() - { - var result = Evaluate( - """ - { - "assert": { "test": ".ok == true", "message": "not ok" }, - "report": { "test": ".forbidden == true", "message": "forbidden" } - } - """, - """{ "ok": false, "forbidden": true }"""); - - Assert.False(result.IsValid); - var errors = CollectErrors(result); - Assert.Contains("not ok", errors); - Assert.Contains("forbidden", errors); - } - - [Fact] - public void Report_sugar_invalid_shape_throws_at_build() - { - Assert.ThrowsAny(() => Schema( - """ - { - "report": 42 - } - """)); - } - - [Fact] - public void Rule_without_asserts_or_reports_throws_at_build() - { - Assert.ThrowsAny(() => Schema( - """ - { - "rules": [ - { - "context": "." - } - ] - } - """)); - } -} diff --git a/src/Tests/RulesTests.cs b/src/Tests/RulesTests.cs deleted file mode 100644 index d02efe7..0000000 --- a/src/Tests/RulesTests.cs +++ /dev/null @@ -1,125 +0,0 @@ -using Json.Schema; - -namespace Jsontron.Tests; - -public class RulesTests : JsontronFixture -{ - const string SampleSchema = """ - { - "type": "object", - "required": [ "orders", "policy", "approvedCustomers" ], - "rules": [ - { - "context": ".orders[] | select(.total > 1000)", - "asserts": [ - { - "test": ".discount >= ($root.policy.minHighValueDiscount // 0.1)", - "message": "High-value orders must respect the root policy discount" - }, - { - "test": ".customer.id | IN($root.approvedCustomers[])", - "message": "Customer is not on the approved list" - } - ] - } - ] - } - """; - - [Fact] - public void High_value_order_passes_policy_and_approved_customer() - { - var result = Evaluate(SampleSchema, """ - { - "policy": { "minHighValueDiscount": 0.15 }, - "approvedCustomers": [ "c1", "c2" ], - "orders": [ - { "total": 1500, "discount": 0.2, "customer": { "id": "c1" } }, - { "total": 50, "discount": 0, "customer": { "id": "unknown" } } - ] - } - """); - - Assert.True(result.IsValid); - } - - [Fact] - public void High_value_order_fails_discount_policy() - { - var result = Evaluate(SampleSchema, """ - { - "policy": { "minHighValueDiscount": 0.15 }, - "approvedCustomers": [ "c1" ], - "orders": [ - { "total": 1500, "discount": 0.05, "customer": { "id": "c1" } } - ] - } - """); - - Assert.False(result.IsValid); - Assert.Contains("High-value orders must respect the root policy discount", CollectErrors(result)); - } - - [Fact] - public void High_value_order_fails_unapproved_customer() - { - var result = Evaluate(SampleSchema, """ - { - "policy": { "minHighValueDiscount": 0.1 }, - "approvedCustomers": [ "c1" ], - "orders": [ - { "total": 2000, "discount": 0.2, "customer": { "id": "c99" } } - ] - } - """); - - Assert.False(result.IsValid); - Assert.Contains("Customer is not on the approved list", CollectErrors(result)); - } - - [Fact] - public void Empty_context_match_is_vacuously_valid() - { - var result = Evaluate(SampleSchema, """ - { - "policy": { "minHighValueDiscount": 0.5 }, - "approvedCustomers": [], - "orders": [ - { "total": 10, "discount": 0, "customer": { "id": "x" } } - ] - } - """); - - Assert.True(result.IsValid); - } - - [Fact] - public void Nested_assert_uses_local_instance_as_dot() - { - var result = Evaluate( - """ - { - "type": "object", - "properties": { - "orders": { - "type": "array", - "items": { - "type": "object", - "assert": ".total >= 0" - } - } - } - } - """, - """ - { - "orders": [ - { "total": 1 }, - { "total": -3 } - ] - } - """); - - Assert.False(result.IsValid); - } -} diff --git a/src/Tests/SeverityAndIdTests.cs b/src/Tests/SeverityAndIdTests.cs deleted file mode 100644 index 05ad795..0000000 --- a/src/Tests/SeverityAndIdTests.cs +++ /dev/null @@ -1,297 +0,0 @@ -using Json.Schema; - -namespace Jsontron.Tests; - -public class SeverityAndIdTests : JsontronFixture -{ - [Fact] - public void Assert_id_prefixes_message() - { - var result = Evaluate( - """ - { - "type": "object", - "assert": { - "id": "A-1", - "test": ".value > 0", - "message": "value must be positive" - } - } - """, - """{ "value": -1 }"""); - - Assert.False(result.IsValid); - Assert.Contains("[A-1] value must be positive", CollectErrors(result)); - } - - [Fact] - public void Report_id_prefixes_message() - { - var result = Evaluate( - """ - { - "type": "object", - "report": { - "id": "R-1", - "test": ".forbidden == true", - "message": "forbidden" - } - } - """, - """{ "forbidden": true }"""); - - Assert.False(result.IsValid); - Assert.Contains("[R-1] forbidden", CollectErrors(result)); - } - - [Fact] - public void Rule_id_and_assert_id_both_prefix_rule_first() - { - var result = Evaluate( - """ - { - "rules": [ - { - "id": "orders", - "context": ".items[]", - "asserts": [ - { "id": "qty-pos", "test": ".qty > 0", "message": "qty must be positive" } - ] - } - ] - } - """, - """{ "items": [ { "qty": -1 } ] }"""); - - Assert.False(result.IsValid); - Assert.Contains("[orders][qty-pos] qty must be positive", CollectErrors(result)); - } - - [Fact] - public void Flag_prefixes_message_without_id() - { - var result = Evaluate( - """ - { - "type": "object", - "assert": { - "flag": "warning", - "test": ".value > 0", - "message": "value should be positive" - } - } - """, - """{ "value": -1 }"""); - - Assert.False(result.IsValid); - Assert.Contains("[flag=warning] value should be positive", CollectErrors(result)); - } - - [Fact] - public void Flag_prefixes_after_id() - { - var result = Evaluate( - """ - { - "type": "object", - "assert": { - "id": "A-1", - "flag": "error", - "test": ".value > 0", - "message": "value must be positive" - } - } - """, - """{ "value": -1 }"""); - - Assert.False(result.IsValid); - Assert.Contains("[A-1][flag=error] value must be positive", CollectErrors(result)); - } - - [Fact] - public void Role_alias_produces_same_output_as_flag() - { - var withFlag = Evaluate( - """ - { - "type": "object", - "assert": { - "flag": "warning", - "test": ".value > 0", - "message": "msg" - } - } - """, - """{ "value": -1 }"""); - - var withRole = Evaluate( - """ - { - "type": "object", - "assert": { - "role": "warning", - "test": ".value > 0", - "message": "msg" - } - } - """, - """{ "value": -1 }"""); - - Assert.False(withFlag.IsValid); - Assert.False(withRole.IsValid); - Assert.Equal(CollectErrors(withFlag), CollectErrors(withRole)); - Assert.Contains("[flag=warning] msg", CollectErrors(withRole)); - } - - [Fact] - public void Flag_and_role_on_same_entry_rejects_at_build() - { - Assert.ThrowsAny(() => Schema( - """ - { - "type": "object", - "assert": { - "flag": "warning", - "role": "warning", - "test": ".value > 0", - "message": "msg" - } - } - """)); - } - - [Fact] - public void Empty_id_rejects_at_build() - { - Assert.ThrowsAny(() => Schema( - """ - { - "type": "object", - "assert": { - "id": " ", - "test": ".value > 0" - } - } - """)); - } - - [Fact] - public void String_sugar_still_works_unchanged() - { - var result = Evaluate( - """ - { - "type": "object", - "assert": ".value > 0" - } - """, - """{ "value": -1 }"""); - - Assert.False(result.IsValid); - var errors = CollectErrors(result); - Assert.DoesNotContain("[", errors); - } - - [Fact] - public void Top_level_assert_sugar_object_form_carries_id() - { - var result = Evaluate( - """ - { - "type": "object", - "assert": { - "id": "top-a", - "test": ".ok == true", - "message": "not ok" - } - } - """, - """{ "ok": false }"""); - - Assert.False(result.IsValid); - Assert.Contains("[top-a] not ok", CollectErrors(result)); - } - - [Fact] - public void Top_level_report_sugar_object_form_carries_id() - { - var result = Evaluate( - """ - { - "type": "object", - "report": { - "id": "top-r", - "test": ".forbidden == true", - "message": "forbidden" - } - } - """, - """{ "forbidden": true }"""); - - Assert.False(result.IsValid); - Assert.Contains("[top-r] forbidden", CollectErrors(result)); - } - - [Fact] - public void Rule_assert_item_flag_prefixes_message() - { - var result = Evaluate( - """ - { - "rules": [ - { - "context": ".items[]", - "asserts": [ - { "flag": "warning", "test": ".qty > 0", "message": "qty low" } - ] - } - ] - } - """, - """{ "items": [ { "qty": -1 } ] }"""); - - Assert.False(result.IsValid); - Assert.Contains("[flag=warning] qty low", CollectErrors(result)); - } - - [Fact] - public void Rule_report_item_id_and_flag_prefix_message() - { - var result = Evaluate( - """ - { - "rules": [ - { - "id": "rule-x", - "context": ".items[]", - "reports": [ - { "id": "neg", "role": "error", "test": ".qty < 0", "message": "negative qty" } - ] - } - ] - } - """, - """{ "items": [ { "qty": -1 } ] }"""); - - Assert.False(result.IsValid); - Assert.Contains("[rule-x][neg][flag=error] negative qty", CollectErrors(result)); - } - - [Fact] - public void Flag_and_role_on_rule_item_rejects_at_build() - { - Assert.ThrowsAny(() => Schema( - """ - { - "rules": [ - { - "context": ".", - "asserts": [ - { "flag": "warning", "role": "warning", "test": ".ok == true" } - ] - } - ] - } - """)); - } -} diff --git a/tests/applicators.json b/tests/applicators.json new file mode 100644 index 0000000..6e1960d --- /dev/null +++ b/tests/applicators.json @@ -0,0 +1,234 @@ +[ + { + "description": "assert inside if selects the branch", + "schema": { + "if": { + "assert": ".kind == \"a\"" + }, + "then": { + "required": [ + "x" + ] + }, + "else": { + "required": [ + "y" + ] + } + }, + "tests": [ + { + "description": "kind a with x", + "data": { + "kind": "a", + "x": 1 + }, + "valid": true + }, + { + "description": "kind a without x", + "data": { + "kind": "a", + "y": 1 + }, + "valid": false + }, + { + "description": "kind b with y", + "data": { + "kind": "b", + "y": 1 + }, + "valid": true + }, + { + "description": "kind b without y", + "data": { + "kind": "b", + "x": 1 + }, + "valid": false + } + ] + }, + { + "description": "assert under not", + "schema": { + "not": { + "assert": ".locked == true" + } + }, + "tests": [ + { + "description": "not locked", + "data": { + "locked": false + }, + "valid": true + }, + { + "description": "locked", + "data": { + "locked": true + }, + "valid": false + } + ] + }, + { + "description": "assert in anyOf branches", + "schema": { + "anyOf": [ + { + "assert": ".a > 0" + }, + { + "assert": ".b > 0" + } + ] + }, + "tests": [ + { + "description": "first holds", + "data": { + "a": 1, + "b": 0 + }, + "valid": true + }, + { + "description": "second holds", + "data": { + "a": 0, + "b": 1 + }, + "valid": true + }, + { + "description": "neither holds", + "data": { + "a": 0, + "b": 0 + }, + "valid": false + } + ] + }, + { + "description": "assert in oneOf branches", + "schema": { + "oneOf": [ + { + "assert": ".a > 0" + }, + { + "assert": ".b > 0" + } + ] + }, + "tests": [ + { + "description": "exactly one holds", + "data": { + "a": 1, + "b": 0 + }, + "valid": true + }, + { + "description": "both hold", + "data": { + "a": 1, + "b": 1 + }, + "valid": false + }, + { + "description": "neither holds", + "data": { + "a": 0, + "b": 0 + }, + "valid": false + } + ] + }, + { + "description": "assert in allOf branches reports each failure", + "schema": { + "allOf": [ + { + "assert": { + "test": ".a > 0", + "message": "a must be positive" + } + }, + { + "assert": { + "test": ".b > 0", + "message": "b must be positive" + } + } + ] + }, + "tests": [ + { + "description": "both hold", + "data": { + "a": 1, + "b": 1 + }, + "valid": true + }, + { + "description": "both fail", + "data": { + "a": 0, + "b": 0 + }, + "valid": false, + "errors": [ + "a must be positive", + "b must be positive" + ] + } + ] + }, + { + "description": "rules combine with standard keywords", + "schema": { + "type": "object", + "required": [ + "a" + ], + "assert": { + "test": ".a != 13", + "message": "a must not be 13" + } + }, + "tests": [ + { + "description": "valid", + "data": { + "a": 1 + }, + "valid": true + }, + { + "description": "rule fails", + "data": { + "a": 13 + }, + "valid": false, + "errors": [ + "a must not be 13" + ] + }, + { + "description": "standard keyword fails", + "data": {}, + "valid": false + } + ] + } +] diff --git a/tests/assert.json b/tests/assert.json new file mode 100644 index 0000000..08e7102 --- /dev/null +++ b/tests/assert.json @@ -0,0 +1,185 @@ +[ + { + "description": "string form: the message is the expression text", + "schema": { + "assert": ".age >= 18" + }, + "tests": [ + { + "description": "adult", + "data": { + "age": 30 + }, + "valid": true + }, + { + "description": "minor", + "data": { + "age": 10 + }, + "valid": false, + "errors": [ + ".age >= 18" + ] + } + ] + }, + { + "description": "object form with message", + "schema": { + "assert": { + "test": ".status != \"approved\" or .approver != null", + "message": "Approved documents require an approver" + } + }, + "tests": [ + { + "description": "draft", + "data": { + "status": "draft" + }, + "valid": true + }, + { + "description": "approved with approver", + "data": { + "status": "approved", + "approver": "ann" + }, + "valid": true + }, + { + "description": "approved without approver", + "data": { + "status": "approved" + }, + "valid": false, + "errors": [ + "Approved documents require an approver" + ] + } + ] + }, + { + "description": "object form without message uses the test text", + "schema": { + "assert": { + "test": ".a == 1" + } + }, + "tests": [ + { + "description": "fails", + "data": { + "a": 2 + }, + "valid": false, + "errors": [ + ".a == 1" + ] + } + ] + }, + { + "description": "array form mixes strings and objects", + "schema": { + "assert": [ + ".a > 0", + { + "test": ".b > 0", + "message": "b must be positive" + } + ] + }, + "tests": [ + { + "description": "both hold", + "data": { + "a": 1, + "b": 1 + }, + "valid": true + }, + { + "description": "both fail", + "data": { + "a": 0, + "b": 0 + }, + "valid": false, + "errors": [ + ".a > 0", + "b must be positive" + ] + }, + { + "description": "second fails", + "data": { + "a": 1, + "b": 0 + }, + "valid": false, + "errors": [ + "b must be positive" + ] + } + ] + }, + { + "description": "assert applies to non-object instances", + "schema": { + "assert": { + "test": ". % 2 == 0", + "message": "must be even" + } + }, + "tests": [ + { + "description": "even", + "data": 4, + "valid": true + }, + { + "description": "odd", + "data": 3, + "valid": false, + "errors": [ + "must be even" + ] + } + ] + }, + { + "description": "without message, the failure text is the literal test text", + "schema": { + "assert": [ + "\"\\(.a)\" == \"x\"", + { + "test": ".s == \"say \\\"hi\\\"\"" + } + ] + }, + "tests": [ + { + "description": "both hold", + "data": { + "a": "x", + "s": "say \"hi\"" + }, + "valid": true + }, + { + "description": "both fail: no interpolation, no evaluation", + "data": { + "a": "y", + "s": "" + }, + "valid": false, + "errors": [ + "\"\\(.a)\" == \"x\"", + ".s == \"say \\\"hi\\\"\"" + ] + } + ] + } +] diff --git a/tests/build-errors.json b/tests/build-errors.json new file mode 100644 index 0000000..4155a5b --- /dev/null +++ b/tests/build-errors.json @@ -0,0 +1,351 @@ +[ + { + "description": "invalid jq in assert", + "schema": { + "assert": ".a |" + }, + "buildError": true + }, + { + "description": "invalid jq in report", + "schema": { + "report": ".a ==" + }, + "buildError": true + }, + { + "description": "invalid jq in context", + "schema": { + "rules": [ + { + "context": ".[", + "asserts": [ + { + "test": "true" + } + ] + } + ] + }, + "buildError": true + }, + { + "description": "invalid jq in a rule test", + "schema": { + "rules": [ + { + "context": ".", + "asserts": [ + { + "test": "if . then" + } + ] + } + ] + }, + "buildError": true + }, + { + "description": "invalid jq in a message expression", + "schema": { + "assert": { + "test": "true", + "message": "\"unterminated \\(.a" + } + }, + "buildError": true + }, + { + "description": "invalid jq in schema-level let", + "schema": { + "let": { + "x": ".a |" + }, + "assert": "true" + }, + "buildError": true + }, + { + "description": "invalid jq in let without other keywords", + "schema": { + "let": { + "x": ".a |" + } + }, + "buildError": true + }, + { + "description": "invalid jq in rule-level let", + "schema": { + "rules": [ + { + "context": ".", + "let": { + "x": "(" + }, + "asserts": [ + { + "test": "true" + } + ] + } + ] + }, + "buildError": true + }, + { + "description": "an expression must be valid on its own", + "schema": { + "assert": "true) , (false" + }, + "buildError": true + }, + { + "description": "unknown function in assert", + "schema": { + "assert": "no_such_function" + }, + "buildError": true + }, + { + "description": "assert must be a string, object or array", + "schema": { + "assert": 5 + }, + "buildError": true + }, + { + "description": "assert string must not be empty", + "schema": { + "assert": "" + }, + "buildError": true + }, + { + "description": "assert array must not be empty", + "schema": { + "assert": [] + }, + "buildError": true + }, + { + "description": "assert object requires test", + "schema": { + "assert": { + "message": "m" + } + }, + "buildError": true + }, + { + "description": "assert message must be a string", + "schema": { + "assert": { + "test": "true", + "message": 5 + } + }, + "buildError": true + }, + { + "description": "rules must be an array", + "schema": { + "rules": { + "context": "." + } + }, + "buildError": true + }, + { + "description": "rules must not be empty", + "schema": { + "rules": [] + }, + "buildError": true + }, + { + "description": "a rule requires context", + "schema": { + "rules": [ + { + "asserts": [ + { + "test": "true" + } + ] + } + ] + }, + "buildError": true + }, + { + "description": "a rule requires asserts or reports", + "schema": { + "rules": [ + { + "context": "." + } + ] + }, + "buildError": true + }, + { + "description": "rule asserts must not be empty", + "schema": { + "rules": [ + { + "context": ".", + "asserts": [] + } + ] + }, + "buildError": true + }, + { + "description": "rule assert items must be objects", + "schema": { + "rules": [ + { + "context": ".", + "asserts": [ + "true" + ] + } + ] + }, + "buildError": true + }, + { + "description": "flag and role are mutually exclusive", + "schema": { + "assert": { + "test": "true", + "flag": "a", + "role": "b" + } + }, + "buildError": true + }, + { + "description": "id must not be empty", + "schema": { + "assert": { + "test": "true", + "id": "" + } + }, + "buildError": true + }, + { + "description": "let must be an object", + "schema": { + "let": [ + "a" + ], + "assert": "true" + }, + "buildError": true + }, + { + "description": "let must not be empty", + "schema": { + "let": {}, + "assert": "true" + }, + "buildError": true + }, + { + "description": "let cannot bind root", + "schema": { + "let": { + "root": "1" + }, + "assert": "true" + }, + "buildError": true + }, + { + "description": "let names must be identifiers", + "schema": { + "let": { + "my-var": "1" + }, + "assert": "true" + }, + "buildError": true + }, + { + "description": "let values must be strings", + "schema": { + "let": { + "x": 1 + }, + "assert": "true" + }, + "buildError": true + }, + { + "description": "report must be a string, object or array", + "schema": { + "report": 42 + }, + "buildError": true + }, + { + "description": "id must not be blank", + "schema": { + "assert": { + "test": "true", + "id": " " + } + }, + "buildError": true + }, + { + "description": "flag and role are mutually exclusive on a rule item", + "schema": { + "rules": [ + { + "context": ".", + "asserts": [ + { + "test": "true", + "flag": "a", + "role": "b" + } + ] + } + ] + }, + "buildError": true + }, + { + "description": "let names cannot start with a digit", + "schema": { + "let": { + "1bad": "." + }, + "assert": "true" + }, + "buildError": true + }, + { + "description": "rule-level let cannot bind root", + "schema": { + "rules": [ + { + "context": ".", + "let": { + "root": "." + }, + "asserts": [ + { + "test": "true" + } + ] + } + ] + }, + "buildError": true + } +] diff --git a/tests/evaluation-errors.json b/tests/evaluation-errors.json new file mode 100644 index 0000000..4d5a459 --- /dev/null +++ b/tests/evaluation-errors.json @@ -0,0 +1,218 @@ +[ + { + "description": "a jq error in a test fails the rule set", + "schema": { + "assert": { + "test": ".a.b == 1", + "message": "never shown" + } + }, + "tests": [ + { + "description": "indexing a string with a key is an error", + "data": { + "a": "text" + }, + "valid": false + }, + { + "description": "no error", + "data": { + "a": { + "b": 1 + } + }, + "valid": true + } + ] + }, + { + "description": "a jq error in a context fails the rule set", + "schema": { + "rules": [ + { + "context": ".items[]", + "asserts": [ + { + "test": "true" + } + ] + } + ] + }, + "tests": [ + { + "description": "iterating a number is an error", + "data": { + "items": 5 + }, + "valid": false + }, + { + "description": "no error", + "data": { + "items": [ + 1 + ] + }, + "valid": true + } + ] + }, + { + "description": "a jq error in a let fails the rule set", + "schema": { + "let": { + "n": ".a | length" + }, + "assert": "$n >= 0" + }, + "tests": [ + { + "description": "length of a boolean is an error", + "data": { + "a": true + }, + "valid": false + }, + { + "description": "no error", + "data": { + "a": [ + 1 + ] + }, + "valid": true + } + ] + }, + { + "description": "an explicit error call", + "schema": { + "assert": "if .a then true else error(\"a missing\") end" + }, + "tests": [ + { + "description": "raises", + "data": {}, + "valid": false + }, + { + "description": "does not raise", + "data": { + "a": 1 + }, + "valid": true + } + ] + }, + { + "description": "try catches errors inside an expression", + "schema": { + "assert": { + "test": "try (.a.b == 1) catch false", + "message": "caught" + } + }, + "tests": [ + { + "description": "the error becomes a plain failure", + "data": { + "a": "text" + }, + "valid": false, + "errors": [ + "caught" + ] + } + ] + }, + { + "description": "unknown variable is an evaluation error", + "schema": { + "assert": "$nope == 1" + }, + "tests": [ + { + "description": "fails evaluation", + "data": {}, + "valid": false + } + ] + }, + { + "description": "rule-level let is not visible in another rule", + "schema": { + "rules": [ + { + "context": ".", + "let": { + "x": "1" + }, + "asserts": [ + { + "test": "$x == 1" + } + ] + }, + { + "context": ".", + "asserts": [ + { + "test": "$x == 1" + } + ] + } + ] + }, + "tests": [ + { + "description": "second rule fails evaluation", + "data": {}, + "valid": false + } + ] + }, + { + "description": "rule-level let is not visible in context", + "schema": { + "rules": [ + { + "context": "$x", + "let": { + "x": "1" + }, + "asserts": [ + { + "test": "true" + } + ] + } + ] + }, + "tests": [ + { + "description": "context fails evaluation", + "data": {}, + "valid": false + } + ] + }, + { + "description": "a let binding cannot see later bindings", + "schema": { + "let": { + "a": "$b", + "b": "1" + }, + "assert": "true" + }, + "tests": [ + { + "description": "earlier binding fails evaluation", + "data": {}, + "valid": false + } + ] + } +] diff --git a/tests/jq-profile.json b/tests/jq-profile.json new file mode 100644 index 0000000..4637e77 --- /dev/null +++ b/tests/jq-profile.json @@ -0,0 +1,975 @@ +[ + { + "description": "paths and optional iteration", + "schema": { + "assert": { + "test": ".a.b[1] == 2 and ([.missing[]?] | length) == 0 and .[\"a\"].b[-1] == 3", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "a": { + "b": [ + 1, + 2, + 3 + ] + } + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "a": { + "b": [ + 1, + 9, + 3 + ] + } + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "slices", + "schema": { + "assert": { + "test": ".list[1:3] == [2, 3] and (.name[0:2] == \"ab\")", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "list": [ + 1, + 2, + 3, + 4 + ], + "name": "abc" + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "list": [ + 1, + 2, + 4, + 4 + ], + "name": "abc" + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "recursive descent", + "schema": { + "assert": { + "test": "[.. | numbers] | add == 6", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "a": 1, + "b": { + "c": 2, + "d": [ + 3 + ] + } + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "a": 1, + "b": { + "c": 2, + "d": [ + 4 + ] + } + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "alternative operator", + "schema": { + "assert": { + "test": "(.a // 5) == 5", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": {}, + "valid": true + }, + { + "description": "does not hold", + "data": { + "a": 6 + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "arithmetic and comparison", + "schema": { + "assert": { + "test": "(.a + .b) * 2 - 1 == 9 and .a % 2 == 0 and .b / 2 == 1.5 and .a < .b", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "a": 2, + "b": 3 + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "a": 4, + "b": 3 + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "boolean operators", + "schema": { + "assert": { + "test": "(.a and .b) or (.c | not)", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "a": true, + "b": true, + "c": true + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "a": true, + "b": false, + "c": true + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "if elif else", + "schema": { + "assert": { + "test": "if .n < 0 then false elif .n == 0 then false else true end", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "n": 1 + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "n": 0 + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "array and object construction", + "schema": { + "assert": { + "test": "{k: .a, l: [.a, .b]} == {\"k\": 1, \"l\": [1, 2]}", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "a": 1, + "b": 2 + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "a": 1, + "b": 3 + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "string interpolation", + "schema": { + "assert": { + "test": "\"\\(.a)-\\(.b)\" == \"x-1\"", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "a": "x", + "b": 1 + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "a": "y", + "b": 1 + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "variable binding and destructuring", + "schema": { + "assert": { + "test": ". as {a: $a, b: [$first, $second]} | $a + $first + $second == 6", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "a": 1, + "b": [ + 2, + 3 + ] + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "a": 1, + "b": [ + 2, + 4 + ] + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "reduce", + "schema": { + "assert": { + "test": "reduce .list[] as $x (0; . + $x) == 6", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "list": [ + 1, + 2, + 3 + ] + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "list": [ + 1, + 2 + ] + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "foreach", + "schema": { + "assert": { + "test": "[foreach .list[] as $x (0; . + $x)] == [1, 3, 6]", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "list": [ + 1, + 2, + 3 + ] + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "list": [ + 1, + 2, + 4 + ] + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "function definition", + "schema": { + "assert": { + "test": "def double: . * 2; (.n | double) == 4", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "n": 2 + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "n": 3 + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "try catch", + "schema": { + "assert": { + "test": "(try error(\"x\") catch .) == \"x\" and .ok", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "ok": true + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "ok": false + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "length keys has in type", + "schema": { + "assert": { + "test": "(.o | length) == 2 and (.o | keys) == [\"a\", \"b\"] and (.o | has(\"a\")) and (\"b\" | in($root.o)) and (.o | type) == \"object\"", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "o": { + "b": 1, + "a": 2 + } + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "o": { + "b": 1, + "c": 2 + } + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "select map empty", + "schema": { + "assert": { + "test": "[.list[] | select(. > 1)] == [2, 3] and (.list | map(. * 2)) == [2, 4, 6] and ([empty] | length) == 0", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "list": [ + 1, + 2, + 3 + ] + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "list": [ + 1, + 2 + ] + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "entries", + "schema": { + "assert": { + "test": "(.o | to_entries | map(.key)) == [\"a\"] and (.o | with_entries(.value += 1)) == {\"a\": 2} and ([{\"key\": \"k\", \"value\": 1}] | from_entries) == {\"k\": 1} and (.o | map_values(. * 2)) == {\"a\": 2}", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "o": { + "a": 1 + } + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "o": { + "a": 2 + } + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "add any all range", + "schema": { + "assert": { + "test": "(.list | add) == 6 and (.list | any(. > 2)) and (.list | all(. > 0)) and [range(3)] == [0, 1, 2] and [range(1; 3)] == [1, 2]", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "list": [ + 1, + 2, + 3 + ] + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "list": [ + 1, + 2, + 0, + 3 + ] + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "first last limit", + "schema": { + "assert": { + "test": "first(.list[]) == 1 and (.list | first) == 1 and (.list | last) == 3 and [limit(2; .list[])] == [1, 2]", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "list": [ + 1, + 2, + 3 + ] + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "list": [ + 2, + 2, + 3 + ] + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "sorting and grouping", + "schema": { + "assert": { + "test": "(.list | sort) == [1, 2, 3] and (.list | unique) == [1, 2, 3] and (.objs | sort_by(.n) | map(.n)) == [1, 2] and (.objs | group_by(.g) | length) == 1 and (.objs | unique_by(.g) | length) == 1 and (.objs | min_by(.n).n) == 1 and (.objs | max_by(.n).n) == 2 and (.list | min) == 1 and (.list | max) == 3", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "list": [ + 3, + 1, + 2 + ], + "objs": [ + { + "n": 2, + "g": "x" + }, + { + "n": 1, + "g": "x" + } + ] + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "list": [ + 3, + 1, + 4 + ], + "objs": [ + { + "n": 2, + "g": "x" + }, + { + "n": 1, + "g": "x" + } + ] + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "contains inside index", + "schema": { + "assert": { + "test": "(.list | contains([2])) and ([2] | inside($root.list)) and (.list | index(2)) == 1 and (.s | indices(\"a\")) == [0, 2] and (.s | contains(\"ab\"))", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "list": [ + 1, + 2 + ], + "s": "aba" + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "list": [ + 1, + 3 + ], + "s": "aba" + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "IN and INDEX", + "schema": { + "assert": { + "test": "(.x | IN($root.allowed[])) and (INDEX(.objs[]; .id) | keys) == [\"a\", \"b\"]", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "x": 2, + "allowed": [ + 1, + 2 + ], + "objs": [ + { + "id": "a" + }, + { + "id": "b" + } + ] + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "x": 3, + "allowed": [ + 1, + 2 + ], + "objs": [ + { + "id": "a" + }, + { + "id": "b" + } + ] + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "conversions", + "schema": { + "assert": { + "test": "(.n | tostring) == \"5\" and (.s | tonumber) == 7 and (.o | tojson) == \"{\\\"a\\\":1}\" and (\"[1,2]\" | fromjson) == [1, 2]", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "n": 5, + "s": "7", + "o": { + "a": 1 + } + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "n": 6, + "s": "7", + "o": { + "a": 1 + } + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "string functions", + "schema": { + "assert": { + "test": "(.s | startswith(\"He\")) and (.s | endswith(\"lo\")) and (.s | ltrimstr(\"He\")) == \"llo\" and (.s | rtrimstr(\"lo\")) == \"Hel\" and (.s | ascii_downcase) == \"hello\" and (.s | ascii_upcase) == \"HELLO\" and (\"a,b\" | split(\",\")) == [\"a\", \"b\"] and ([\"a\", \"b\"] | join(\"-\")) == \"a-b\" and (.s | length) == 5", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "s": "Hello" + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "s": "Hallo" + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "regular expressions", + "schema": { + "assert": { + "test": "(.s | test(\"^[a-z]+-[0-9]+$\")) and (.s | test(\"ABC\"; \"i\")) and (.s | capture(\"(?[a-z]+)-(?[0-9]+)\")) == {\"word\": \"abc\", \"num\": \"42\"} and (.s | sub(\"-\"; \"_\")) == \"abc_42\" and (.s | gsub(\"[0-9]\"; \"#\")) == \"abc-##\" and (.s | match(\"[0-9]+\").string) == \"42\"", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "s": "abc-42" + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "s": "abd-42" + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "math", + "schema": { + "assert": { + "test": "(.n | floor) == 2 and (.n | ceil) == 3 and (.n | round) == 3 and (16 | sqrt) == 4 and (-.n | abs) == 2.5", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "n": 2.5 + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "n": 3.5 + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "paths getpath flatten reverse", + "schema": { + "assert": { + "test": "[paths] == [[\"a\"], [\"a\", 0], [\"a\", 1]] and getpath([\"a\", 1]) == 2 and ([[1], [2, [3]]] | flatten) == [1, 2, 3] and (.a | reverse) == [2, 1]", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "a": [ + 1, + 2 + ] + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "a": [ + 1, + 3 + ] + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + }, + { + "description": "type selectors", + "schema": { + "assert": { + "test": "[.list[] | numbers] == [1] and [.list[] | strings] == [\"s\"] and [.list[] | nulls] == [null] and [.list[] | booleans] == [true] and [.list[] | arrays] == [[]] and [.list[] | objects] == [{}] and ([.list[] | scalars] | length) == 4 and ([.list[] | values] | length) == 5 and isempty(empty)", + "message": "does not hold" + } + }, + "tests": [ + { + "description": "holds", + "data": { + "list": [ + 1, + "s", + null, + true, + [], + {} + ] + }, + "valid": true + }, + { + "description": "does not hold", + "data": { + "list": [ + 2, + "s", + null, + true, + [], + {} + ] + }, + "valid": false, + "errors": [ + "does not hold" + ] + } + ] + } +] diff --git a/tests/labels.json b/tests/labels.json new file mode 100644 index 0000000..17dc503 --- /dev/null +++ b/tests/labels.json @@ -0,0 +1,257 @@ +[ + { + "description": "rule id, item id and flag prefix the message", + "schema": { + "rules": [ + { + "id": "orders", + "context": ".orders[]", + "asserts": [ + { + "id": "high-value-discount", + "flag": "warning", + "test": ".total <= 1000 or .discount >= 0.1", + "message": "order \\(.id) discount is below policy" + } + ] + } + ] + }, + "tests": [ + { + "description": "passes", + "data": { + "orders": [ + { + "id": "O-1", + "total": 10 + } + ] + }, + "valid": true + }, + { + "description": "full prefix", + "data": { + "orders": [ + { + "id": "O-1", + "total": 5000, + "discount": 0 + } + ] + }, + "valid": false, + "errors": [ + "[orders][high-value-discount][flag=warning] order O-1 discount is below policy" + ] + } + ] + }, + { + "description": "missing labels are omitted", + "schema": { + "rules": [ + { + "id": "r", + "context": ".", + "asserts": [ + { + "test": ".a", + "message": "rule id only" + } + ] + }, + { + "context": ".", + "asserts": [ + { + "id": "i", + "test": ".a", + "message": "item id only" + } + ] + }, + { + "context": ".", + "asserts": [ + { + "flag": "info", + "test": ".a", + "message": "flag only" + } + ] + }, + { + "context": ".", + "asserts": [ + { + "test": ".a", + "message": "no labels" + } + ] + } + ] + }, + "tests": [ + { + "description": "all fail", + "data": {}, + "valid": false, + "errors": [ + "[r] rule id only", + "[i] item id only", + "[flag=info] flag only", + "no labels" + ] + } + ] + }, + { + "description": "role is an alias of flag", + "schema": { + "report": { + "id": "forbidden-flag", + "role": "error", + "test": ".forbidden == true", + "message": "forbidden flag set" + } + }, + "tests": [ + { + "description": "not set", + "data": {}, + "valid": true + }, + { + "description": "set", + "data": { + "forbidden": true + }, + "valid": false, + "errors": [ + "[forbidden-flag][flag=error] forbidden flag set" + ] + } + ] + }, + { + "description": "labels are trimmed", + "schema": { + "rules": [ + { + "id": " r ", + "context": ".", + "asserts": [ + { + "id": " i ", + "flag": " warn ", + "test": ".a", + "message": "m" + } + ] + } + ] + }, + "tests": [ + { + "description": "fails", + "data": {}, + "valid": false, + "errors": [ + "[r][i][flag=warn] m" + ] + } + ] + }, + { + "description": "labels do not change validity", + "schema": { + "assert": { + "id": "x", + "flag": "info", + "test": ".a", + "message": "a required" + } + }, + "tests": [ + { + "description": "an info flag still fails", + "data": {}, + "valid": false, + "errors": [ + "[x][flag=info] a required" + ] + } + ] + }, + { + "description": "an empty message leaves the prefix and its space", + "schema": { + "assert": { + "id": "x", + "test": ".a", + "message": "" + } + }, + "tests": [ + { + "description": "fails", + "data": {}, + "valid": false, + "errors": [ + "[x] " + ] + } + ] + }, + { + "description": "labels on a rule report", + "schema": { + "rules": [ + { + "id": "rule-x", + "context": ".items[]", + "reports": [ + { + "id": "neg", + "role": "error", + "test": ".qty < 0", + "message": "negative qty" + } + ] + } + ] + }, + "tests": [ + { + "description": "no negative qty", + "data": { + "items": [ + { + "qty": 1 + } + ] + }, + "valid": true + }, + { + "description": "negative qty", + "data": { + "items": [ + { + "qty": -1 + }, + { + "qty": 2 + } + ] + }, + "valid": false, + "errors": [ + "[rule-x][neg][flag=error] negative qty" + ] + } + ] + } +] diff --git a/tests/let.json b/tests/let.json new file mode 100644 index 0000000..ef9cf0a --- /dev/null +++ b/tests/let.json @@ -0,0 +1,449 @@ +[ + { + "description": "schema-level let is visible in context, test and message", + "schema": { + "let": { + "cap": ".policy.maxLineItems", + "active": ".customers | map(select(.active)) | map(.id)" + }, + "rules": [ + { + "context": ".orders[] | select(.lines > 0 or $cap > 0)", + "asserts": [ + { + "test": ".customerId | IN($active[])", + "message": "customer \\(.customerId) is not active" + }, + { + "test": ".lines <= $cap", + "message": "order \\(.id) has \\(.lines) lines, over cap \\($cap)" + } + ] + } + ] + }, + "tests": [ + { + "description": "within cap and active", + "data": { + "policy": { + "maxLineItems": 3 + }, + "customers": [ + { + "id": "c1", + "active": true + } + ], + "orders": [ + { + "id": "o1", + "customerId": "c1", + "lines": 2 + } + ] + }, + "valid": true + }, + { + "description": "over cap and inactive", + "data": { + "policy": { + "maxLineItems": 3 + }, + "customers": [ + { + "id": "c1", + "active": false + } + ], + "orders": [ + { + "id": "o1", + "customerId": "c1", + "lines": 9 + } + ] + }, + "valid": false, + "errors": [ + "customer c1 is not active", + "order o1 has 9 lines, over cap 3" + ] + } + ] + }, + { + "description": "later bindings see earlier ones", + "schema": { + "let": { + "a": ".x", + "b": "$a + 1", + "c": "$a + $b" + }, + "assert": { + "test": "$c == 3", + "message": "c is \\($c)" + } + }, + "tests": [ + { + "description": "x = 1", + "data": { + "x": 1 + }, + "valid": true + }, + { + "description": "x = 2", + "data": { + "x": 2 + }, + "valid": false, + "errors": [ + "c is 5" + ] + } + ] + }, + { + "description": "a binding takes the first value, or null for an empty stream", + "schema": { + "let": { + "first": ".list[]", + "none": ".list[] | select(. > 100)" + }, + "assert": [ + { + "test": "$first == 7", + "message": "first is \\($first)" + }, + { + "test": "$none == null", + "message": "none is \\($none)" + } + ] + }, + "tests": [ + { + "description": "first of several", + "data": { + "list": [ + 7, + 8, + 9 + ] + }, + "valid": true + }, + { + "description": "different first", + "data": { + "list": [ + 1, + 7 + ] + }, + "valid": false, + "errors": [ + "first is 1" + ] + }, + { + "description": "a matching value is bound", + "data": { + "list": [ + 7, + 200 + ] + }, + "valid": false, + "errors": [ + "none is 200" + ] + } + ] + }, + { + "description": "rule-level let is evaluated per context node", + "schema": { + "rules": [ + { + "context": ".orders[]", + "let": { + "n": ".lineItems | length" + }, + "asserts": [ + { + "test": "$n <= 2", + "message": "order \\(.id) has \\($n) lines" + } + ] + } + ] + }, + "tests": [ + { + "description": "all within", + "data": { + "orders": [ + { + "id": "a", + "lineItems": [ + 1 + ] + }, + { + "id": "b", + "lineItems": [ + 1, + 2 + ] + } + ] + }, + "valid": true + }, + { + "description": "one over", + "data": { + "orders": [ + { + "id": "a", + "lineItems": [ + 1 + ] + }, + { + "id": "b", + "lineItems": [ + 1, + 2, + 3 + ] + } + ] + }, + "valid": false, + "errors": [ + "order b has 3 lines" + ] + } + ] + }, + { + "description": "rule-level let shadows schema-level let for that rule only", + "schema": { + "let": { + "limit": "10" + }, + "rules": [ + { + "context": ".", + "let": { + "limit": "1" + }, + "asserts": [ + { + "test": ".n <= $limit", + "message": "first rule limit \\($limit)" + } + ] + }, + { + "context": ".", + "asserts": [ + { + "test": ".n <= $limit", + "message": "second rule limit \\($limit)" + } + ] + } + ] + }, + "tests": [ + { + "description": "under both", + "data": { + "n": 1 + }, + "valid": true + }, + { + "description": "over the shadowed limit only", + "data": { + "n": 5 + }, + "valid": false, + "errors": [ + "first rule limit 1" + ] + }, + { + "description": "over both", + "data": { + "n": 50 + }, + "valid": false, + "errors": [ + "first rule limit 1", + "second rule limit 10" + ] + } + ] + }, + { + "description": "rule-level let sees schema-level let and $root", + "schema": { + "let": { + "base": ".base" + }, + "rules": [ + { + "context": ".items[]", + "let": { + "total": ". + $base + $root.extra" + }, + "asserts": [ + { + "test": "$total < 10", + "message": "total \\($total)" + } + ] + } + ] + }, + "tests": [ + { + "description": "under", + "data": { + "base": 1, + "extra": 1, + "items": [ + 1, + 2 + ] + }, + "valid": true + }, + { + "description": "over", + "data": { + "base": 5, + "extra": 4, + "items": [ + 1, + 2 + ] + }, + "valid": false, + "errors": [ + "total 10", + "total 11" + ] + } + ] + }, + { + "description": "let with sugar assert and report", + "schema": { + "let": { + "max": ".max" + }, + "assert": { + "test": ".value <= $max", + "message": "value over \\($max)" + }, + "report": { + "test": ".value < 0", + "message": "value negative" + } + }, + "tests": [ + { + "description": "in range", + "data": { + "max": 5, + "value": 3 + }, + "valid": true + }, + { + "description": "over", + "data": { + "max": 5, + "value": 8 + }, + "valid": false, + "errors": [ + "value over 5" + ] + }, + { + "description": "negative", + "data": { + "max": 5, + "value": -1 + }, + "valid": false, + "errors": [ + "value negative" + ] + } + ] + }, + { + "description": "let alone is never evaluated", + "schema": { + "let": { + "x": "error(\"boom\")" + } + }, + "tests": [ + { + "description": "any instance is valid", + "data": { + "a": 1 + }, + "valid": true + } + ] + }, + { + "description": "let with report sugar alone", + "schema": { + "let": { + "cap": ".limits.max" + }, + "report": { + "test": ".value > $cap", + "message": "value \\(.value) exceeds \\($cap)" + } + }, + "tests": [ + { + "description": "under the cap", + "data": { + "limits": { + "max": 10 + }, + "value": 5 + }, + "valid": true + }, + { + "description": "over the cap", + "data": { + "limits": { + "max": 10 + }, + "value": 15 + }, + "valid": false, + "errors": [ + "value 15 exceeds 10" + ] + } + ] + } +] diff --git a/tests/locations.json b/tests/locations.json new file mode 100644 index 0000000..710ced4 --- /dev/null +++ b/tests/locations.json @@ -0,0 +1,257 @@ +[ + { + "description": "under properties and items, . is the nested value and $root the document", + "schema": { + "type": "object", + "properties": { + "shipments": { + "type": "array", + "items": { + "type": "object", + "assert": { + "test": ".method != \"air\" or .weightKg <= $root.limits.maxAirKg", + "message": "Air shipment \\(.id // \"?\") exceeds max air weight" + } + } + } + } + }, + "tests": [ + { + "description": "within limit", + "data": { + "limits": { + "maxAirKg": 10 + }, + "shipments": [ + { + "id": "s1", + "method": "air", + "weightKg": 5 + }, + { + "id": "s2", + "method": "sea", + "weightKg": 500 + } + ] + }, + "valid": true + }, + { + "description": "two over limit, one without id", + "data": { + "limits": { + "maxAirKg": 10 + }, + "shipments": [ + { + "id": "s1", + "method": "air", + "weightKg": 50 + }, + { + "method": "air", + "weightKg": 11 + } + ] + }, + "valid": false, + "errors": [ + "Air shipment s1 exceeds max air weight", + "Air shipment ? exceeds max air weight" + ] + } + ] + }, + { + "description": "rule sets at several schema locations all run", + "schema": { + "assert": { + "test": ".a.n < 10", + "message": "root: n too big" + }, + "properties": { + "a": { + "assert": { + "test": ".n > 0", + "message": "nested: n must be positive" + } + } + } + }, + "tests": [ + { + "description": "valid", + "data": { + "a": { + "n": 5 + } + }, + "valid": true + }, + { + "description": "nested fails", + "data": { + "a": { + "n": 0 + } + }, + "valid": false, + "errors": [ + "nested: n must be positive" + ] + }, + { + "description": "root fails", + "data": { + "a": { + "n": 50 + } + }, + "valid": false, + "errors": [ + "root: n too big" + ] + } + ] + }, + { + "description": "schema-level let is scoped to its schema object", + "schema": { + "let": { + "x": "1" + }, + "assert": "$x == 1", + "properties": { + "child": { + "let": { + "x": "2" + }, + "assert": { + "test": "$x == 2 and . == \"c\"", + "message": "child x is \\($x)" + } + } + } + }, + "tests": [ + { + "description": "valid", + "data": { + "child": "c" + }, + "valid": true + }, + { + "description": "child fails with its own binding", + "data": { + "child": "d" + }, + "valid": false, + "errors": [ + "child x is 2" + ] + } + ] + }, + { + "description": "through $ref, . is the referencing instance and $root the document", + "schema": { + "$defs": { + "money": { + "type": "object", + "assert": { + "test": ".currency == $root.currency", + "message": "currency \\(.currency) differs from \\($root.currency)" + } + } + }, + "properties": { + "price": { + "$ref": "#/$defs/money" + }, + "tax": { + "$ref": "#/$defs/money" + } + } + }, + "tests": [ + { + "description": "same currency", + "data": { + "currency": "USD", + "price": { + "currency": "USD" + }, + "tax": { + "currency": "USD" + } + }, + "valid": true + }, + { + "description": "tax differs", + "data": { + "currency": "USD", + "price": { + "currency": "USD" + }, + "tax": { + "currency": "EUR" + } + }, + "valid": false, + "errors": [ + "currency EUR differs from USD" + ] + } + ] + }, + { + "description": "the root of a nested array item is still the document", + "schema": { + "items": { + "items": { + "report": { + "test": ". > $root[0][0]", + "message": "\\(.) is above the first cell" + } + } + } + }, + "tests": [ + { + "description": "all at or below", + "data": [ + [ + 5, + 1 + ], + [ + 2, + 5 + ] + ], + "valid": true + }, + { + "description": "one above", + "data": [ + [ + 5, + 1 + ], + [ + 9, + 5 + ] + ], + "valid": false, + "errors": [ + "9 is above the first cell" + ] + } + ] + } +] diff --git a/tests/merge.json b/tests/merge.json new file mode 100644 index 0000000..6b72e13 --- /dev/null +++ b/tests/merge.json @@ -0,0 +1,264 @@ +[ + { + "description": "assert sugar merges into the existing context \".\" rule", + "schema": { + "rules": [ + { + "id": "root", + "context": ".", + "asserts": [ + { + "test": ".a", + "message": "a required" + } + ] + } + ], + "assert": { + "test": ".b", + "message": "b required" + } + }, + "tests": [ + { + "description": "both hold", + "data": { + "a": 1, + "b": 1 + }, + "valid": true + }, + { + "description": "the merged assert carries the rule id", + "data": { + "a": 1 + }, + "valid": false, + "errors": [ + "[root] b required" + ] + }, + { + "description": "both fail, rule asserts first", + "data": {}, + "valid": false, + "errors": [ + "[root] a required", + "[root] b required" + ] + } + ] + }, + { + "description": "sugar creates a context \".\" rule when none exists", + "schema": { + "rules": [ + { + "id": "items", + "context": ".items[]", + "asserts": [ + { + "test": ". > 0", + "message": "item must be positive" + } + ] + } + ], + "assert": { + "test": ".items | length > 0", + "message": "items required" + }, + "report": { + "test": ".locked", + "message": "locked" + } + }, + "tests": [ + { + "description": "all hold", + "data": { + "items": [ + 1 + ] + }, + "valid": true + }, + { + "description": "the created rule has no id", + "data": { + "items": [], + "locked": true + }, + "valid": false, + "errors": [ + "items required", + "locked" + ] + }, + { + "description": "rule and sugar fail", + "data": { + "items": [ + -1 + ], + "locked": true + }, + "valid": false, + "errors": [ + "[items] item must be positive", + "locked" + ] + } + ] + }, + { + "description": "assert and report sugar without rules form one rule", + "schema": { + "assert": { + "test": ".a", + "message": "a required" + }, + "report": { + "test": ".b", + "message": "b forbidden" + } + }, + "tests": [ + { + "description": "valid", + "data": { + "a": 1 + }, + "valid": true + }, + { + "description": "both fail", + "data": { + "b": 1 + }, + "valid": false, + "errors": [ + "a required", + "b forbidden" + ] + } + ] + }, + { + "description": "only a context that is exactly \".\" receives the sugar", + "schema": { + "rules": [ + { + "id": "spaced", + "context": " . ", + "asserts": [ + { + "test": ".a", + "message": "a required" + } + ] + } + ], + "assert": { + "test": ".b", + "message": "b required" + } + }, + "tests": [ + { + "description": "sugar goes to a new rule without the id", + "data": {}, + "valid": false, + "errors": [ + "[spaced] a required", + "b required" + ] + } + ] + }, + { + "description": "merged sugar sees the rule-level let of the rule it joins", + "schema": { + "rules": [ + { + "context": ".", + "let": { + "n": ".n" + }, + "asserts": [ + { + "test": "$n > 0", + "message": "n positive" + } + ] + } + ], + "assert": { + "test": "$n < 10", + "message": "n is \\($n), must be under 10" + } + }, + "tests": [ + { + "description": "in range", + "data": { + "n": 5 + }, + "valid": true + }, + { + "description": "over", + "data": { + "n": 50 + }, + "valid": false, + "errors": [ + "n is 50, must be under 10" + ] + } + ] + }, + { + "description": "report sugar merges into the existing context \".\" rule", + "schema": { + "rules": [ + { + "id": "root", + "context": ".", + "asserts": [ + { + "test": ".value > 0", + "message": "value must be positive" + } + ] + } + ], + "report": { + "test": ".forbidden == true", + "message": "forbidden" + } + }, + "tests": [ + { + "description": "both hold", + "data": { + "value": 1, + "forbidden": false + }, + "valid": true + }, + { + "description": "both fail, the report joins the rule and takes its id", + "data": { + "value": -1, + "forbidden": true + }, + "valid": false, + "errors": [ + "[root] value must be positive", + "[root] forbidden" + ] + } + ] + } +] diff --git a/tests/messages.json b/tests/messages.json new file mode 100644 index 0000000..a28be5a --- /dev/null +++ b/tests/messages.json @@ -0,0 +1,311 @@ +[ + { + "description": "plain text is wrapped as a jq string", + "schema": { + "assert": { + "test": ".a", + "message": "Discount too low" + } + }, + "tests": [ + { + "description": "fails", + "data": {}, + "valid": false, + "errors": [ + "Discount too low" + ] + } + ] + }, + { + "description": "interpolation works in plain text", + "schema": { + "assert": { + "test": ".qty <= .cap", + "message": "Line \\(.sku): qty \\(.qty) exceeds cap \\(.cap)" + } + }, + "tests": [ + { + "description": "fails", + "data": { + "sku": "A1", + "qty": 5, + "cap": 2 + }, + "valid": false, + "errors": [ + "Line A1: qty 5 exceeds cap 2" + ] + } + ] + }, + { + "description": "double quotes inside plain text are kept", + "schema": { + "assert": { + "test": ".a", + "message": "field \"a\" is required" + } + }, + "tests": [ + { + "description": "fails", + "data": {}, + "valid": false, + "errors": [ + "field \"a\" is required" + ] + } + ] + }, + { + "description": "newline and tab in plain text are kept", + "schema": { + "assert": { + "test": ".a", + "message": "line one\nline two\tend" + } + }, + "tests": [ + { + "description": "fails", + "data": {}, + "valid": false, + "errors": [ + "line one\nline two\tend" + ] + } + ] + }, + { + "description": "a message starting with a quote is a jq expression", + "schema": { + "assert": { + "test": ".a", + "message": "\"got \" + (.b | tostring)" + } + }, + "tests": [ + { + "description": "fails", + "data": { + "b": 7 + }, + "valid": false, + "errors": [ + "got 7" + ] + } + ] + }, + { + "description": "leading whitespace before the quote is ignored", + "schema": { + "assert": { + "test": ".a", + "message": " \"x\" + \"y\"" + } + }, + "tests": [ + { + "description": "fails", + "data": {}, + "valid": false, + "errors": [ + "xy" + ] + } + ] + }, + { + "description": "non-string message results", + "schema": { + "assert": [ + { + "test": ".a", + "message": "\"\" | null" + }, + { + "test": ".a", + "message": "\"\" | {k: 1}" + }, + { + "test": ".a", + "message": "\"\" | [1, 2]" + }, + { + "test": ".a", + "message": "\"\" | 42" + }, + { + "test": ".a", + "message": "\"\" | true" + } + ] + }, + "tests": [ + { + "description": "null is empty, others are JSON text", + "data": {}, + "valid": false, + "errors": [ + "", + "{\"k\":1}", + "[1,2]", + "42", + "true" + ] + } + ] + }, + { + "description": "a message that fails or yields nothing is empty", + "schema": { + "assert": [ + { + "test": ".a", + "message": "\"x\" | error" + }, + { + "test": ".a", + "message": "\"x\" | empty" + } + ] + }, + "tests": [ + { + "description": "two empty messages", + "data": {}, + "valid": false, + "errors": [ + "", + "" + ] + } + ] + }, + { + "description": "only the first message value is used", + "schema": { + "assert": { + "test": ".a", + "message": "\"one\", \"two\"" + } + }, + "tests": [ + { + "description": "fails", + "data": {}, + "valid": false, + "errors": [ + "one" + ] + } + ] + }, + { + "description": "the message sees let bindings and $root", + "schema": { + "properties": { + "item": { + "let": { + "who": ".owner" + }, + "assert": { + "test": ".ok", + "message": "\\($who) / \\($root.name)" + } + } + } + }, + "tests": [ + { + "description": "fails", + "data": { + "name": "doc", + "item": { + "owner": "ann" + } + }, + "valid": false, + "errors": [ + "ann / doc" + ] + }, + { + "description": "passes", + "data": { + "name": "doc", + "item": { + "owner": "ann", + "ok": true + } + }, + "valid": true + } + ] + }, + { + "description": "quotes inside an interpolation are not escaped", + "schema": { + "assert": { + "test": ".ok", + "message": "order \\(.id // \"?\") has \"\\(.n | tostring + \"!\")\" lines" + } + }, + "tests": [ + { + "description": "fails", + "data": { + "n": 3 + }, + "valid": false, + "errors": [ + "order ? has \"3!\" lines" + ] + } + ] + }, + { + "description": "a parenthesis in a string inside an interpolation does not end it", + "schema": { + "assert": { + "test": ".ok", + "message": "v=\\(.s | ltrimstr(\"(\") | rtrimstr(\")\")) \"end\"" + } + }, + "tests": [ + { + "description": "fails", + "data": { + "s": "(x)" + }, + "valid": false, + "errors": [ + "v=x \"end\"" + ] + } + ] + }, + { + "description": "a backslash in plain text keeps the character after it", + "schema": { + "assert": { + "test": ".ok", + "message": "say \\\"hi\\\" \\\\ done" + } + }, + "tests": [ + { + "description": "fails", + "data": {}, + "valid": false, + "errors": [ + "say \"hi\" \\ done" + ] + } + ] + } +] diff --git a/tests/readme.md b/tests/readme.md new file mode 100644 index 0000000..db4610a --- /dev/null +++ b/tests/readme.md @@ -0,0 +1,48 @@ +# Jsontron conformance suite + +These files are the executable form of the [specification](../spec/jsontron.md). Every +implementation in this repository runs all of them; an implementation conforms when all pass. + +## Format + +Each `*.json` file (except `schema.json`, which describes the format) is an array of groups: + +```json +[ + { + "description": "report fails when the test is truthy", + "schema": { "report": { "test": ".total < 0", "message": "negative total" } }, + "tests": [ + { "description": "positive total", "data": { "total": 5 }, "valid": true }, + { "description": "negative total", "data": { "total": -1 }, "valid": false, + "errors": [ "negative total" ] } + ] + }, + { "description": "invalid jq in assert", "schema": { "assert": ".a |" }, "buildError": true } +] +``` + +- `schema` is a JSON Schema (draft 2020-12) using the Jsontron keywords. +- A group with `buildError: true` passes when compiling the schema fails. +- Otherwise the schema must compile, and for each test `data` must validate as `valid` says. +- `errors`, when present, is the list of failure texts of the Jsontron keywords (`rules`, + `assert`, `report`) for that instance. A runner collects the messages of the validation + errors those keywords raised, at any schema location, and compares the two lists **sorted**: + the order in which a host visits schema locations is not part of the contract. Errors of + standard keywords are ignored. +- A test that is invalid without `errors` checks validity only: the failure comes from an + evaluation error, whose text is not normative, or from a standard keyword. + +## Running + +| Implementation | Command | +|----------------|---------| +| .NET | `dnx --yes retest` at the repository root | +| JavaScript | `npm test` in `js/` | +| Python | `pytest` in `python/` | + +## Adding cases + +Add the group to the file of its area, or a new file: runners pick up every `*.json` here. +A case must follow from the specification; when it shows the specification is silent or +ambiguous, change the specification in the same commit. diff --git a/tests/report.json b/tests/report.json new file mode 100644 index 0000000..492d2a1 --- /dev/null +++ b/tests/report.json @@ -0,0 +1,189 @@ +[ + { + "description": "report fails when the test is truthy", + "schema": { + "report": { + "test": ".total < 0", + "message": "negative total" + } + }, + "tests": [ + { + "description": "positive total", + "data": { + "total": 5 + }, + "valid": true + }, + { + "description": "negative total", + "data": { + "total": -1 + }, + "valid": false, + "errors": [ + "negative total" + ] + } + ] + }, + { + "description": "string form: the message is the expression text", + "schema": { + "report": ".forbidden == true" + }, + "tests": [ + { + "description": "not set", + "data": {}, + "valid": true + }, + { + "description": "set", + "data": { + "forbidden": true + }, + "valid": false, + "errors": [ + ".forbidden == true" + ] + } + ] + }, + { + "description": "a report whose test yields nothing does not fail", + "schema": { + "report": { + "test": ".tags[]", + "message": "has tags" + } + }, + "tests": [ + { + "description": "empty stream", + "data": { + "tags": [] + }, + "valid": true + }, + { + "description": "truthy values", + "data": { + "tags": [ + "a" + ] + }, + "valid": false, + "errors": [ + "has tags" + ] + }, + { + "description": "a false value makes it not truthy", + "data": { + "tags": [ + "a", + false + ] + }, + "valid": true + } + ] + }, + { + "description": "array form", + "schema": { + "report": [ + { + "test": ".a", + "message": "a is set" + }, + { + "test": ".b", + "message": "b is set" + } + ] + }, + "tests": [ + { + "description": "none set", + "data": {}, + "valid": true + }, + { + "description": "both set", + "data": { + "a": 1, + "b": 1 + }, + "valid": false, + "errors": [ + "a is set", + "b is set" + ] + } + ] + }, + { + "description": "regular expression in a report", + "schema": { + "report": { + "test": ".password | test(\"password\"; \"i\")", + "message": "password must not contain the word 'password'" + } + }, + "tests": [ + { + "description": "clean", + "data": { + "password": "s3cret" + }, + "valid": true + }, + { + "description": "contains the word", + "data": { + "password": "myPassword1" + }, + "valid": false, + "errors": [ + "password must not contain the word 'password'" + ] + } + ] + }, + { + "description": "array form mixes strings and objects", + "schema": { + "report": [ + ".a < 0", + { + "test": ".b < 0", + "message": "b must not be negative" + } + ] + }, + "tests": [ + { + "description": "none fires", + "data": { + "a": 1, + "b": 1 + }, + "valid": true + }, + { + "description": "both fire", + "data": { + "a": -1, + "b": -1 + }, + "valid": false, + "errors": [ + ".a < 0", + "b must not be negative" + ] + } + ] + } +] diff --git a/tests/rules.json b/tests/rules.json new file mode 100644 index 0000000..3229229 --- /dev/null +++ b/tests/rules.json @@ -0,0 +1,483 @@ +[ + { + "description": "context selects nodes, asserts run on each, $root is the document", + "schema": { + "type": "object", + "rules": [ + { + "context": ".orders[] | select(.total > 1000)", + "asserts": [ + { + "test": ".discount >= ($root.policy.minHighValueDiscount // 0.1)", + "message": "High-value order \\(.id) discount \\(.discount) is below policy" + }, + { + "test": ".customer.id | IN($root.approvedCustomers[])", + "message": "Customer \\(.customer.id) is not on the approved list" + } + ] + } + ] + }, + "tests": [ + { + "description": "high-value order within policy and approved", + "data": { + "policy": { + "minHighValueDiscount": 0.15 + }, + "approvedCustomers": [ + "c1", + "c2" + ], + "orders": [ + { + "id": "O-1", + "total": 1500, + "discount": 0.2, + "customer": { + "id": "c1" + } + }, + { + "id": "O-2", + "total": 50, + "discount": 0, + "customer": { + "id": "unknown" + } + } + ] + }, + "valid": true + }, + { + "description": "discount below policy", + "data": { + "policy": { + "minHighValueDiscount": 0.15 + }, + "approvedCustomers": [ + "c1" + ], + "orders": [ + { + "id": "O-1", + "total": 1500, + "discount": 0.05, + "customer": { + "id": "c1" + } + } + ] + }, + "valid": false, + "errors": [ + "High-value order O-1 discount 0.05 is below policy" + ] + }, + { + "description": "both asserts fail on the same node", + "data": { + "policy": { + "minHighValueDiscount": 0.15 + }, + "approvedCustomers": [ + "acme" + ], + "orders": [ + { + "id": "O-1001", + "total": 2500, + "discount": 0.05, + "customer": { + "id": "initech" + } + } + ] + }, + "valid": false, + "errors": [ + "High-value order O-1001 discount 0.05 is below policy", + "Customer initech is not on the approved list" + ] + }, + { + "description": "policy default applies when missing", + "data": { + "policy": {}, + "approvedCustomers": [ + "c1" + ], + "orders": [ + { + "id": "O-1", + "total": 2000, + "discount": 0.1, + "customer": { + "id": "c1" + } + } + ] + }, + "valid": true + }, + { + "description": "one failure per failing context node", + "data": { + "policy": {}, + "approvedCustomers": [ + "c1" + ], + "orders": [ + { + "id": "A", + "total": 2000, + "discount": 0, + "customer": { + "id": "c1" + } + }, + { + "id": "B", + "total": 3000, + "discount": 0.01, + "customer": { + "id": "c1" + } + } + ] + }, + "valid": false, + "errors": [ + "High-value order A discount 0 is below policy", + "High-value order B discount 0.01 is below policy" + ] + } + ] + }, + { + "description": "a context that matches nothing is vacuously valid", + "schema": { + "rules": [ + { + "context": ".items[]?", + "asserts": [ + { + "test": "false", + "message": "never" + } + ] + } + ] + }, + "tests": [ + { + "description": "no items property", + "data": {}, + "valid": true + }, + { + "description": "empty items", + "data": { + "items": [] + }, + "valid": true + }, + { + "description": "one item", + "data": { + "items": [ + 1 + ] + }, + "valid": false, + "errors": [ + "never" + ] + } + ] + }, + { + "description": "every rule runs, there is no shadowing between rules", + "schema": { + "rules": [ + { + "context": ".", + "asserts": [ + { + "test": ".a == 1", + "message": "a must be 1" + } + ] + }, + { + "context": ".", + "asserts": [ + { + "test": ".b == 2", + "message": "b must be 2" + } + ] + }, + { + "context": ".list[]", + "asserts": [ + { + "test": ". > 0", + "message": "item \\(.) must be positive" + } + ] + } + ] + }, + "tests": [ + { + "description": "all rules pass", + "data": { + "a": 1, + "b": 2, + "list": [ + 1, + 2 + ] + }, + "valid": true + }, + { + "description": "all rules fail", + "data": { + "a": 0, + "b": 0, + "list": [ + -1, + 5, + -2 + ] + }, + "valid": false, + "errors": [ + "a must be 1", + "b must be 2", + "item -1 must be positive", + "item -2 must be positive" + ] + } + ] + }, + { + "description": "truthiness: at least one value and none false or null", + "schema": { + "rules": [ + { + "context": ".", + "asserts": [ + { + "test": ".values[]", + "message": "not truthy" + } + ] + } + ] + }, + "tests": [ + { + "description": "all values truthy", + "data": { + "values": [ + 1, + "a", + true + ] + }, + "valid": true + }, + { + "description": "zero and empty string are truthy in jq", + "data": { + "values": [ + 0, + "" + ] + }, + "valid": true + }, + { + "description": "an empty stream is not truthy", + "data": { + "values": [] + }, + "valid": false, + "errors": [ + "not truthy" + ] + }, + { + "description": "a false among the values", + "data": { + "values": [ + true, + false, + true + ] + }, + "valid": false, + "errors": [ + "not truthy" + ] + }, + { + "description": "a null among the values", + "data": { + "values": [ + 1, + null + ] + }, + "valid": false, + "errors": [ + "not truthy" + ] + } + ] + }, + { + "description": "a rule with reports only", + "schema": { + "rules": [ + { + "context": ".orders[]", + "reports": [ + { + "test": ".total < 0", + "message": "order \\(.id) has negative total" + } + ] + } + ] + }, + "tests": [ + { + "description": "no negative totals", + "data": { + "orders": [ + { + "id": 1, + "total": 5 + } + ] + }, + "valid": true + }, + { + "description": "a negative total", + "data": { + "orders": [ + { + "id": 1, + "total": 5 + }, + { + "id": 2, + "total": -5 + } + ] + }, + "valid": false, + "errors": [ + "order 2 has negative total" + ] + } + ] + }, + { + "description": "asserts are reported before reports within a rule", + "schema": { + "rules": [ + { + "context": ".", + "reports": [ + { + "test": ".bad", + "message": "report failed" + } + ], + "asserts": [ + { + "test": ".good", + "message": "assert failed" + } + ] + } + ] + }, + "tests": [ + { + "description": "both fail", + "data": { + "bad": true, + "good": false + }, + "valid": false, + "errors": [ + "assert failed", + "report failed" + ] + }, + { + "description": "neither fails", + "data": { + "bad": false, + "good": true + }, + "valid": true + } + ] + }, + { + "description": "a trailing comment does not swallow what follows", + "schema": { + "rules": [ + { + "context": ".items[] # each item", + "asserts": [ + { + "test": ". > 0 # positive", + "message": "item must be positive" + }, + { + "test": ". < 10 # small \\", + "message": "item must be under 10" + } + ] + } + ] + }, + "tests": [ + { + "description": "all hold", + "data": { + "items": [ + 1, + 2 + ] + }, + "valid": true + }, + { + "description": "both asserts still run", + "data": { + "items": [ + 0, + 50 + ] + }, + "valid": false, + "errors": [ + "item must be positive", + "item must be under 10" + ] + } + ] + } +] diff --git a/tests/schema.json b/tests/schema.json new file mode 100644 index 0000000..cb55220 --- /dev/null +++ b/tests/schema.json @@ -0,0 +1,81 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Jsontron conformance suite file", + "type": "array", + "items": { + "oneOf": [ + { + "type": "object", + "required": [ + "description", + "schema", + "tests" + ], + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "schema": { + "type": [ + "object", + "boolean" + ] + }, + "tests": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": [ + "description", + "data", + "valid" + ], + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "data": {}, + "valid": { + "type": "boolean" + }, + "errors": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Failure texts of the Jsontron keywords, compared as a sorted list. Only allowed when valid is false." + } + } + } + } + } + }, + { + "type": "object", + "required": [ + "description", + "schema", + "buildError" + ], + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "schema": { + "type": [ + "object", + "boolean" + ] + }, + "buildError": { + "const": true + } + } + } + ] + } +}