diff --git a/.gitignore b/.gitignore index 73d8a43..b50d613 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,6 @@ node_modules/ -docs/ +/docs scratch/ TODO* diff --git a/README.md b/README.md index d819e39..911e969 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,33 @@ -# Hyperjump - Better JSON Schema Errors +# Hyperjump - Better JSON Schema Errors +It transforms standard, machine-oriented validation output into clear, human-friendly error messages ideal for API responses and developer tools. Built upon the official JSON Schema Output Format introduced in draft 2019-09, it ensures seamless compatibility with any compliant validator. -TODO: Write a short description of the package +### Node.js + +```bash +npm install @hyperjump/better-json-schema-errors +``` + +## API Error Message Format + +Our API Error Format includes :- +- **`schemaLocation`** - A URI that points to the specific keyword(s) within the schema that failed validation. This can be a single string or an array of absolute keyword locations for errors that are grouped together. + +- **`instanceLocation`** - JSON Pointer to the invalid piece of input data. + +- **`message`** - Human-friendly explanation of the validation error. + +Example:- +```json +{ + "errors": [ + { + "schemaLocation": "https://example.com/main#/properties/name/minLength", + "instanceLocation": "#/name", + "message": "Expected a string at least 5 characters long." + } + ] +} +``` ## Install @@ -8,16 +35,241 @@ This module is designed for node.js (ES Modules, TypeScript) and browsers. It should work in Bun and Deno as well, but the test runner doesn't work in these environments, so this module may be less stable in those environments. -### Node.js +## Examples and Basic Usage +Better JSON Schema Errors works with **any JSON Schema validator** that follows the official [JSON Schema Output Format](https://json-schema.org/draft/2020-12/json-schema-core#name-output-structure). +In this example, we’ll showcase it with the [Hyperjump JSON Schema Validator](https://github.com/hyperjump-io/json-schema). -```bash -npm install @hyperjump/better-json-schema-errors +Now let's define a schema and some invalid data, then run the validation and process the output with `better-json-schema-errors`. :- +```js +import { registerSchema, validate, unregisterSchema } from "@hyperjump/json-schema/draft-2020-12"; +import { betterJsonSchemaErrors } from "@hyperjump/better-json-schema-errors"; + +const schemaUri = "https://example.com/main"; +registerSchema({ + $schema: "https://json-schema.org/draft/2020-12/schema", + anyOf: [ + { enum: ["a", "b", "c"] } + ] +}, schemaUri); + +const instance = 4; +const result = await validate(schemaUri, instance, "BASIC"); + +if (result.valid) { + console.log("Valid instance!"); +} else { + const friendlyErrors = await betterJsonSchemaErrors(result, schemaUri, instance); + console.log(JSON.stringify(friendlyErrors, null, 2)); +} + +unregisterSchema(schemaUri); + +``` +Output:- +```json +{ + "errors": [ + { + "message": "Unexpected value 4. Expected one of: 'a', 'b', or 'c'.", + "instanceLocation": "#", + "schemaLocation": "https://example.com/main#/enum" + } + ] +} +``` + +## Features and Advanced Usage + +### 1. Works with All Output Formats +Supports all three standardized output formats: +- **BASIC** — The "Basic" structure is a flat list of output units +- **DETAILED** — The "Detailed" structure is based on the schema and can be more readable for both +humans and machines. +- **VERBOSE** — The "Verbose" structure is a fully realised hierarchy that exactly matches that of the +schema. + +No matter which output format your validator produces, Better JSON Schema Errors can process it. + +### 2. Multiple Schema Locations +Sometimes a single validation issue is tied to **more than one schema keyword**. +For example, when both `minimum` and `exclusiveMinimum` apply, or when `minLength` and `maxLength` constraints overlap or when when both `minimum` and `maximum` apply. + +Instead of multiple related error messages, It groups these into an **array of schema locations** and produces one concise, human-friendly message :- + +```json +{ + "schemaLocation": [ + "https://example.com/main#/minimum", + "https://example.com/main#/maximum" + ], + "instanceLocation": "#/age", + "message": "Expected a number greater than 5 and less than 10." +} ``` +### 3. Localization -## Examples and Usage +The library uses [fluent](https://projectfluent.org) `.ftl` files to provide localized error messages. By default, only English is supported. -TODO: Write some examples +We need contributions from different countries to add more languages. +To change the language, pass a language option to the betterJsonSchemaErrors function, like this: + +```js +const friendlyErrors = await betterJsonSchemaErrors(result, schemaUri, instance, { language: "en-US" }); +``` + +### 4. Handling `anyOf`/`oneOf` with Clarity + +The `anyOf`/`oneOf` keyword is a powerful but complex JSON Schema feature. **better-json-schema-errors** intelligently simplifies its output by providing clear, consolidated error messages that are easier to debug. Whenever possible it will try to determine which alternative the user intended and focus the error output to only those errors related to correcting the data for that alternative. + +**Schema:** +```json +{ + "anyOf": [ + { "type": "string", "minLength": 5 }, + { "type": "number" } + ] +} +``` + +Invalid Instance:- +```json +"abc" +``` +BetterJSONSchemaErrors Output:- +```json +{ + "errors": [ + { + "schemaLocation": "https://example.com/main#/anyOf/0/minLength", + "instanceLocation": "#", + "message": "Expected a string at least 5 characters long." + } + ] +} +``` + +For detailed examples, see the dedicated [**anyOf** documentation](./documentation/anyOf.md). + +### 5. Handling `enum` with Suggestions + +When data doesn’t match an allowed `enum` value, Better JSON Schema Errors produces clear messages. +It can also suggest the closest valid value (using string similarity). + +Example: + +```json +{ + "errors": [ + { + "message": "Unexpected value 'appl'. Did you mean 'apple'?", + "instanceLocation": "#/fruit", + "schemaLocation": "https://example.com/main#/properties/fruit/enum" + } + ] +} +``` +This makes typos or near-misses much easier to debug. +For full details and strategies, see the dedicated [enum documentation](./documentation/enum.md). + +### 6. Range constraint keywords +Better JSON Schema Errors consolidates multiple range-related validation errors (`minimum`, `maxLength`, `minItems`, etc.) into a single, clear message. +For example, a schema like: +```json +{ "allOf": [ + { "minimum": 3 }, + { "minimum": 5 } + ] +} +``` +Instance:- +```json +2 +``` +BetterJSONSchemaErrors Output:- +```json +{ + "errors": [ + { + "schemaLocation": "https://example.com/main#/allOf/1/minimum", + "instanceLocation": "#", + "message": "Expected a number greater than 5." + } + ] +} +``` +Instead of 2 error message it manages to give a single concise error message. For details, see the dedicated [Range documenetation](./documentation/range-handler.md) + +### 6. Custom Keywords and Error Handlers +In order to create the custom keywords and error handlers we need to create and +register two types of handlers: **Normalization Handler** and **Error Handlers**. + +1. Normalization: This phase takes the raw, often deeply nested, error output +from the validator and converts it into a NormalizedOutput (you can check type of +normalizedOutput in the index.d.ts file). + +2. Error Handling: This phase takes the normalized output and uses it to generate the final error messages. This is the job of the Error Handlers. + +Fist step -: Creating the keywordHandler +```js +/** + * @import { KeywordHandler } from "@hyperjump/better-json-schema-errors" + */ + +/** @type KeywordHandler */ +const multipleOfTen = { + appliesTo(type) { + return type === "number" + } +}; + +export default multipleOfTen; + +``` + +Second step -: Creating the errorHandler +```js +import { getSchema } from "@hyperjump/json-schema/experimental"; +import * as Schema from "@hyperjump/browser"; +import * as Instance from "@hyperjump/json-schema/instance/experimental"; + +/** + * @import { ErrorHandler, ErrorObject } from "@hyperjump/better-json-schema-errors" + */ + +/** @type ErrorHandler */ +const ErrorHandler = async (normalizedErrors, instance, localization) => { + /** @type ErrorObject[] */ + const errors = []; + + if (normalizedErrors["https://json-schema.org/keyword/multipleOfTen"]) { + for (const schemaLocation in normalizedErrors["https://json-schema.org/keyword/multipleOfTen"]) { + if (!normalizedErrors["https://json-schema.org/keyword/multipleOfTen"][schemaLocation]) { + errors.push({ + message: "Instance must be multiple of 10", + instanceLocation: Instance.uri(instance), + schemaLocation: schemaLocation + }); + } + } + } + + return errors; +}; + + +``` + +Step 3:- Register the handlers: + +```js +import { setNormalizationHandler, addErrorHandler } from "@hyperjump/better-json-schema-errors"; +const KEYWORD_URI = "https://json-schema.org/keyword/multipleOfTen"; + +setNormalizationHandler(KEYWORD_URI, multipleOften); + +addErrorHandler(errorHandler); +``` ## API @@ -29,7 +281,6 @@ changes you'd like to make before implementing it. If it's an obvious bug with an obvious solution or something simple like a fixing a typo, creating an issue isn't required. You can just send a PR without creating an issue. Before submitting any code, please remember to first run the following tests. - - `npm test` (Tests can also be run continuously using `npm test -- --watch`) - `npm run lint` - `npm run type-check` diff --git a/documentation/anyOf.md b/documentation/anyOf.md new file mode 100644 index 0000000..4d5f76a --- /dev/null +++ b/documentation/anyOf.md @@ -0,0 +1,196 @@ +## Handling `anyOf` with Clarity + +`better-json-schema-errors` intelligently simplifies error output, providing clear, consolidated error messages that are easier to debug. +Here are the differnt cases and how better-json-schema-errors handles them to produces better errors. + +--- + +#### 1. Mismatched Types + +If the instance's type doesn't match any of the alternatives in an `anyOf`, the library provides a concise error message listing the expected types. + +**Schema:** +```json +{ + "anyOf": [ + { "type": "string" }, + { "type": "number" } + ] +} +``` + +Invalid Instance:- +```json +false +``` +BetterJSONSchemaErrors Output:- +```json +{ + "errors": [ + { + "schemaLocation": "https://example.com/main#/anyOf", + "instanceLocation": "#", + "message": "The instance should be of type 'string' or 'number' but found 'boolean'." + } + ] +} + +``` +#### 2. Partial Match with a Failed Constraint + +If the instance's type matches one of the `anyOf` alternatives but fails a subsequent constraint (like `minLength`), our library correctly identifies the specific rule that was violated. + +**Schema:** +```json +{ + "anyOf": [ + { "type": "string", "minLength": 5 }, + { "type": "number" } + ] +} +``` + +Invalid Instance:- +```json +"abc" +``` +BetterJSONSchemaErrors Output:- +```json +{ + "errors": [ + { + "schemaLocation": "https://example.com/main#/anyOf/0/minLength", + "instanceLocation": "#", + "message": "Expected a string at least 5 characters long." + } + ] +} + +``` + +#### 3. Multiple types match, pick based on field overlap + +When an instance matches multiple `anyOf` alternatives type, the library prioritizes the one with the most relevant error based on the instance's fields. + +**Schema:** +```json +{ + "anyOf": [ + { + "type": "object", + "properties": { + "name": { "type": "string" }, + "age": { "type": "number" } + }, + "required": ["name", "age"] + }, + { + "type": "object", + "properties": { + "title": { "type": "string" }, + "author": { "type": "string" }, + "ID": { "type": "string", "pattern": "^[0-9\\-]+$" } + }, + "required": ["title", "author", "ID"] + } + ] +} +``` + +Invalid Instance:- +```json +{ + "title": "Clean Code", + "author": "Robert Martin", + "ID": "NotValidId" +} +``` +BetterJSONSchemaErrors Output:- +```json +{ + "errors": [ + { + "schemaLocation": "https://example.com/main#/anyOf/1/properties/ID/pattern", + "instanceLocation": "#/ID", + "message": "The instance should match the format: \"^[0-9\\-]+$\". " + } + ] +} +``` + +#### 4. anyOf handling const/enum + +When an instance fails all enum or const options in an anyOf, the library merges them into one clear error message, avoiding multiple errors and even suggesting close matches in many cases. + +**Schema:** +```json +{ + "anyOf": [ + { "enum": ["a", "b", "c"] }, + { "const": 1 } + ] +} +``` + +Invalid Instance:- +```json +2 +``` +BetterJSONSchemaErrors Output:- +```json +{ + "errors": [ + { + "schemaLocation": "https://example.com/main#/anyOf", + "instanceLocation": "#", + "message": "Unexpected value 2. Expected one of: 'a', 'b', 'c' or 1 ." + } + ] +} + +``` + +#### 5. anyOf with a Discriminator + +When `anyOf` uses a discriminator, the library leverages it to give precise errors, matching the instance to the intended alternative via a specific property (e.g., `"type"`, `"const"`). + + +**Schema:** +```json +{ + "anyOf": [ + { + "properties": { + "type": { "const": "a" }, + "apple": { "type": "string" } + } + }, + { + "properties": { + "type": { "const": "b" }, + "banana": { "type": "string" } + } + } + ] +} +``` + +Invalid Instance:- +```json +{ + "type": "a", + "apple": 42 +} +``` +BetterJSONSchemaErrors Output:- +```json +{ + "errors": [ + { + "schemaLocation": "https://example.com/main#/anyOf/0/properties/apple/type", + "instanceLocation": "#/apple", + "message": "The instance should be of type 'string' but found 'number'." + } + ] +} +``` \ No newline at end of file diff --git a/documentation/enum.md b/documentation/enum.md new file mode 100644 index 0000000..85394a4 --- /dev/null +++ b/documentation/enum.md @@ -0,0 +1,60 @@ +# Handling `enum` in Better JSON Schema Errors + +The `enum` keyword restricts a value to a fixed set of allowed options. +This library enhances `enum` errors with **two strategies**: + +--- + +## 1. Suggestion Strategy (Levenshtein Distance) + +If the user-provided value is close to one of the allowed values (based on string similarity), +the error message will include a **suggestion**. + +Example Schema: +**Schema:** +```json +{ + "enum": ["apple", "banana", "orange"] +} +``` + +Invalid Instance:- +```json +{ "fruit": "appl" } +``` +BetterJSONSchemaErrors Output:- +```json +{ + "errros": { + "message": "Unexpected value 'appl'. Did you mean 'apple'?", + "instanceLocation": "#/fruit", + "schemaLocation": "https://example.com/main#/properties/fruit/enum" + } +} +``` +## 2. Fallback Strategy (List All Options) + +If no close match is found, the error lists all valid values: + +Example Schema: +**Schema:** +```json +{ + "enum": ["apple", "banana", "orange"] +} +``` + +Invalid Instance:- +```json +{ "fruit": "grape" } +``` +BetterJSONSchemaErrors Output:- +```json +{ + "errros": { + "message": "Unexpected value 'grape'. Expected one of: 'apple', 'banana', or 'orange'.", + "instanceLocation": "#/fruit", + "schemaLocation": "https://example.com/main#/properties/fruit/enum" + } +} +``` \ No newline at end of file diff --git a/documentation/range-handler.md b/documentation/range-handler.md new file mode 100644 index 0000000..a4cebf2 --- /dev/null +++ b/documentation/range-handler.md @@ -0,0 +1,142 @@ +# Range Constraint Keywords + +`better-json-schema-errors` processes validation errors for keywords that define a numeric range or count, such as `minimum`/`maximum`/`exclusiveMinimum`/`exculsiveMaximum` for numbers, `minLength`/`maxLength` for strings, `minItems`/`maxItems` for arrays, and `minProperties`/`maxProperties` for objects. +The primary goal is to consolidate multiple, separate validation errors related to these constraints into a single, clear, and human-readable message that describes the effective valid range for the instance. + +--- + +### Explaination + +When a JSON schema uses combinators like `allOf`, it's possible for an instance to fail validation against multiple range constraints simultaneously. For example, a schema might require an array to have at least 3 items and also at least 5 items. A standard validator might produce two separate errors for this. + +This handler improves the user experience by implementing a unified consolidation strategy for all data types: + +1. Collect All Range Failures: It gathers all failed validation errors for a given type (e.g., all minItems and maxItems failures for an array). + +2. Determine the Strictest Bounds: + + - It calculates the most restrictive lower bound by finding the highest min value (e.g., minimum: 5 is stricter than minimum: 3). + + - It calculates the most restrictive upper bound by finding the lowest max value (e.g., maxLength: 10 is stricter than maxLength: 20). + + - It correctly tracks exclusivity for numbers (e.g., exclusiveMinimum). + +3. Produce a Single, Unified Error: After calculating the effective range, it generates a single error message that combines these constraints into one statement. This prevents overwhelming the user with redundant information and clearly states what is allowed. + +### Examples +### 1. **Number** (`minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`) +Schema: +```json +{ + "allOf": [ + { "minimum": 3 }, + { "minimum": 5 } + ] +} +``` +Instance:- +```json +2 +``` +BetterJSONSchemaErrors Output:- +```json +{ + "errors": [ + { + "schemaLocation": "https://example.com/main#/allOf/1/minimum", + "instanceLocation": "#", + "message": "Expected a number greater than 5." + } + ] +} + +``` + +### 2. **String** (`minLength`, `maxLength`) +Schema: +```json +{ + "allOf": [ + { "minLength": 3 }, + { "minLegth": 5 } + ] +} +``` +Instance:- +```json +"helo" +``` +`better-json-schema-errors` Output:- +```json +{ + "errors": [ + { + "schemaLocation": "https://example.com/main#/allOf/1/minLength", + "instanceLocation": "#", + "message": "Expected a string at least 5 characters long" + } + ] +} + +``` + +### 3. **Array** (`minItems`, `maxItems`) +Schema: +```json +{ + "allOf": [ + { "minItems": 3 }, + { "maxItems": 7 } + ] +} +``` +Instance:- +```json +[1,2] +``` +BetterJSONSchemaErrors Output:- +```json +{ + "errors": [ + { + "schemaLocation": [ + "https://example.com/main#/allOf/0/minItems", + "https://example.com/main#/allOf/1/maxItems" + ], + "instanceLocation": "#", + "message": "Expected the array to have at least 2 items and at most 7 items." + } + ] +} + +``` +### 4. **Object** (`minProperties`, `maxProperties`) +Schema: +```json +{ + "allOf": [ + { "minProperties": 2 }, + { "maxProperties": 5 } + ] +} +``` +Instance:- +```json +{"a": 1} +``` +BetterJSONSchemaErrors Output:- +```json +{ + "errors": [ + { + "schemaLocation": [ + "https://example.com/main#/allOf/0/minProperteis", + "https://example.com/main#/allOf/1/maxProperties" + ], + "instanceLocation": "#", + "message": "Expected the object to have at least 2 properties and at most 5 Properties." + } + ] +} + +``` \ No newline at end of file diff --git a/src/error-handlers/anyOf.js b/src/error-handlers/anyOf.js index 77244a9..14d14d0 100644 --- a/src/error-handlers/anyOf.js +++ b/src/error-handlers/anyOf.js @@ -5,7 +5,7 @@ import * as JsonPointer from "@hyperjump/json-pointer"; import { getErrors } from "../error-handling.js"; /** - * @import { ErrorHandler, ErrorObject, NormalizedOutput } from "../index.d.ts" + * @import { ErrorHandler, ErrorObject, Json, NormalizedOutput } from "../index.d.ts" */ /** @type ErrorHandler */