import { TraverseOptions } from './traverse.js'; import { EvalLog } from './tools.js'; export { registerFormatCompilers } from './format.js'; export { ValidationError, messagesEn, compileMessageTemplate, compileMessageCatalog, renderErrorMessage, localizeErrors, } from './messages.js'; export { TraverseOptions }; export type DollarDataRef = { /** * - Relative JSON Pointer resolved from the current data location */ $data: string; }; export type DataKeywordSchema = { /** * - JSON Pointer to the minimum value */ minimum?: string; /** * - JSON Pointer to the maximum value */ maximum?: string; /** * - JSON Pointer to the exclusive minimum value */ exclusiveMinimum?: string; /** * - JSON Pointer to the exclusive maximum value */ exclusiveMaximum?: string; /** * - JSON Pointer to the multipleOf value */ multipleOf?: string; /** * - JSON Pointer to the minLength value */ minLength?: string; /** * - JSON Pointer to the maxLength value */ maxLength?: string; /** * - JSON Pointer to the pattern string */ pattern?: string; /** * - JSON Pointer to the format name */ format?: string; /** * - JSON Pointer to an array of valid values */ enum?: string; /** * - JSON Pointer to the constant value */ const?: string; /** * - JSON Pointer to the minItems value */ minItems?: string; /** * - JSON Pointer to the maxItems value */ maxItems?: string; /** * - JSON Pointer to the minProperties value */ minProperties?: string; /** * - JSON Pointer to the maxProperties value */ maxProperties?: string; }; export type JSONSchemaKeywords = { /** * - Schema resource identifier (URI) */ $id?: string; /** * - Meta-schema URI declaring the draft dialect */ $schema?: string; /** * - Reference to another schema (URI reference) */ $ref?: string; /** * - Plain-name fragment identifier (2019-09+) */ $anchor?: string; /** * - Dynamic reference (2020-12) */ $dynamicRef?: string; /** * - Dynamic anchor (2020-12) */ $dynamicAnchor?: string; /** * - Vocabulary declarations of a meta-schema */ $vocabulary?: Record; /** * - Comment for schema maintainers; not used in validation */ $comment?: string; /** * - Reusable subschema definitions (2019-09+) */ $defs?: Record; /** * - Reusable subschema definitions (draft-07 and earlier) */ definitions?: Record; /** * - Expected JSON type(s): 'null', 'boolean', 'object', 'array', 'number', 'string' or 'integer' */ type?: string | string[]; /** * - Exhaustive list of valid values */ enum?: unknown[] | DollarDataRef; /** * - Single valid value */ const?: unknown | DollarDataRef; /** * - Minimum string length (in graphemes by default) */ minLength?: number | DollarDataRef; /** * - Maximum string length (in graphemes by default) */ maxLength?: number | DollarDataRef; /** * - ECMA-262 regular expression the string must match */ pattern?: string | DollarDataRef; /** * - Encoding of a string-embedded document (e.g. 'base64') */ contentEncoding?: string; /** * - Media type of a string-embedded document */ contentMediaType?: string; /** * - Schema for the decoded string-embedded document */ contentSchema?: JSONSchema; /** * - Number must be a multiple of this value */ multipleOf?: number | DollarDataRef; /** * - Inclusive lower bound */ minimum?: number | DollarDataRef; /** * - Inclusive upper bound */ maximum?: number | DollarDataRef; /** * - Exclusive lower bound (boolean form in draft-04 style schemas) */ exclusiveMinimum?: number | boolean | DollarDataRef; /** * - Exclusive upper bound (boolean form in draft-04 style schemas) */ exclusiveMaximum?: number | boolean | DollarDataRef; /** * - Schemas for named object members */ properties?: Record; /** * - Schemas for members whose name matches a regular expression */ patternProperties?: Record; /** * - Schema for members not matched by properties/patternProperties */ additionalProperties?: boolean | JSONSchema; /** * - Schema for members not evaluated by any subschema (2019-09+) */ unevaluatedProperties?: boolean | JSONSchema; /** * - Member names that must be present */ required?: string[] | DollarDataRef; /** * - Schema every member name must validate against */ propertyNames?: JSONSchema; /** * - Minimum number of members */ minProperties?: number | DollarDataRef; /** * - Maximum number of members */ maxProperties?: number | DollarDataRef; /** * - Schema for array elements (array form is the draft-07 tuple syntax) */ items?: JSONSchema | JSONSchema[]; /** * - Tuple element schemas (2020-12) */ prefixItems?: JSONSchema[]; /** * - Schema for elements beyond the tuple prefix (draft-07 and earlier) */ additionalItems?: boolean | JSONSchema; /** * - Schema for elements not evaluated by any subschema (2019-09+) */ unevaluatedItems?: boolean | JSONSchema; /** * - At least one element must validate against this schema */ contains?: JSONSchema; /** * - Minimum number of elements */ minItems?: number | DollarDataRef; /** * - Maximum number of elements */ maxItems?: number | DollarDataRef; /** * - Whether all elements must be unique */ uniqueItems?: boolean | DollarDataRef; /** * - Minimum number of elements matching 'contains' (2019-09+) */ minContains?: number; /** * - Maximum number of elements matching 'contains' (2019-09+) */ maxContains?: number; /** * - Value must validate against all of these schemas */ allOf?: JSONSchema[]; /** * - Value must validate against at least one of these schemas */ anyOf?: JSONSchema[]; /** * - Value must validate against exactly one of these schemas */ oneOf?: JSONSchema[]; /** * - Value must NOT validate against this schema */ not?: JSONSchema; /** * - Condition schema selecting between 'then' and 'else' */ if?: JSONSchema; /** * - Applied when 'if' validates */ then?: JSONSchema; /** * - Applied when 'if' does not validate */ else?: JSONSchema; /** * - Schemas applied when a member is present (2019-09+) */ dependentSchemas?: Record; /** * - Members required when a member is present (2019-09+) */ dependentRequired?: Record; /** * - Short descriptive title */ title?: string; /** * - Explanation of the schema's purpose */ description?: string; /** * - Default value annotation */ default?: unknown; /** * - Example values annotation */ examples?: unknown[]; /** * - Value is managed by the receiving authority */ readOnly?: boolean; /** * - Value is never returned by the receiving authority */ writeOnly?: boolean; /** * - Value is deprecated */ deprecated?: boolean; /** * - Named semantic format (e.g. 'email', 'uri', 'date-time') */ format?: string | DollarDataRef; /** * - Format-aware inclusive lower bound (non-standard, Ajv-style) */ formatMinimum?: string; /** * - Format-aware inclusive upper bound (non-standard, Ajv-style) */ formatMaximum?: string; /** * - Format-aware exclusive lower bound (non-standard, Ajv-style) */ formatExclusiveMinimum?: string; /** * - Format-aware exclusive upper bound (non-standard, Ajv-style) */ formatExclusiveMaximum?: string; /** * - Data keyword referencing instance data (json-everything style) */ data?: DataKeywordSchema; }; export type JSONSchema = JSONSchemaKeywords & Record; export type JSONSchemaLike = JSONSchema | Record; export type FormatCompiler = (schemaObj: ValidationObject, jsonSchema: JSONSchema & { format?: string; }) => ((data: unknown, dataPath?: string) => boolean) | undefined; /** * Ajv-style $data reference object. * The value is a Relative JSON Pointer that resolves from the current data location. * Format: `("#"|)` * - "0" - The current value itself * - "0#" - The property name/index of the current value * - "0/foo" - The "foo" property of the current value * - "1" - The parent value * - "1/foo" - The "foo" property of the parent value * @see https://github.com/ajv-validator/ajv/tree/master/spec/extras/%24data * @typedef {Object} DollarDataRef * @property {string} $data - Relative JSON Pointer resolved from the current data location */ /** * Data keyword schema for referencing instance data (json-everything style). * Allows constraints to reference values from other parts of the instance; * every property value is a (relative) JSON Pointer to the constraint's value. * @see https://docs.json-everything.net/schema/examples/data-ref/ * @typedef {Object} DataKeywordSchema * @property {string} [minimum] - JSON Pointer to the minimum value * @property {string} [maximum] - JSON Pointer to the maximum value * @property {string} [exclusiveMinimum] - JSON Pointer to the exclusive minimum value * @property {string} [exclusiveMaximum] - JSON Pointer to the exclusive maximum value * @property {string} [multipleOf] - JSON Pointer to the multipleOf value * @property {string} [minLength] - JSON Pointer to the minLength value * @property {string} [maxLength] - JSON Pointer to the maxLength value * @property {string} [pattern] - JSON Pointer to the pattern string * @property {string} [format] - JSON Pointer to the format name * @property {string} [enum] - JSON Pointer to an array of valid values * @property {string} [const] - JSON Pointer to the constant value * @property {string} [minItems] - JSON Pointer to the minItems value * @property {string} [maxItems] - JSON Pointer to the maxItems value * @property {string} [minProperties] - JSON Pointer to the minProperties value * @property {string} [maxProperties] - JSON Pointer to the maxProperties value */ /** * The standard JSON Schema keywords understood by Jaren * (draft-06 through draft 2020-12). See {@link JSONSchema} for the full * schema object type that also permits custom keywords. * @typedef {Object} JSONSchemaKeywords * @property {string} [$id] - Schema resource identifier (URI) * @property {string} [$schema] - Meta-schema URI declaring the draft dialect * @property {string} [$ref] - Reference to another schema (URI reference) * @property {string} [$anchor] - Plain-name fragment identifier (2019-09+) * @property {string} [$dynamicRef] - Dynamic reference (2020-12) * @property {string} [$dynamicAnchor] - Dynamic anchor (2020-12) * @property {Record} [$vocabulary] - Vocabulary declarations of a meta-schema * @property {string} [$comment] - Comment for schema maintainers; not used in validation * @property {Record} [$defs] - Reusable subschema definitions (2019-09+) * @property {Record} [definitions] - Reusable subschema definitions (draft-07 and earlier) * @property {string | string[]} [type] - Expected JSON type(s): 'null', 'boolean', 'object', 'array', 'number', 'string' or 'integer' * @property {unknown[] | DollarDataRef} [enum] - Exhaustive list of valid values * @property {unknown | DollarDataRef} [const] - Single valid value * @property {number | DollarDataRef} [minLength] - Minimum string length (in graphemes by default) * @property {number | DollarDataRef} [maxLength] - Maximum string length (in graphemes by default) * @property {string | DollarDataRef} [pattern] - ECMA-262 regular expression the string must match * @property {string} [contentEncoding] - Encoding of a string-embedded document (e.g. 'base64') * @property {string} [contentMediaType] - Media type of a string-embedded document * @property {JSONSchema} [contentSchema] - Schema for the decoded string-embedded document * @property {number | DollarDataRef} [multipleOf] - Number must be a multiple of this value * @property {number | DollarDataRef} [minimum] - Inclusive lower bound * @property {number | DollarDataRef} [maximum] - Inclusive upper bound * @property {number | boolean | DollarDataRef} [exclusiveMinimum] - Exclusive lower bound (boolean form in draft-04 style schemas) * @property {number | boolean | DollarDataRef} [exclusiveMaximum] - Exclusive upper bound (boolean form in draft-04 style schemas) * @property {Record} [properties] - Schemas for named object members * @property {Record} [patternProperties] - Schemas for members whose name matches a regular expression * @property {boolean | JSONSchema} [additionalProperties] - Schema for members not matched by properties/patternProperties * @property {boolean | JSONSchema} [unevaluatedProperties] - Schema for members not evaluated by any subschema (2019-09+) * @property {string[] | DollarDataRef} [required] - Member names that must be present * @property {JSONSchema} [propertyNames] - Schema every member name must validate against * @property {number | DollarDataRef} [minProperties] - Minimum number of members * @property {number | DollarDataRef} [maxProperties] - Maximum number of members * @property {JSONSchema | JSONSchema[]} [items] - Schema for array elements (array form is the draft-07 tuple syntax) * @property {JSONSchema[]} [prefixItems] - Tuple element schemas (2020-12) * @property {boolean | JSONSchema} [additionalItems] - Schema for elements beyond the tuple prefix (draft-07 and earlier) * @property {boolean | JSONSchema} [unevaluatedItems] - Schema for elements not evaluated by any subschema (2019-09+) * @property {JSONSchema} [contains] - At least one element must validate against this schema * @property {number | DollarDataRef} [minItems] - Minimum number of elements * @property {number | DollarDataRef} [maxItems] - Maximum number of elements * @property {boolean | DollarDataRef} [uniqueItems] - Whether all elements must be unique * @property {number} [minContains] - Minimum number of elements matching 'contains' (2019-09+) * @property {number} [maxContains] - Maximum number of elements matching 'contains' (2019-09+) * @property {JSONSchema[]} [allOf] - Value must validate against all of these schemas * @property {JSONSchema[]} [anyOf] - Value must validate against at least one of these schemas * @property {JSONSchema[]} [oneOf] - Value must validate against exactly one of these schemas * @property {JSONSchema} [not] - Value must NOT validate against this schema * @property {JSONSchema} [if] - Condition schema selecting between 'then' and 'else' * @property {JSONSchema} [then] - Applied when 'if' validates * @property {JSONSchema} [else] - Applied when 'if' does not validate * @property {Record} [dependentSchemas] - Schemas applied when a member is present (2019-09+) * @property {Record} [dependentRequired] - Members required when a member is present (2019-09+) * @property {string} [title] - Short descriptive title * @property {string} [description] - Explanation of the schema's purpose * @property {unknown} [default] - Default value annotation * @property {unknown[]} [examples] - Example values annotation * @property {boolean} [readOnly] - Value is managed by the receiving authority * @property {boolean} [writeOnly] - Value is never returned by the receiving authority * @property {boolean} [deprecated] - Value is deprecated * @property {string | DollarDataRef} [format] - Named semantic format (e.g. 'email', 'uri', 'date-time') * @property {string} [formatMinimum] - Format-aware inclusive lower bound (non-standard, Ajv-style) * @property {string} [formatMaximum] - Format-aware inclusive upper bound (non-standard, Ajv-style) * @property {string} [formatExclusiveMinimum] - Format-aware exclusive lower bound (non-standard, Ajv-style) * @property {string} [formatExclusiveMaximum] - Format-aware exclusive upper bound (non-standard, Ajv-style) * @property {DataKeywordSchema} [data] - Data keyword referencing instance data (json-everything style) */ /** * Represents a JSON Schema object. * Covers the standard keywords of drafts 06, 07, 2019-09 and 2020-12 * (see {@link JSONSchemaKeywords}) while remaining open for custom * keywords: any property outside the standard set is permitted. * Note that a complete schema is `JSONSchema | boolean` - the boolean * forms accept everything (`true`) or nothing (`false`). * @typedef {JSONSchemaKeywords & Record} JSONSchema */ /** * A schema as a validator boundary ACCEPTS it. {@link JSONSchema} * documents what a schema IS — typed keywords, open for extensions — * but a schema held as a plain `Record` map (the * natural type for a document that crossed a wire or a package * boundary) does not assign to that keyword intersection under strict * TypeScript, and forcing the consumer to cast at every `compile` and * `addSchema` call site teaches them to cast, which is worse than the * looser parameter. The boundary methods accept this union; both arms * are treated identically at runtime, which was always true. * @typedef {JSONSchema | Record} JSONSchemaLike */ /** * A format compiler function. * Called once per schema location at compile time with the compiling * ValidationObject and the schema that declares the format; returns the * format validator that is invoked for each instance value, or undefined * when the format does not apply to the schema location. Compilers are * only invoked for schemas whose `format` member is a plain string. * @typedef {(schemaObj: ValidationObject, jsonSchema: JSONSchema & {format?: string}) => ((data: unknown, dataPath?: string) => boolean) | undefined} FormatCompiler */ export declare const DEFAULT_SCHEMA_DRAFT = "http://json-schema.org/draft-07/schema#"; /** * Detects the JSON Schema draft version from the schema's $schema property * @param {object} schema - The JSON schema * @returns {number} - The draft version (6, 7, 2019, or 2020) */ export declare function detectSchemaDraft(schema: object): number; declare class InternalValidationError { timeStamp: any; object: any; key: any; expected: any; dataKey: any; value: any; rest: any; constructor(obj: any, key: any, expected: any, dataKey: any, value: any, rest: any); } /** * ValidationOptions configures the behavior of the validation process. * @class */ export declare class ValidationOptions { /** @type {boolean} Whether to stop at first error or continue */ skipErrors: boolean; /** @type {boolean} Whether to use grapheme cluster counting for string length */ useGrapheme: boolean; /** @type {boolean} Whether to collect and return detailed errors */ collectErrors: boolean; /** @type {boolean|null} Whether to validate contentEncoding/contentMediaType (null = auto based on draft) */ contentValidation: boolean | null; /** @type {number} The JSON Schema draft version (6, 7, 2019, or 2020) */ draftVersion: number; /** @type {boolean} Whether validation vocabulary keywords (type, minimum, ...) are asserted */ vocabValidation: boolean; /** @type {boolean|null} Whether the format keyword asserts (null = auto by draft) */ formatAssertion: boolean | null; /** @type {boolean} Whether collected errors carry rendered message text */ messages: boolean; /** @type {'error'|'ignore'} What an asserting `format` with no registered compiler does */ unknownFormats: 'error' | 'ignore'; /** * Creates validation options. * @param {boolean} [skipErrors=true] - Whether to stop at first error or continue * @param {boolean} [useGrapheme=true] - Whether to use grapheme cluster counting for strings * @param {boolean} [collectErrors=false] - Whether to collect all errors or just return boolean * @param {boolean|null} [contentValidation=null] - Whether to validate contentEncoding/contentMediaType (null = auto based on draft) * @param {number} [draftVersion=7] - The JSON Schema draft version (6, 7, 2019, or 2020) * @param {boolean} [vocabValidation=true] - Whether the validation vocabulary is enabled (false when the schema's metaschema omits it via $vocabulary) * @param {boolean|null} [formatAssertion=null] - Whether format asserts (null = auto: asserts below draft 2020-12, annotation-only from 2020-12 on) * @param {boolean} [messages=true] - Whether collected errors carry rendered message text; false skips rendering (message: '', params/msgid still set) * @param {'error'|'ignore'} [unknownFormats='ignore'] - What to do when an ASSERTING `format` names something no compiler is registered for: 'ignore' (the default, and what the specification requires) accepts it as an annotation; 'error' throws at COMPILE time. Never affects instance validation, and never applies where format is annotation-only anyway. */ constructor(skipErrors?: boolean, useGrapheme?: boolean, collectErrors?: boolean, contentValidation?: boolean | null, draftVersion?: number, vocabValidation?: boolean, formatAssertion?: boolean | null, messages?: boolean, unknownFormats?: 'error' | 'ignore'); } /** * ValidationRoot manages the compilation and validation context for a schema. * It holds references to all schemas, formats, options, and compiled ValidationObjects. * @class */ export declare class ValidationRoot { #private; /** * Creates a new ValidationRoot. * @param {string} origin - The root schema origin/URI * @param {Map} schemas - Map of schema paths to schema objects * @param {Record} formats - Registered format validators * @param {ValidationOptions} [opts] - Validation options * @param {TraverseOptions} [traverse] - Schema traversal options * @param {object|null} [owner] - The owning JarenValidator instance; extension * keywords ('$query') compile embedded schema literals against it so their * `$ref`s resolve to the owner's `addSchema` registrations */ constructor(origin: string, schemas: Map, formats: Record, opts?: ValidationOptions, traverse?: TraverseOptions, owner?: object | null); /** @returns {TraverseOptions} Schema traversal options */ get traverse(): TraverseOptions; /** @returns {ValidationOptions} Validation options */ get options(): ValidationOptions; /** @returns {object} Registered format validators */ get formats(): object; /** @returns {Array} Array of validation errors */ get errors(): any[]; /** @returns {boolean} Whether any schema in this compilation contains a $data reference */ get usesDollarData(): boolean; /** @returns {boolean} Whether any schema in this compilation contains unevaluatedProperties/unevaluatedItems */ get usesUnevaluated(): boolean; /** @returns {EvalLog} The evaluation log for unevaluated* annotation tracking */ get evalLog(): EvalLog; /** @returns {object|null} The owning JarenValidator instance, or null when constructed standalone */ get owner(): object | null; /** @returns {Map|null} Compiled 'errorMessage' specs by schema path, or null when the schema set has none */ get errorMessages(): Map | null; /** * Register a compiled 'errorMessage' spec for a schema location. * Called at schema compile time (see compileSchemaObject); the registry * is only consulted at report time, over the already-failed set. * @param {string} path - The schema path (ValidationObject.path) * @param {object} spec - The compiled spec (see messages.js compileErrorMessageSpec) */ registerErrorMessage(path: string, spec: object): void; /** * Creates a new ValidationObject for the given path and schema. * @param {string} path - The URI path for this schema object * @param {object|boolean} schema - The JSON schema * @param {string} baseUri - The base URI for resolving relative refs * @returns {ValidationObject} The created ValidationObject */ createObject(path: string, schema: object | boolean, baseUri: string, parentDeclaredDraft?: null): ValidationObject; /** * Checks if an object exists at the given path without creating it. * @param {string} path - The URI path to check * @returns {ValidationObject|null|undefined} The existing object, null if marked unresolved, or undefined if not known */ unresolvedObject(path: string): ValidationObject | null | undefined; /** * Gets the raw schema object by its URI/ID directly from the schemas map. * This performs a direct lookup without following references. * @param {string} uri - The schema URI to look up * @returns {object|undefined} The raw schema object or undefined */ getSchemaByUri(uri: string): object | undefined; /** * Resolves a $ref to a ValidationObject, creating it if necessary. * @param {string} ref - The reference URI to resolve * @param {string} path - The current path (for error messages) * @param {object} schema - The schema containing the $ref * @returns {ValidationObject} The resolved ValidationObject */ resolveObject(ref: string, path: string, schema: object): ValidationObject; /** * Adds an error to the validation errors list. * @param {InternalValidationError} error - The error to add * @returns {boolean} Always returns false for convenience in validators */ addError(error: InternalValidationError): boolean; /** * A checkpoint in the collected-error list. * * A SPECULATIVE applicator - an `anyOf` branch, an `if` condition, the * subschema of a `not`, a `contains` candidate - runs a validator whose * failure may be entirely expected. Those failures still call `addError`, * so without a checkpoint they leak into the caller's issue list and blame * a document for not matching a branch it was never required to match. * Marking before the probe and rolling back after is the same discipline * `EvalLog` already uses for annotations. * @returns {number} The mark to pass to {@link rollbackErrors} */ errorMark(): number; /** * Discard every error collected since `mark`. * @param {number} mark - A value from {@link errorMark} */ rollbackErrors(mark: number): void; /** * Validates data against the root schema. * @param {unknown} data - The data to validate * @returns {boolean} True if valid, false otherwise */ validate(data: unknown): boolean; /** * Returns the fastest repeated-validation entry point for this root. * Error collection and root-level dynamic anchors need the per-call * bookkeeping of validate(); without them the compiled root validator * only needs the annotation log cleared (when tracking is on) and can * otherwise be invoked directly. Dynamic anchors pushed during * validation are balanced by try/finally, so the anchor map needs no * per-call clearing here. * @returns {(data: unknown) => boolean} The validation entry point */ createValidateFn(): (data: unknown) => boolean; /** * Get the stored validator for a dynamic anchor. * Used by $dynamicRef for runtime resolution. * Per draft 2020-12, $dynamicRef resolves to the FIRST (outermost) * resource in the dynamic scope that defines the anchor. * @param {string} anchorName - The anchor name * @returns {Function|null} The validator function or null if not set */ getDynamicAnchorValidator(anchorName: string): Function | null; /** * Get the outermost validator for a recursive anchor. * Used by $recursiveRef for runtime resolution. * Returns the bottom of the stack (first/outermost registered validator). * @param {string} anchorName - The anchor name (empty string for $recursiveRef) * @returns {Function|null} The validator function or null if not set */ getOutermostDynamicAnchorValidator(anchorName: string): Function | null; /** * Push a validator onto the stack for a dynamic anchor. * Called when entering a schema with $recursiveAnchor or $dynamicAnchor. * @param {string} anchorName - The anchor name * @param {Function} validator - The validator function */ pushDynamicAnchorValidator(anchorName: string, validator: Function): void; /** * Pop a validator from the stack for a dynamic anchor. * Called when exiting a schema with $recursiveAnchor or $dynamicAnchor. * @param {string} anchorName - The anchor name */ popDynamicAnchorValidator(anchorName: string): void; /** * Get or create a validator for a given schema. * This is used when we need a validator for a schema at validation time * (e.g., for dynamic anchors collected from $defs). * @param {object} schema - The schema to create a validator for * @param {string} basePath - The base path for the schema * @param {string} baseUri - The base URI for the schema * @returns {Function} The validator function */ getOrCreateValidator(schema: object, basePath: string, baseUri: string): Function; } /** * ValidationObject represents a single schema location with its compiled validator. * It handles the compilation of schema validation logic and provides methods for * creating child validators and error handlers. * @class */ export declare class ValidationObject { #private; /** * Compiles a validator function for the given schema. * This is the main entry point for schema compilation. It handles: * - Simple schemas (type-only, required-only) via fast paths * - Schemas with $ref by resolving to target validators * - Complex schemas by delegating to compileSchemaObject * @param {ValidationObject} self - The validation object that is compiling this validator * @param {string} path - The path to this schema object (its URI identifier) * @param {any} schema - The schema object to compile * @param {string} baseUri - The base URI for resolving $ref (parent's base, before any sibling $id) * @returns {function(any, any):boolean} A function that validates data against the compiled schema and returns a boolean. */ static compileValidator(self: ValidationObject, path: string, schema: any, baseUri: string): Function; /** * Creates a new ValidationObject. * @param {ValidationRoot} root - The root validation context * @param {string} path - The URI path identifying this schema object * @param {any} schema - The schema object to compile * @param {string} baseUri - The base URI for resolving $ref * @param {number|null} [parentDeclaredDraft] - The declared draft inherited from the parent schema object */ constructor(root: ValidationRoot, path: string, schema: any, baseUri: string, parentDeclaredDraft?: number | null); /** @returns {string} The URI path identifying this schema object */ get path(): string; /** @returns {string} The effective base URI for resolving relative $refs */ get baseUri(): string; /** @returns {function} The compiled validator function */ get validate(): Function; /** @returns {ValidationOptions} The validation options */ get options(): ValidationOptions; /** @returns {object} The registered format validators */ get formats(): object; /** @returns {ValidationRoot} The root validation context */ get root(): ValidationRoot; /** @returns {object} The schema object */ get schema(): object; /** @returns {number|null} Draft version declared by this schema's document via $schema, or null when never declared */ get declaredDraft(): number | null; /** * Creates an error handler function for validation failures. * @param {any} expected - The expected value that failed validation * @param {string | string[]} key - The keyword or keywords that failed * @returns {(data: unknown, ...meta: any[]) => boolean} A function that adds an error and returns false */ createErrorHandler(expected: any, key: string | string[]): (data: unknown, ...meta: any[]) => boolean; /** * Creates a validator function for a child schema. * This is used when compiling nested schemas (e.g., array items, object properties). * @param {JSONSchema | boolean} schema - The child schema to compile * @param {string} key - The property key where the schema is located * @param {number} [index] - Optional array index for tuple items * @returns {function|undefined} The compiled validator function, or undefined if schema is invalid */ createValidator(schema: JSONSchema | boolean, key: string, index?: number): Function | undefined; } /** * ValidatorOptions configures the JarenValidator instance. * Can be created with positional arguments or an options object. * @class * @example * // Positional arguments * const options = new ValidatorOptions(formats, schemas, validation, traverse); * * // Options object (recommended) * const options = new ValidatorOptions({ * formats: { custom: validator }, * collectErrors: true, * useGrapheme: false * }); */ export declare class ValidatorOptions { /** @type {object} Registered format validators */ formats: object; /** @type {object[]} Initial schemas to register */ schemas: object[]; validation: ValidationOptions; /** @type {TraverseOptions} Schema traversal options */ traverse: TraverseOptions; /** * Creates validator options. * @param {object|object[]} [formats={}] - Format validators or options object * @param {object[]} [schemas=[]] - Initial schemas to register * @param {ValidationOptions} [validation] - Validation behavior options * @param {TraverseOptions} [traverse] - Schema traversal options */ constructor(formats?: object | object[], schemas?: object[], validation?: ValidationOptions, traverse?: TraverseOptions); } export type ValidationResultObject = { valid: boolean; errors: import("./messages.js").ValidationError[]; }; export type CompiledPredicate = (data: unknown) => data is T; export type CompiledCollector = (data: unknown) => ValidationResultObject; export type ValidatorInit = { /** * - Format compilers to register */ formats?: Record; /** * - Schemas to register */ schemas?: (JSONSchema | boolean)[]; /** * - Validation behavior options */ validation?: ValidationOptions; /** * - Schema traversal options */ traverse?: TraverseOptions; /** * - Return `{ valid, errors }` instead of a boolean */ collectErrors?: TCollect; /** * - Stop at the first failure (defaults to `!collectErrors`) */ skipErrors?: boolean; /** * - Count grapheme clusters for string length */ useGrapheme?: boolean; /** * - Assert contentEncoding/contentMediaType */ contentValidation?: boolean; /** * - The JSON Schema draft version */ draftVersion?: number; /** * - Assert the format keyword */ formatAssertion?: boolean; /** * - Render English message text on collected errors */ messages?: boolean; /** * - What an ASSERTING `format` with no registered compiler does: 'ignore' (default, per spec) accepts it as an annotation, 'error' throws at compile time */ unknownFormats?: 'error' | 'ignore'; }; /** * The object a compiled validator returns when `collectErrors` is enabled. * @typedef {{ valid: boolean, errors: import("./messages.js").ValidationError[] }} ValidationResultObject */ /** * A compiled validator in the default boolean mode. It is a type guard, so * `T` is whatever the caller asserts the schema describes; with no `T` it * behaves as an ordinary boolean predicate. * @template T * @typedef {(data: unknown) => data is T} CompiledPredicate */ /** * A compiled validator in collect-errors mode. * @typedef {(data: unknown) => ValidationResultObject} CompiledCollector */ /** * The plain-object form accepted by the JarenValidator constructor, mixing * validator-level settings with the ValidationOptions fields. * @template {boolean} [TCollect=false] * @typedef {object} ValidatorInit * @property {Record} [formats] - Format compilers to register * @property {(JSONSchema | boolean)[]} [schemas] - Schemas to register * @property {ValidationOptions} [validation] - Validation behavior options * @property {TraverseOptions} [traverse] - Schema traversal options * @property {TCollect} [collectErrors] - Return `{ valid, errors }` instead of a boolean * @property {boolean} [skipErrors] - Stop at the first failure (defaults to `!collectErrors`) * @property {boolean} [useGrapheme] - Count grapheme clusters for string length * @property {boolean} [contentValidation] - Assert contentEncoding/contentMediaType * @property {number} [draftVersion] - The JSON Schema draft version * @property {boolean} [formatAssertion] - Assert the format keyword * @property {boolean} [messages] - Render English message text on collected errors * @property {'error'|'ignore'} [unknownFormats] - What an ASSERTING `format` with no registered compiler does: 'ignore' (default, per spec) accepts it as an annotation, 'error' throws at compile time */ /** * JarenValidator is the main entry point for JSON Schema validation. * It manages schema registration, format registration, and compilation. * * The `collectErrors` option decides what a compiled validator returns, and * it is carried in the type parameter so the two shapes never have to be * distinguished at runtime. * @template {boolean} [TCollect=false] * @class * @example * const validator = new JarenValidator(); * validator.addSchema({ $id: 'http://example.com/schema', type: 'object' }); * const validate = validator.compile({ $ref: 'http://example.com/schema' }); * const valid = validate({ foo: 'bar' }); // true */ export declare class JarenValidator { #private; /** * Creates a new JarenValidator instance. * @param {ValidatorOptions | ValidatorInit} [options] - Validator options including formats, schemas, validation options, and traverse options */ constructor(options?: ValidatorOptions | ValidatorInit); /** * Adds a format validator. * @param {string} name - The format name (e.g., 'email', 'uri', 'date-time') * @param {FormatCompiler} formatCompiler - A function that compiles format validators * @returns {this} This validator instance for chaining (the polymorphic `this` keeps the collectErrors type parameter across a chain) * @example * validator.addFormat('custom', (schemaObj, schema) => { * return (data) => data.startsWith('custom:'); * }); */ addFormat(name: string, formatCompiler: FormatCompiler): this; /** * Adds multiple format validators at once. * @param {Record} formatCompilers - Object mapping format names to compiler functions * @returns {this} This validator instance for chaining (the polymorphic `this` keeps the collectErrors type parameter across a chain) */ addFormats(formatCompilers: Record): this; /** * Adds schema(s) to the validator instance. * This method does not compile schemas - it only registers them for reference. * Dependencies can be added in any order, and circular dependencies are supported. * @param {JSONSchemaLike | boolean | (JSONSchemaLike | boolean)[]} schema - The schema(s) to add * @param {string} [key] - Optional key/URI to register the schema under * @returns {this} This validator instance for chaining (the polymorphic `this` keeps the collectErrors type parameter across a chain) * @example * // Add a single schema * validator.addSchema({ $id: 'http://example.com/user', type: 'object' }); * * // Add multiple schemas * validator.addSchema([schema1, schema2]); * * // Add with explicit key * validator.addSchema({ type: 'string' }, 'http://example.com/name'); */ addSchema(schema: JSONSchemaLike | boolean | (JSONSchemaLike | boolean)[], key?: string): this; static normalizeUriKey(key: any): any; /** * Adds meta-schema(s) that can be used to validate schemas. * Meta-schemas are schemas that describe the structure of valid JSON schemas. * @param {JSONSchemaLike | boolean | (JSONSchemaLike | boolean)[]} schema - The meta-schema(s) to add * @param {string} [key] - Optional key/URI for the meta-schema * @returns {this} This validator instance for chaining (the polymorphic `this` keeps the collectErrors type parameter across a chain) * @example * validator.addMetaSchema(draft7MetaSchema, 'http://json-schema.org/draft-07/schema'); */ addMetaSchema(schema: JSONSchemaLike | boolean | (JSONSchemaLike | boolean)[], key?: string): this; /** * Retrieves a registered schema by its key/URI. * @param {string} key - The schema URI/key * @returns {JSONSchema | boolean | null} The registered schema, or null if not found */ getSchema(key: string): JSONSchema | boolean | null; /** * Validates a schema against a registered meta-schema. * This is used to ensure schemas are valid according to the JSON Schema specification. * @param {JSONSchemaLike | boolean} schema - The schema to validate * @returns {boolean} True if the schema is valid * @example * validator.addMetaSchema(draft7MetaSchema); * const isValid = validator.validateSchema({ type: 'string' }); // true */ validateSchema(schema: JSONSchemaLike | boolean): boolean; /** * Compiles a schema into a validation function. * This is the main method for creating validators. It resolves all $ref references, * compiles the schema structure, and returns a function that validates data. * The return type follows the instance's `collectErrors` setting: a type * guard over `unknown` by default, or a function producing * `{ valid, errors }` when errors are collected. Jaren does not infer `T` * from the schema — the caller asserts what the schema describes, which is * what a checked contract wrapper wants; pair it with a schema-to-type * generator if you need the shape derived mechanically. * @template [T=unknown] * @param {JSONSchemaLike | boolean} schema - The schema to compile * @param {(JSONSchemaLike | boolean)[]} [schemas] - Additional schemas to reference during compilation * @returns {TCollect extends true ? CompiledCollector : CompiledPredicate} A validation function * @example * const validate = validator.compile({ * type: 'object', * properties: { * name: { type: 'string' } * } * }); * * const valid = validate({ name: 'John' }); // true * const invalid = validate({ name: 123 }); // false * * // Narrowing to a caller-asserted type * const isUser = validator.compile<{ name: string }>(userSchema); * if (isUser(input)) input.name; // input is { name: string } here * * // With error collection * const collecting = new JarenValidator({ collectErrors: true }); * const result = collecting.compile(schema)({ name: 123 }); * // result = { valid: false, errors: [...] } */ compile(schema: JSONSchemaLike | boolean, schemas?: (JSONSchemaLike | boolean)[]): TCollect extends true ? CompiledCollector : CompiledPredicate; }