code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;
const codegen_1 = require("../codegen");
const util_1 = require("../util");
function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
    if (keyword !== undefined && schema !== undefined) {
        throw new Error('both "keyword" and "schema" passed, only one allowed');
    }
    if (keyword !== undefined) {
        const sch = it.schema[keyword];
        return schemaProp === undefined
            ? {
                schema: sch,
                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
                errSchemaPath: `${it.errSchemaPath}/${keyword}`,
            }
            : {
                schema: sch[schemaProp],
                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
                errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`,
            };
    }
    if (schema !== undefined) {
        if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
            throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
        }
        return {
            schema,
            schemaPath,
            topSchemaRef,
            errSchemaPath,
        };
    }
    throw new Error('either "keyword" or "schema" must be passed');
}
exports.getSubschema = getSubschema;
function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
    if (data !== undefined && dataProp !== undefined) {
        throw new Error('both "data" and "dataProp" passed, only one allowed');
    }
    const { gen } = it;
    if (dataProp !== undefined) {
        const { errorPath, dataPathArr, opts } = it;
        const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
        dataContextProps(nextData);
        subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
        subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`;
        subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
    }
    if (data !== undefined) {
        const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); // replaceable if used once?
        dataContextProps(nextData);
        if (propertyName !== undefined)
            subschema.propertyName = propertyName;
        // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
    }
    if (dataTypes)
        subschema.dataTypes = dataTypes;
    function dataContextProps(_nextData) {
        subschema.data = _nextData;
        subschema.dataLevel = it.dataLevel + 1;
        subschema.dataTypes = [];
        it.definedProperties = new Set();
        subschema.parentData = it.data;
        subschema.dataNames = [...it.dataNames, _nextData];
    }
}
exports.extendSubschemaData = extendSubschemaData;
function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
    if (compositeRule !== undefined)
        subschema.compositeRule = compositeRule;
    if (createErrors !== undefined)
        subschema.createErrors = createErrors;
    if (allErrors !== undefined)
        subschema.allErrors = allErrors;
    subschema.jtdDiscriminator = jtdDiscriminator; // not inherited
    subschema.jtdMetadata = jtdMetadata; // not inherited
}
exports.extendSubschemaMode = extendSubschemaMode;
//# sourceMappingURL=subschema.js.map


code:
export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, AnyValidateFunction, ErrorObject, ErrorNoParams, } from "./types";
export { SchemaCxt, SchemaObjCxt } from "./compile";
export interface Plugin<Opts> {
    (ajv: Ajv, options?: Opts): Ajv;
    [prop: string]: any;
}
export { KeywordCxt } from "./compile/validate";
export { DefinedError } from "./vocabularies/errors";
export { JSONType } from "./compile/rules";
export { JSONSchemaType } from "./types/json-schema";
export { JTDSchemaType, SomeJTDSchemaType, JTDDataType } from "./types/jtd-schema";
export { _, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions } from "./compile/codegen";
import type { Schema, AnySchema, AnySchemaObject, SchemaObject, AsyncSchema, Vocabulary, KeywordDefinition, AddedKeywordDefinition, AnyValidateFunction, ValidateFunction, AsyncValidateFunction, ErrorObject, Format, AddedFormat, RegExpEngine, UriResolver } from "./types";
import type { JSONSchemaType } from "./types/json-schema";
import type { JTDSchemaType, SomeJTDSchemaType, JTDDataType } from "./types/jtd-schema";
import ValidationError from "./runtime/validation_error";
import MissingRefError from "./compile/ref_error";
import { ValidationRules } from "./compile/rules";
import { SchemaEnv } from "./compile";
import { Code, ValueScope } from "./compile/codegen";
export type Options = CurrentOptions & DeprecatedOptions;
export interface CurrentOptions {
    strict?: boolean | "log";
    strictSchema?: boolean | "log";
    strictNumbers?: boolean | "log";
    strictTypes?: boolean | "log";
    strictTuples?: boolean | "log";
    strictRequired?: boolean | "log";
    allowMatchingProperties?: boolean;
    allowUnionTypes?: boolean;
    validateFormats?: boolean;
    $data?: boolean;
    allErrors?: boolean;
    verbose?: boolean;
    discriminator?: boolean;
    unicodeRegExp?: boolean;
    timestamp?: "string" | "date";
    parseDate?: boolean;
    allowDate?: boolean;
    $comment?: true | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown);
    formats?: {
        [Name in string]?: Format;
    };
    keywords?: Vocabulary;
    schemas?: AnySchema[] | {
        [Key in string]?: AnySchema;
    };
    logger?: Logger | false;
    loadSchema?: (uri: string) => Promise<AnySchemaObject>;
    removeAdditional?: boolean | "all" | "failing";
    useDefaults?: boolean | "empty";
    coerceTypes?: boolean | "array";
    next?: boolean;
    unevaluated?: boolean;
    dynamicRef?: boolean;
    schemaId?: "id" | "$id";
    jtd?: boolean;
    meta?: SchemaObject | boolean;
    defaultMeta?: string | AnySchemaObject;
    validateSchema?: boolean | "log";
    addUsedSchema?: boolean;
    inlineRefs?: boolean | number;
    passContext?: boolean;
    loopRequired?: number;
    loopEnum?: number;
    ownProperties?: boolean;
    multipleOfPrecision?: number;
    int32range?: boolean;
    messages?: boolean;
    code?: CodeOptions;
    uriResolver?: UriResolver;
}
export interface CodeOptions {
    es5?: boolean;
    esm?: boolean;
    lines?: boolean;
    optimize?: boolean | number;
    formats?: Code;
    source?: boolean;
    process?: (code: string, schema?: SchemaEnv) => string;
    regExp?: RegExpEngine;
}
interface InstanceCodeOptions extends CodeOptions {
    regExp: RegExpEngine;
    optimize: number;
}
interface DeprecatedOptions {
    /** @deprecated */
    ignoreKeywordsWithRef?: boolean;
    /** @deprecated */
    jsPropertySyntax?: boolean;
    /** @deprecated */
    unicode?: boolean;
}
type RequiredInstanceOptions = {
    [K in "strictSchema" | "strictNumbers" | "strictTypes" | "strictTuples" | "strictRequired" | "inlineRefs" | "loopRequired" | "loopEnum" | "meta" | "messages" | "schemaId" | "addUsedSchema" | "validateSchema" | "validateFormats" | "int32range" | "unicodeRegExp" | "uriResolver"]: NonNullable<Options[K]>;
} & {
    code: InstanceCodeOptions;
};
export type InstanceOptions = Options & RequiredInstanceOptions;
export interface Logger {
    log(...args: unknown[]): unknown;
    warn(...args: unknown[]): unknown;
    error(...args: unknown[]): unknown;
}
export default class Ajv {
    opts: InstanceOptions;
    errors?: ErrorObject[] | null;
    logger: Logger;
    readonly scope: ValueScope;
    readonly schemas: {
        [Key in string]?: SchemaEnv;
    };
    readonly refs: {
        [Ref in string]?: SchemaEnv | string;
    };
    readonly formats: {
        [Name in string]?: AddedFormat;
    };
    readonly RULES: ValidationRules;
    readonly _compilations: Set<SchemaEnv>;
    private readonly _loading;
    private readonly _cache;
    private readonly _metaOpts;
    static ValidationError: typeof ValidationError;
    static MissingRefError: typeof MissingRefError;
    constructor(opts?: Options);
    _addVocabularies(): void;
    _addDefaultMetaSchema(): void;
    defaultMeta(): string | AnySchemaObject | undefined;
    validate(schema: Schema | string, data: unknown): boolean;
    validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown>;
    validate<T>(schema: Schema | JSONSchemaType<T> | string, data: unknown): data is T;
    validate<T>(schema: JTDSchemaType<T>, data: unknown): data is T;
    validate<N extends never, T extends SomeJTDSchemaType>(schema: T, data: unknown): data is JTDDataType<T>;
    validate<T>(schema: AsyncSchema, data: unknown | T): Promise<T>;
    validate<T>(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise<T>;
    compile<T = unknown>(schema: Schema | JSONSchemaType<T>, _meta?: boolean): ValidateFunction<T>;
    compile<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): ValidateFunction<T>;
    compile<N extends never, T extends SomeJTDSchemaType>(schema: T, _meta?: boolean): ValidateFunction<JTDDataType<T>>;
    compile<T = unknown>(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction<T>;
    compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T>;
    compileAsync<T = unknown>(schema: SchemaObject | JSONSchemaType<T>, _meta?: boolean): Promise<ValidateFunction<T>>;
    compileAsync<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): Promise<ValidateFunction<T>>;
    compileAsync<T = unknown>(schema: AsyncSchema, meta?: boolean): Promise<AsyncValidateFunction<T>>;
    compileAsync<T = unknown>(schema: AnySchemaObject, meta?: boolean): Promise<AnyValidateFunction<T>>;
    addSchema(schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored
    key?: string, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
    _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
    _validateSchema?: boolean | "log"): Ajv;
    addMetaSchema(schema: AnySchemaObject, key?: string, // schema key
    _validateSchema?: boolean | "log"): Ajv;
    validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise<unknown>;
    getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined;
    removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv;
    addVocabulary(definitions: Vocabulary): Ajv;
    addKeyword(kwdOrDef: string | KeywordDefinition, def?: KeywordDefinition): Ajv;
    getKeyword(keyword: string): AddedKeywordDefinition | boolean;
    removeKeyword(keyword: string): Ajv;
    addFormat(name: string, format: Format): Ajv;
    errorsText(errors?: ErrorObject[] | null | undefined, // optional array of validation errors
    { separator, dataVar }?: ErrorsTextOptions): string;
    $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject;
    private _removeAllSchemas;
    _addSchema(schema: AnySchema, meta?: boolean, baseId?: string, validateSchema?: boolean | "log", addSchema?: boolean): SchemaEnv;
    private _checkUnique;
    private _compileSchemaEnv;
    private _compileMetaSchema;
}
export interface ErrorsTextOptions {
    separator?: string;
    dataVar?: string;
}

license: mit


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
const validation_error_1 = require("./runtime/validation_error");
const ref_error_1 = require("./compile/ref_error");
const rules_1 = require("./compile/rules");
const compile_1 = require("./compile");
const codegen_2 = require("./compile/codegen");
const resolve_1 = require("./compile/resolve");
const dataType_1 = require("./compile/validate/dataType");
const util_1 = require("./compile/util");
const $dataRefSchema = require("./refs/data.json");
const uri_1 = require("./runtime/uri");
const defaultRegExp = (str, flags) => new RegExp(str, flags);
defaultRegExp.code = "new RegExp";
const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
const EXT_SCOPE_NAMES = new Set([
    "validate",
    "serialize",
    "parse",
    "wrapper",
    "root",
    "schema",
    "keyword",
    "pattern",
    "formats",
    "validate$data",
    "func",
    "obj",
    "Error",
]);
const removedOptions = {
    errorDataPath: "",
    format: "`validateFormats: false` can be used instead.",
    nullable: '"nullable" keyword is supported by default.',
    jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
    extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
    missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
    processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
    sourceCode: "Use option `code: {source: true}`",
    strictDefaults: "It is default now, see option `strict`.",
    strictKeywords: "It is default now, see option `strict`.",
    uniqueItems: '"uniqueItems" keyword is always validated.',
    unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
    cache: "Map is used as cache, schema object as key.",
    serialize: "Map is used as cache, schema object as key.",
    ajvErrors: "It is default now.",
};
const deprecatedOptions = {
    ignoreKeywordsWithRef: "",
    jsPropertySyntax: "",
    unicode: '"minLength"/"maxLength" account for unicode characters by default.',
};
const MAX_EXPRESSION = 200;
// eslint-disable-next-line complexity
function requiredOptions(o) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
    const s = o.strict;
    const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
    const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
    const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
    const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
    return {
        strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
        strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
        strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
        strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
        strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
        code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
        loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
        loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
        meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
        messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
        inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
        schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
        addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
        validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
        validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
        unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
        int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
        uriResolver: uriResolver,
    };
}
class Ajv {
    constructor(opts = {}) {
        this.schemas = {};
        this.refs = {};
        this.formats = {};
        this._compilations = new Set();
        this._loading = {};
        this._cache = new Map();
        opts = this.opts = { ...opts, ...requiredOptions(opts) };
        const { es5, lines } = this.opts.code;
        this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
        this.logger = getLogger(opts.logger);
        const formatOpt = opts.validateFormats;
        opts.validateFormats = false;
        this.RULES = (0, rules_1.getRules)();
        checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
        checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
        this._metaOpts = getMetaSchemaOptions.call(this);
        if (opts.formats)
            addInitialFormats.call(this);
        this._addVocabularies();
        this._addDefaultMetaSchema();
        if (opts.keywords)
            addInitialKeywords.call(this, opts.keywords);
        if (typeof opts.meta == "object")
            this.addMetaSchema(opts.meta);
        addInitialSchemas.call(this);
        opts.validateFormats = formatOpt;
    }
    _addVocabularies() {
        this.addKeyword("$async");
    }
    _addDefaultMetaSchema() {
        const { $data, meta, schemaId } = this.opts;
        let _dataRefSchema = $dataRefSchema;
        if (schemaId === "id") {
            _dataRefSchema = { ...$dataRefSchema };
            _dataRefSchema.id = _dataRefSchema.$id;
            delete _dataRefSchema.$id;
        }
        if (meta && $data)
            this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
    }
    defaultMeta() {
        const { meta, schemaId } = this.opts;
        return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined);
    }
    validate(schemaKeyRef, // key, ref or schema object
    // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
    data // to be validated
    ) {
        let v;
        if (typeof schemaKeyRef == "string") {
            v = this.getSchema(schemaKeyRef);
            if (!v)
                throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
        }
        else {
            v = this.compile(schemaKeyRef);
        }
        const valid = v(data);
        if (!("$async" in v))
            this.errors = v.errors;
        return valid;
    }
    compile(schema, _meta) {
        const sch = this._addSchema(schema, _meta);
        return (sch.validate || this._compileSchemaEnv(sch));
    }
    compileAsync(schema, meta) {
        if (typeof this.opts.loadSchema != "function") {
            throw new Error("options.loadSchema should be a function");
        }
        const { loadSchema } = this.opts;
        return runCompileAsync.call(this, schema, meta);
        async function runCompileAsync(_schema, _meta) {
            await loadMetaSchema.call(this, _schema.$schema);
            const sch = this._addSchema(_schema, _meta);
            return sch.validate || _compileAsync.call(this, sch);
        }
        async function loadMetaSchema($ref) {
            if ($ref && !this.getSchema($ref)) {
                await runCompileAsync.call(this, { $ref }, true);
            }
        }
        async function _compileAsync(sch) {
            try {
                return this._compileSchemaEnv(sch);
            }
            catch (e) {
                if (!(e instanceof ref_error_1.default))
                    throw e;
                checkLoaded.call(this, e);
                await loadMissingSchema.call(this, e.missingSchema);
                return _compileAsync.call(this, sch);
            }
        }
        function checkLoaded({ missingSchema: ref, missingRef }) {
            if (this.refs[ref]) {
                throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
            }
        }
        async function loadMissingSchema(ref) {
            const _schema = await _loadSchema.call(this, ref);
            if (!this.refs[ref])
                await loadMetaSchema.call(this, _schema.$schema);
            if (!this.refs[ref])
                this.addSchema(_schema, ref, meta);
        }
        async function _loadSchema(ref) {
            const p = this._loading[ref];
            if (p)
                return p;
            try {
                return await (this._loading[ref] = loadSchema(ref));
            }
            finally {
                delete this._loading[ref];
            }
        }
    }
    // Adds schema to the instance
    addSchema(schema, // If array is passed, `key` will be ignored
    key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
    _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
    _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
    ) {
        if (Array.isArray(schema)) {
            for (const sch of schema)
                this.addSchema(sch, undefined, _meta, _validateSchema);
            return this;
        }
        let id;
        if (typeof schema === "object") {
            const { schemaId } = this.opts;
            id = schema[schemaId];
            if (id !== undefined && typeof id != "string") {
                throw new Error(`schema ${schemaId} must be string`);
            }
        }
        key = (0, resolve_1.normalizeId)(key || id);
        this._checkUnique(key);
        this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
        return this;
    }
    // Add schema that will be used to validate other schemas
    // options in META_IGNORE_OPTIONS are alway set to false
    addMetaSchema(schema, key, // schema key
    _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
    ) {
        this.addSchema(schema, key, true, _validateSchema);
        return this;
    }
    //  Validate schema against its meta-schema
    validateSchema(schema, throwOrLogError) {
        if (typeof schema == "boolean")
            return true;
        let $schema;
        $schema = schema.$schema;
        if ($schema !== undefined && typeof $schema != "string") {
            throw new Error("$schema must be a string");
        }
        $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
        if (!$schema) {
            this.logger.warn("meta-schema not available");
            this.errors = null;
            return true;
        }
        const valid = this.validate($schema, schema);
        if (!valid && throwOrLogError) {
            const message = "schema is invalid: " + this.errorsText();
            if (this.opts.validateSchema === "log")
                this.logger.error(message);
            else
                throw new Error(message);
        }
        return valid;
    }
    // Get compiled schema by `key` or `ref`.
    // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
    getSchema(keyRef) {
        let sch;
        while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
            keyRef = sch;
        if (sch === undefined) {
            const { schemaId } = this.opts;
            const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
            sch = compile_1.resolveSchema.call(this, root, keyRef);
            if (!sch)
                return;
            this.refs[keyRef] = sch;
        }
        return (sch.validate || this._compileSchemaEnv(sch));
    }
    // Remove cached schema(s).
    // If no parameter is passed all schemas but meta-schemas are removed.
    // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
    // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
    removeSchema(schemaKeyRef) {
        if (schemaKeyRef instanceof RegExp) {
            this._removeAllSchemas(this.schemas, schemaKeyRef);
            this._removeAllSchemas(this.refs, schemaKeyRef);
            return this;
        }
        switch (typeof schemaKeyRef) {
            case "undefined":
                this._removeAllSchemas(this.schemas);
                this._removeAllSchemas(this.refs);
                this._cache.clear();
                return this;
            case "string": {
                const sch = getSchEnv.call(this, schemaKeyRef);
                if (typeof sch == "object")
                    this._cache.delete(sch.schema);
                delete this.schemas[schemaKeyRef];
                delete this.refs[schemaKeyRef];
                return this;
            }
            case "object": {
                const cacheKey = schemaKeyRef;
                this._cache.delete(cacheKey);
                let id = schemaKeyRef[this.opts.schemaId];
                if (id) {
                    id = (0, resolve_1.normalizeId)(id);
                    delete this.schemas[id];
                    delete this.refs[id];
                }
                return this;
            }
            default:
                throw new Error("ajv.removeSchema: invalid parameter");
        }
    }
    // add "vocabulary" - a collection of keywords
    addVocabulary(definitions) {
        for (const def of definitions)
            this.addKeyword(def);
        return this;
    }
    addKeyword(kwdOrDef, def // deprecated
    ) {
        let keyword;
        if (typeof kwdOrDef == "string") {
            keyword = kwdOrDef;
            if (typeof def == "object") {
                this.logger.warn("these parameters are deprecated, see docs for addKeyword");
                def.keyword = keyword;
            }
        }
        else if (typeof kwdOrDef == "object" && def === undefined) {
            def = kwdOrDef;
            keyword = def.keyword;
            if (Array.isArray(keyword) && !keyword.length) {
                throw new Error("addKeywords: keyword must be string or non-empty array");
            }
        }
        else {
            throw new Error("invalid addKeywords parameters");
        }
        checkKeyword.call(this, keyword, def);
        if (!def) {
            (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
            return this;
        }
        keywordMetaschema.call(this, def);
        const definition = {
            ...def,
            type: (0, dataType_1.getJSONTypes)(def.type),
            schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),
        };
        (0, util_1.eachItem)(keyword, definition.type.length === 0
            ? (k) => addRule.call(this, k, definition)
            : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
        return this;
    }
    getKeyword(keyword) {
        const rule = this.RULES.all[keyword];
        return typeof rule == "object" ? rule.definition : !!rule;
    }
    // Remove keyword
    removeKeyword(keyword) {
        // TODO return type should be Ajv
        const { RULES } = this;
        delete RULES.keywords[keyword];
        delete RULES.all[keyword];
        for (const group of RULES.rules) {
            const i = group.rules.findIndex((rule) => rule.keyword === keyword);
            if (i >= 0)
                group.rules.splice(i, 1);
        }
        return this;
    }
    // Add format
    addFormat(name, format) {
        if (typeof format == "string")
            format = new RegExp(format);
        this.formats[name] = format;
        return this;
    }
    errorsText(errors = this.errors, // optional array of validation errors
    { separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar`
    ) {
        if (!errors || errors.length === 0)
            return "No errors";
        return errors
            .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
            .reduce((text, msg) => text + separator + msg);
    }
    $dataMetaSchema(metaSchema, keywordsJsonPointers) {
        const rules = this.RULES.all;
        metaSchema = JSON.parse(JSON.stringify(metaSchema));
        for (const jsonPointer of keywordsJsonPointers) {
            const segments = jsonPointer.split("/").slice(1); // first segment is an empty string
            let keywords = metaSchema;
            for (const seg of segments)
                keywords = keywords[seg];
            for (const key in rules) {
                const rule = rules[key];
                if (typeof rule != "object")
                    continue;
                const { $data } = rule.definition;
                const schema = keywords[key];
                if ($data && schema)
                    keywords[key] = schemaOrData(schema);
            }
        }
        return metaSchema;
    }
    _removeAllSchemas(schemas, regex) {
        for (const keyRef in schemas) {
            const sch = schemas[keyRef];
            if (!regex || regex.test(keyRef)) {
                if (typeof sch == "string") {
                    delete schemas[keyRef];
                }
                else if (sch && !sch.meta) {
                    this._cache.delete(sch.schema);
                    delete schemas[keyRef];
                }
            }
        }
    }
    _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
        let id;
        const { schemaId } = this.opts;
        if (typeof schema == "object") {
            id = schema[schemaId];
        }
        else {
            if (this.opts.jtd)
                throw new Error("schema must be object");
            else if (typeof schema != "boolean")
                throw new Error("schema must be object or boolean");
        }
        let sch = this._cache.get(schema);
        if (sch !== undefined)
            return sch;
        baseId = (0, resolve_1.normalizeId)(id || baseId);
        const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
        sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
        this._cache.set(sch.schema, sch);
        if (addSchema && !baseId.startsWith("#")) {
            // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
            if (baseId)
                this._checkUnique(baseId);
            this.refs[baseId] = sch;
        }
        if (validateSchema)
            this.validateSchema(schema, true);
        return sch;
    }
    _checkUnique(id) {
        if (this.schemas[id] || this.refs[id]) {
            throw new Error(`schema with key or id "${id}" already exists`);
        }
    }
    _compileSchemaEnv(sch) {
        if (sch.meta)
            this._compileMetaSchema(sch);
        else
            compile_1.compileSchema.call(this, sch);
        /* istanbul ignore if */
        if (!sch.validate)
            throw new Error("ajv implementation error");
        return sch.validate;
    }
    _compileMetaSchema(sch) {
        const currentOpts = this.opts;
        this.opts = this._metaOpts;
        try {
            compile_1.compileSchema.call(this, sch);
        }
        finally {
            this.opts = currentOpts;
        }
    }
}
Ajv.ValidationError = validation_error_1.default;
Ajv.MissingRefError = ref_error_1.default;
exports.default = Ajv;
function checkOptions(checkOpts, options, msg, log = "error") {
    for (const key in checkOpts) {
        const opt = key;
        if (opt in options)
            this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
    }
}
function getSchEnv(keyRef) {
    keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line
    return this.schemas[keyRef] || this.refs[keyRef];
}
function addInitialSchemas() {
    const optsSchemas = this.opts.schemas;
    if (!optsSchemas)
        return;
    if (Array.isArray(optsSchemas))
        this.addSchema(optsSchemas);
    else
        for (const key in optsSchemas)
            this.addSchema(optsSchemas[key], key);
}
function addInitialFormats() {
    for (const name in this.opts.formats) {
        const format = this.opts.formats[name];
        if (format)
            this.addFormat(name, format);
    }
}
function addInitialKeywords(defs) {
    if (Array.isArray(defs)) {
        this.addVocabulary(defs);
        return;
    }
    this.logger.warn("keywords option as map is deprecated, pass array");
    for (const keyword in defs) {
        const def = defs[keyword];
        if (!def.keyword)
            def.keyword = keyword;
        this.addKeyword(def);
    }
}
function getMetaSchemaOptions() {
    const metaOpts = { ...this.opts };
    for (const opt of META_IGNORE_OPTIONS)
        delete metaOpts[opt];
    return metaOpts;
}
const noLogs = { log() { }, warn() { }, error() { } };
function getLogger(logger) {
    if (logger === false)
        return noLogs;
    if (logger === undefined)
        return console;
    if (logger.log && logger.warn && logger.error)
        return logger;
    throw new Error("logger must implement log, warn and error methods");
}
const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
function checkKeyword(keyword, def) {
    const { RULES } = this;
    (0, util_1.eachItem)(keyword, (kwd) => {
        if (RULES.keywords[kwd])
            throw new Error(`Keyword ${kwd} is already defined`);
        if (!KEYWORD_NAME.test(kwd))
            throw new Error(`Keyword ${kwd} has invalid name`);
    });
    if (!def)
        return;
    if (def.$data && !("code" in def || "validate" in def)) {
        throw new Error('$data keyword must have "code" or "validate" function');
    }
}
function addRule(keyword, definition, dataType) {
    var _a;
    const post = definition === null || definition === void 0 ? void 0 : definition.post;
    if (dataType && post)
        throw new Error('keyword with "post" flag cannot have "type"');
    const { RULES } = this;
    let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
    if (!ruleGroup) {
        ruleGroup = { type: dataType, rules: [] };
        RULES.rules.push(ruleGroup);
    }
    RULES.keywords[keyword] = true;
    if (!definition)
        return;
    const rule = {
        keyword,
        definition: {
            ...definition,
            type: (0, dataType_1.getJSONTypes)(definition.type),
            schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),
        },
    };
    if (definition.before)
        addBeforeRule.call(this, ruleGroup, rule, definition.before);
    else
        ruleGroup.rules.push(rule);
    RULES.all[keyword] = rule;
    (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
}
function addBeforeRule(ruleGroup, rule, before) {
    const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
    if (i >= 0) {
        ruleGroup.rules.splice(i, 0, rule);
    }
    else {
        ruleGroup.rules.push(rule);
        this.logger.warn(`rule ${before} is not defined`);
    }
}
function keywordMetaschema(def) {
    let { metaSchema } = def;
    if (metaSchema === undefined)
        return;
    if (def.$data && this.opts.$data)
        metaSchema = schemaOrData(metaSchema);
    def.validateSchema = this.compile(metaSchema, true);
}
const $dataRef = {
    $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
};
function schemaOrData(schema) {
    return { anyOf: [schema, $dataRef] };
}
//# sourceMappingURL=core.js.map


code:
import type { AnySchemaObject, SchemaObject, JTDParser } from "./types";
import type { JTDSchemaType, SomeJTDSchemaType, JTDDataType } from "./types/jtd-schema";
import AjvCore, { CurrentOptions } from "./core";
type JTDOptions = CurrentOptions & {
    strict?: never;
    allowMatchingProperties?: never;
    allowUnionTypes?: never;
    validateFormats?: never;
    $data?: never;
    verbose?: boolean;
    $comment?: never;
    formats?: never;
    loadSchema?: never;
    useDefaults?: never;
    coerceTypes?: never;
    next?: never;
    unevaluated?: never;
    dynamicRef?: never;
    meta?: boolean;
    defaultMeta?: never;
    inlineRefs?: boolean;
    loopRequired?: never;
    multipleOfPrecision?: never;
};
export declare class Ajv extends AjvCore {
    constructor(opts?: JTDOptions);
    _addVocabularies(): void;
    _addDefaultMetaSchema(): void;
    defaultMeta(): string | AnySchemaObject | undefined;
    compileSerializer<T = unknown>(schema: SchemaObject): (data: T) => string;
    compileSerializer<T = unknown>(schema: JTDSchemaType<T>): (data: T) => string;
    compileParser<T = unknown>(schema: SchemaObject): JTDParser<T>;
    compileParser<T = unknown>(schema: JTDSchemaType<T>): JTDParser<T>;
    private _compileSerializer;
    private _compileParser;
}
export default Ajv;
export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, ErrorObject, ErrorNoParams, JTDParser, } from "./types";
export { Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions } from "./core";
export { SchemaCxt, SchemaObjCxt } from "./compile";
export { KeywordCxt } from "./compile/validate";
export { JTDErrorObject } from "./vocabularies/jtd";
export { _, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions } from "./compile/codegen";
export { JTDSchemaType, SomeJTDSchemaType, JTDDataType };
export { JTDOptions };
export { default as ValidationError } from "./runtime/validation_error";
export { default as MissingRefError } from "./compile/ref_error";


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
const core_1 = require("./core");
const jtd_1 = require("./vocabularies/jtd");
const jtd_schema_1 = require("./refs/jtd-schema");
const serialize_1 = require("./compile/jtd/serialize");
const parse_1 = require("./compile/jtd/parse");
const META_SCHEMA_ID = "JTD-meta-schema";
class Ajv extends core_1.default {
    constructor(opts = {}) {
        super({
            ...opts,
            jtd: true,
        });
    }
    _addVocabularies() {
        super._addVocabularies();
        this.addVocabulary(jtd_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        if (!this.opts.meta)
            return;
        this.addMetaSchema(jtd_schema_1.default, META_SCHEMA_ID, false);
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
    compileSerializer(schema) {
        const sch = this._addSchema(schema);
        return sch.serialize || this._compileSerializer(sch);
    }
    compileParser(schema) {
        const sch = this._addSchema(schema);
        return (sch.parse || this._compileParser(sch));
    }
    _compileSerializer(sch) {
        serialize_1.default.call(this, sch, sch.schema.definitions || {});
        /* istanbul ignore if */
        if (!sch.serialize)
            throw new Error("ajv implementation error");
        return sch.serialize;
    }
    _compileParser(sch) {
        parse_1.default.call(this, sch, sch.schema.definitions || {});
        /* istanbul ignore if */
        if (!sch.parse)
            throw new Error("ajv implementation error");
        return sch.parse;
    }
}
exports.Ajv = Ajv;
module.exports = exports = Ajv;
module.exports.Ajv = Ajv;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceMappingURL=jtd.js.map


description: Meta-schema for $data reference (JSON AnySchema extension proposal)

type: object

type: string

format: relative-json-pointer

format: json-pointer


code:
import type Ajv from "../../core";
export default function addMetaSchema2019(this: Ajv, $data?: boolean): Ajv;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const metaSchema = require("./schema.json");
const applicator = require("./meta/applicator.json");
const content = require("./meta/content.json");
const core = require("./meta/core.json");
const format = require("./meta/format.json");
const metadata = require("./meta/meta-data.json");
const validation = require("./meta/validation.json");
const META_SUPPORT_DATA = ["/properties"];
function addMetaSchema2019($data) {
    ;
    [
        metaSchema,
        applicator,
        content,
        core,
        with$data(this, format),
        metadata,
        with$data(this, validation),
    ].forEach((sch) => this.addMetaSchema(sch, undefined, false));
    return this;
    function with$data(ajv, sch) {
        return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch;
    }
}
exports.default = addMetaSchema2019;
//# sourceMappingURL=index.js.map


title: Applicator vocabulary meta-schema

type: object boolean

$ref: #/$defs/schemaArray

format: regex

type: array


title: Content vocabulary meta-schema


title: Core vocabulary meta-schema

format: uri-reference

$comment: Non-empty fragments not allowed.

format: uri

type: boolean


title: Format vocabulary meta-schema


title: Meta-data vocabulary meta-schema


title: Validation vocabulary meta-schema

type: number

$ref: #/$defs/nonNegativeInteger

$ref: #/$defs/stringArray

$ref: #/$defs/simpleTypes

type: integer

enum: array boolean integer null number object string


title: Core and Validation specifications meta-schema

$ref: meta/core

$ref: meta/applicator

$ref: meta/validation

$ref: meta/meta-data

$ref: meta/format

$ref: meta/content

$comment: While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.

$comment: "dependencies" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to "dependentSchemas" and "dependentRequired"

$ref: meta/validation#/$defs/stringArray


code:
import type Ajv from "../../core";
export default function addMetaSchema2020(this: Ajv, $data?: boolean): Ajv;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const metaSchema = require("./schema.json");
const applicator = require("./meta/applicator.json");
const unevaluated = require("./meta/unevaluated.json");
const content = require("./meta/content.json");
const core = require("./meta/core.json");
const format = require("./meta/format-annotation.json");
const metadata = require("./meta/meta-data.json");
const validation = require("./meta/validation.json");
const META_SUPPORT_DATA = ["/properties"];
function addMetaSchema2020($data) {
    ;
    [
        metaSchema,
        applicator,
        unevaluated,
        content,
        core,
        with$data(this, format),
        metadata,
        with$data(this, validation),
    ].forEach((sch) => this.addMetaSchema(sch, undefined, false));
    return this;
    function with$data(ajv, sch) {
        return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch;
    }
}
exports.default = addMetaSchema2020;
//# sourceMappingURL=index.js.map


$dynamicAnchor: meta

title: Applicator vocabulary meta-schema

$dynamicRef: #meta


title: Content vocabulary meta-schema


title: Core vocabulary meta-schema

$ref: #/$defs/uriReferenceString

$ref: #/$defs/uriString

$ref: #/$defs/anchorString


title: Format vocabulary meta-schema for annotation results


title: Meta-data vocabulary meta-schema


title: Unevaluated applicator vocabulary meta-schema


title: Validation vocabulary meta-schema


$ref: meta/unevaluated

$ref: meta/format-annotation

$comment: This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.

$comment: "definitions" has been replaced by "$defs".

$comment: "dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.

$comment: "$recursiveAnchor" has been replaced by "$dynamicAnchor".

$ref: meta/core#/$defs/anchorString

$comment: "$recursiveRef" has been replaced by "$dynamicRef".

$ref: meta/core#/$defs/uriReferenceString


title: Core schema meta-schema

$ref: #/definitions/nonNegativeInteger

$ref: #/definitions/schemaArray

$ref: #/definitions/stringArray

$ref: #/definitions/simpleTypes


title: Core schema meta-schema


title: Meta-schema for the security assessment of JSON Schemas

description: If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data

description: prevent slow validation of large property names

description: prevent slow validation of large non-scalar arrays

enum: object array

description: prevent slow pattern matching of large strings

description: prevent slow format validation of large strings


code:
import { SchemaObject } from "../types";
declare const jtdMetaSchema: SchemaObject;
export default jtdMetaSchema;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const shared = (root) => {
    const sch = {
        nullable: { type: "boolean" },
        metadata: {
            optionalProperties: {
                union: { elements: { ref: "schema" } },
            },
            additionalProperties: true,
        },
    };
    if (root)
        sch.definitions = { values: { ref: "schema" } };
    return sch;
};
const emptyForm = (root) => ({
    optionalProperties: shared(root),
});
const refForm = (root) => ({
    properties: {
        ref: { type: "string" },
    },
    optionalProperties: shared(root),
});
const typeForm = (root) => ({
    properties: {
        type: {
            enum: [
                "boolean",
                "timestamp",
                "string",
                "float32",
                "float64",
                "int8",
                "uint8",
                "int16",
                "uint16",
                "int32",
                "uint32",
            ],
        },
    },
    optionalProperties: shared(root),
});
const enumForm = (root) => ({
    properties: {
        enum: { elements: { type: "string" } },
    },
    optionalProperties: shared(root),
});
const elementsForm = (root) => ({
    properties: {
        elements: { ref: "schema" },
    },
    optionalProperties: shared(root),
});
const propertiesForm = (root) => ({
    properties: {
        properties: { values: { ref: "schema" } },
    },
    optionalProperties: {
        optionalProperties: { values: { ref: "schema" } },
        additionalProperties: { type: "boolean" },
        ...shared(root),
    },
});
const optionalPropertiesForm = (root) => ({
    properties: {
        optionalProperties: { values: { ref: "schema" } },
    },
    optionalProperties: {
        additionalProperties: { type: "boolean" },
        ...shared(root),
    },
});
const discriminatorForm = (root) => ({
    properties: {
        discriminator: { type: "string" },
        mapping: {
            values: {
                metadata: {
                    union: [propertiesForm(false), optionalPropertiesForm(false)],
                },
            },
        },
    },
    optionalProperties: shared(root),
});
const valuesForm = (root) => ({
    properties: {
        values: { ref: "schema" },
    },
    optionalProperties: shared(root),
});
const schema = (root) => ({
    metadata: {
        union: [
            emptyForm,
            refForm,
            typeForm,
            enumForm,
            elementsForm,
            propertiesForm,
            optionalPropertiesForm,
            discriminatorForm,
            valuesForm,
        ].map((s) => s(root)),
    },
});
const jtdMetaSchema = {
    definitions: {
        schema: schema(false),
    },
    ...schema(true),
};
exports.default = jtdMetaSchema;
//# sourceMappingURL=jtd-schema.js.map


code:
import * as equal from "fast-deep-equal";
type Equal = typeof equal & {
    code: string;
};
declare const _default: Equal;
export default _default;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// https://github.com/ajv-validator/ajv/issues/889
const equal = require("fast-deep-equal");
equal.code = 'require("ajv/dist/runtime/equal").default';
exports.default = equal;
//# sourceMappingURL=equal.js.map


code:
export declare function parseJson(s: string, pos: number): unknown;
export declare namespace parseJson {
    var message: string | undefined;
    var position: number;
    var code: string;
}
export declare function parseJsonNumber(s: string, pos: number, maxDigits?: number): number | undefined;
export declare namespace parseJsonNumber {
    var message: string | undefined;
    var position: number;
    var code: string;
}
export declare function parseJsonString(s: string, pos: number): string | undefined;
export declare namespace parseJsonString {
    var message: string | undefined;
    var position: number;
    var code: string;
}


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseJsonString = exports.parseJsonNumber = exports.parseJson = void 0;
const rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/;
function parseJson(s, pos) {
    let endPos;
    parseJson.message = undefined;
    let matches;
    if (pos)
        s = s.slice(pos);
    try {
        parseJson.position = pos + s.length;
        return JSON.parse(s);
    }
    catch (e) {
        matches = rxParseJson.exec(e.message);
        if (!matches) {
            parseJson.message = "unexpected end";
            return undefined;
        }
        endPos = +matches[1];
        const c = s[endPos];
        s = s.slice(0, endPos);
        parseJson.position = pos + endPos;
        try {
            return JSON.parse(s);
        }
        catch (e1) {
            parseJson.message = `unexpected token ${c}`;
            return undefined;
        }
    }
}
exports.parseJson = parseJson;
parseJson.message = undefined;
parseJson.position = 0;
parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson';
function parseJsonNumber(s, pos, maxDigits) {
    let numStr = "";
    let c;
    parseJsonNumber.message = undefined;
    if (s[pos] === "-") {
        numStr += "-";
        pos++;
    }
    if (s[pos] === "0") {
        numStr += "0";
        pos++;
    }
    else {
        if (!parseDigits(maxDigits)) {
            errorMessage();
            return undefined;
        }
    }
    if (maxDigits) {
        parseJsonNumber.position = pos;
        return +numStr;
    }
    if (s[pos] === ".") {
        numStr += ".";
        pos++;
        if (!parseDigits()) {
            errorMessage();
            return undefined;
        }
    }
    if (((c = s[pos]), c === "e" || c === "E")) {
        numStr += "e";
        pos++;
        if (((c = s[pos]), c === "+" || c === "-")) {
            numStr += c;
            pos++;
        }
        if (!parseDigits()) {
            errorMessage();
            return undefined;
        }
    }
    parseJsonNumber.position = pos;
    return +numStr;
    function parseDigits(maxLen) {
        let digit = false;
        while (((c = s[pos]), c >= "0" && c <= "9" && (maxLen === undefined || maxLen-- > 0))) {
            digit = true;
            numStr += c;
            pos++;
        }
        return digit;
    }
    function errorMessage() {
        parseJsonNumber.position = pos;
        parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end";
    }
}
exports.parseJsonNumber = parseJsonNumber;
parseJsonNumber.message = undefined;
parseJsonNumber.position = 0;
parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber';
const escapedChars = {
    b: "\b",
    f: "\f",
    n: "\n",
    r: "\r",
    t: "\t",
    '"': '"',
    "/": "/",
    "\\": "\\",
};
const CODE_A = "a".charCodeAt(0);
const CODE_0 = "0".charCodeAt(0);
function parseJsonString(s, pos) {
    let str = "";
    let c;
    parseJsonString.message = undefined;
    // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition
    while (true) {
        c = s[pos++];
        if (c === '"')
            break;
        if (c === "\\") {
            c = s[pos];
            if (c in escapedChars) {
                str += escapedChars[c];
                pos++;
            }
            else if (c === "u") {
                pos++;
                let count = 4;
                let code = 0;
                while (count--) {
                    code <<= 4;
                    c = s[pos];
                    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
                    if (c === undefined) {
                        errorMessage("unexpected end");
                        return undefined;
                    }
                    c = c.toLowerCase();
                    if (c >= "a" && c <= "f") {
                        code += c.charCodeAt(0) - CODE_A + 10;
                    }
                    else if (c >= "0" && c <= "9") {
                        code += c.charCodeAt(0) - CODE_0;
                    }
                    else {
                        errorMessage(`unexpected token ${c}`);
                        return undefined;
                    }
                    pos++;
                }
                str += String.fromCharCode(code);
            }
            else {
                errorMessage(`unexpected token ${c}`);
                return undefined;
            }
            // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
        }
        else if (c === undefined) {
            errorMessage("unexpected end");
            return undefined;
        }
        else {
            if (c.charCodeAt(0) >= 0x20) {
                str += c;
            }
            else {
                errorMessage(`unexpected token ${c}`);
                return undefined;
            }
        }
    }
    parseJsonString.position = pos;
    return str;
    function errorMessage(msg) {
        parseJsonString.position = pos;
        parseJsonString.message = msg;
    }
}
exports.parseJsonString = parseJsonString;
parseJsonString.message = undefined;
parseJsonString.position = 0;
parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString';
//# sourceMappingURL=parseJson.js.map


code:
declare function quote(s: string): string;
declare namespace quote {
    var code: string;
}
export default quote;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const rxEscapable =
// eslint-disable-next-line no-control-regex, no-misleading-character-class
/[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
const escaped = {
    "\b": "\\b",
    "\t": "\\t",
    "\n": "\\n",
    "\f": "\\f",
    "\r": "\\r",
    '"': '\\"',
    "\\": "\\\\",
};
function quote(s) {
    rxEscapable.lastIndex = 0;
    return ('"' +
        (rxEscapable.test(s)
            ? s.replace(rxEscapable, (a) => {
                const c = escaped[a];
                return typeof c === "string"
                    ? c
                    : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
            })
            : s) +
        '"');
}
exports.default = quote;
quote.code = 'require("ajv/dist/runtime/quote").default';
//# sourceMappingURL=quote.js.map


code:
import * as re2 from "re2";
type Re2 = typeof re2 & {
    code: string;
};
declare const _default: Re2;
export default _default;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const re2 = require("re2");
re2.code = 'require("ajv/dist/runtime/re2").default';
exports.default = re2;
//# sourceMappingURL=re2.js.map


code:
declare function validTimestamp(str: string, allowDate: boolean): boolean;
declare namespace validTimestamp {
    var code: string;
}
export default validTimestamp;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const DT_SEPARATOR = /t|\s/i;
const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i;
const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function validTimestamp(str, allowDate) {
    // http://tools.ietf.org/html/rfc3339#section-5.6
    const dt = str.split(DT_SEPARATOR);
    return ((dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) ||
        (allowDate && dt.length === 1 && validDate(dt[0])));
}
exports.default = validTimestamp;
function validDate(str) {
    const matches = DATE.exec(str);
    if (!matches)
        return false;
    const y = +matches[1];
    const m = +matches[2];
    const d = +matches[3];
    return (m >= 1 &&
        m <= 12 &&
        d >= 1 &&
        (d <= DAYS[m] ||
            // leap year: https://tools.ietf.org/html/rfc3339#appendix-C
            (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0))));
}
function validTime(str) {
    const matches = TIME.exec(str);
    if (!matches)
        return false;
    const hr = +matches[1];
    const min = +matches[2];
    const sec = +matches[3];
    const tzH = +(matches[4] || 0);
    const tzM = +(matches[5] || 0);
    return ((hr <= 23 && min <= 59 && sec <= 59) ||
        // leap second
        (hr - tzH === 23 && min - tzM === 59 && sec === 60));
}
validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default';
//# sourceMappingURL=timestamp.js.map


code:
declare function ucs2length(str: string): number;
declare namespace ucs2length {
    var code: string;
}
export default ucs2length;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
function ucs2length(str) {
    const len = str.length;
    let length = 0;
    let pos = 0;
    let value;
    while (pos < len) {
        length++;
        value = str.charCodeAt(pos++);
        if (value >= 0xd800 && value <= 0xdbff && pos < len) {
            // high surrogate, and there is a next character
            value = str.charCodeAt(pos);
            if ((value & 0xfc00) === 0xdc00)
                pos++; // low surrogate
        }
    }
    return length;
}
exports.default = ucs2length;
ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
//# sourceMappingURL=ucs2length.js.map


code:
import * as uri from "uri-js";
type URI = typeof uri & {
    code: string;
};
declare const _default: URI;
export default _default;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const uri = require("uri-js");
uri.code = 'require("ajv/dist/runtime/uri").default';
exports.default = uri;
//# sourceMappingURL=uri.js.map


code:
import type { ErrorObject } from "../types";
export default class ValidationError extends Error {
    readonly errors: Partial<ErrorObject>[];
    readonly ajv: true;
    readonly validation: true;
    constructor(errors: Partial<ErrorObject>[]);
}


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class ValidationError extends Error {
    constructor(errors) {
        super("validation failed");
        this.errors = errors;
        this.ajv = this.validation = true;
    }
}
exports.default = ValidationError;
//# sourceMappingURL=validation_error.js.map


code:
import type AjvCore from "../core";
import type { AnyValidateFunction } from "../types";
declare function standaloneCode(ajv: AjvCore, refsOrFunc?: {
    [K in string]?: string;
} | AnyValidateFunction): string;
export default standaloneCode;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const scope_1 = require("../compile/codegen/scope");
const code_1 = require("../compile/codegen/code");
function standaloneCode(ajv, refsOrFunc) {
    if (!ajv.opts.code.source) {
        throw new Error("moduleCode: ajv instance must have code.source option");
    }
    const { _n } = ajv.scope.opts;
    return typeof refsOrFunc == "function"
        ? funcExportCode(refsOrFunc.source)
        : refsOrFunc !== undefined
            ? multiExportsCode(refsOrFunc, getValidate)
            : multiExportsCode(ajv.schemas, (sch) => sch.meta ? undefined : ajv.compile(sch.schema));
    function getValidate(id) {
        const v = ajv.getSchema(id);
        if (!v)
            throw new Error(`moduleCode: no schema with id ${id}`);
        return v;
    }
    function funcExportCode(source) {
        const usedValues = {};
        const n = source === null || source === void 0 ? void 0 : source.validateName;
        const vCode = validateCode(usedValues, source);
        if (ajv.opts.code.esm) {
            // Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value
            return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}`;
        }
        return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}`;
    }
    function multiExportsCode(schemas, getValidateFunc) {
        var _a;
        const usedValues = {};
        let code = (0, code_1._) `"use strict";`;
        for (const name in schemas) {
            const v = getValidateFunc(schemas[name]);
            if (v) {
                const vCode = validateCode(usedValues, v.source);
                const exportSyntax = ajv.opts.code.esm
                    ? (0, code_1._) `export const ${(0, code_1.getEsmExportName)(name)}`
                    : (0, code_1._) `exports${(0, code_1.getProperty)(name)}`;
                code = (0, code_1._) `${code}${_n}${exportSyntax} = ${(_a = v.source) === null || _a === void 0 ? void 0 : _a.validateName};${_n}${vCode}`;
            }
        }
        return `${code}`;
    }
    function validateCode(usedValues, s) {
        if (!s)
            throw new Error('moduleCode: function does not have "source" property');
        if (usedState(s.validateName) === scope_1.UsedValueState.Completed)
            return code_1.nil;
        setUsedState(s.validateName, scope_1.UsedValueState.Started);
        const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode);
        const code = new code_1._Code(`${scopeCode}${_n}${s.validateCode}`);
        return s.evaluated ? (0, code_1._) `${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code;
        function refValidateCode(n) {
            var _a;
            const vRef = (_a = n.value) === null || _a === void 0 ? void 0 : _a.ref;
            if (n.prefix === "validate" && typeof vRef == "function") {
                const v = vRef;
                return validateCode(usedValues, v.source);
            }
            else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") {
                const { validate, validateName } = vRef;
                if (!validateName)
                    throw new Error("ajv internal error");
                const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const;
                const wrapper = (0, code_1._) `${def} ${n} = {validate: ${validateName}};`;
                if (usedState(validateName) === scope_1.UsedValueState.Started)
                    return wrapper;
                const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source);
                return (0, code_1._) `${wrapper}${_n}${vCode}`;
            }
            return undefined;
        }
        function usedState(name) {
            var _a;
            return (_a = usedValues[name.prefix]) === null || _a === void 0 ? void 0 : _a.get(name);
        }
        function setUsedState(name, state) {
            const { prefix } = name;
            const names = (usedValues[prefix] = usedValues[prefix] || new Map());
            names.set(name, state);
        }
    }
}
module.exports = exports = standaloneCode;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = standaloneCode;
//# sourceMappingURL=index.js.map


code:
import Ajv, { AnySchema, AnyValidateFunction, ErrorObject } from "../core";
export default class AjvPack {
    readonly ajv: Ajv;
    errors?: ErrorObject[] | null;
    constructor(ajv: Ajv);
    validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown>;
    compile<T = unknown>(schema: AnySchema, meta?: boolean): AnyValidateFunction<T>;
    getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined;
    private getStandalone;
    addSchema(...args: Parameters<typeof Ajv.prototype.addSchema>): AjvPack;
    addKeyword(...args: Parameters<typeof Ajv.prototype.addKeyword>): AjvPack;
}


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("../core");
const _1 = require(".");
const requireFromString = require("require-from-string");
class AjvPack {
    constructor(ajv) {
        this.ajv = ajv;
    }
    validate(schemaKeyRef, data) {
        return core_1.default.prototype.validate.call(this, schemaKeyRef, data);
    }
    compile(schema, meta) {
        return this.getStandalone(this.ajv.compile(schema, meta));
    }
    getSchema(keyRef) {
        const v = this.ajv.getSchema(keyRef);
        if (!v)
            return undefined;
        return this.getStandalone(v);
    }
    getStandalone(v) {
        return requireFromString((0, _1.default)(this.ajv, v));
    }
    addSchema(...args) {
        this.ajv.addSchema.call(this.ajv, ...args);
        return this;
    }
    addKeyword(...args) {
        this.ajv.addKeyword.call(this.ajv, ...args);
        return this;
    }
}
exports.default = AjvPack;
//# sourceMappingURL=instance.js.map


code:
import * as URI from "uri-js";
import type { CodeGen, Code, Name, ScopeValueSets, ValueScopeName } from "../compile/codegen";
import type { SchemaEnv, SchemaCxt, SchemaObjCxt } from "../compile";
import type { JSONType } from "../compile/rules";
import type { KeywordCxt } from "../compile/validate";
import type Ajv from "../core";
interface _SchemaObject {
    id?: string;
    $id?: string;
    $schema?: string;
    [x: string]: any;
}
export interface SchemaObject extends _SchemaObject {
    id?: string;
    $id?: string;
    $schema?: string;
    $async?: false;
    [x: string]: any;
}
export interface AsyncSchema extends _SchemaObject {
    $async: true;
}
export type AnySchemaObject = SchemaObject | AsyncSchema;
export type Schema = SchemaObject | boolean;
export type AnySchema = Schema | AsyncSchema;
export type SchemaMap = {
    [Key in string]?: AnySchema;
};
export interface SourceCode {
    validateName: ValueScopeName;
    validateCode: string;
    scopeValues: ScopeValueSets;
    evaluated?: Code;
}
export interface DataValidationCxt<T extends string | number = string | number> {
    instancePath: string;
    parentData: {
        [K in T]: any;
    };
    parentDataProperty: T;
    rootData: Record<string, any> | any[];
    dynamicAnchors: {
        [Ref in string]?: ValidateFunction;
    };
}
export interface ValidateFunction<T = unknown> {
    (this: Ajv | any, data: any, dataCxt?: DataValidationCxt): data is T;
    errors?: null | ErrorObject[];
    evaluated?: Evaluated;
    schema: AnySchema;
    schemaEnv: SchemaEnv;
    source?: SourceCode;
}
export interface JTDParser<T = unknown> {
    (json: string): T | undefined;
    message?: string;
    position?: number;
}
export type EvaluatedProperties = {
    [K in string]?: true;
} | true;
export type EvaluatedItems = number | true;
export interface Evaluated {
    props?: EvaluatedProperties;
    items?: EvaluatedItems;
    dynamicProps: boolean;
    dynamicItems: boolean;
}
export interface AsyncValidateFunction<T = unknown> extends ValidateFunction<T> {
    (...args: Parameters<ValidateFunction<T>>): Promise<T>;
    $async: true;
}
export type AnyValidateFunction<T = any> = ValidateFunction<T> | AsyncValidateFunction<T>;
export interface ErrorObject<K extends string = string, P = Record<string, any>, S = unknown> {
    keyword: K;
    instancePath: string;
    schemaPath: string;
    params: P;
    propertyName?: string;
    message?: string;
    schema?: S;
    parentSchema?: AnySchemaObject;
    data?: unknown;
}
export type ErrorNoParams<K extends string, S = unknown> = ErrorObject<K, Record<string, never>, S>;
interface _KeywordDef {
    keyword: string | string[];
    type?: JSONType | JSONType[];
    schemaType?: JSONType | JSONType[];
    allowUndefined?: boolean;
    $data?: boolean;
    implements?: string[];
    before?: string;
    post?: boolean;
    metaSchema?: AnySchemaObject;
    validateSchema?: AnyValidateFunction;
    dependencies?: string[];
    error?: KeywordErrorDefinition;
    $dataError?: KeywordErrorDefinition;
}
export interface CodeKeywordDefinition extends _KeywordDef {
    code: (cxt: KeywordCxt, ruleType?: string) => void;
    trackErrors?: boolean;
}
export type MacroKeywordFunc = (schema: any, parentSchema: AnySchemaObject, it: SchemaCxt) => AnySchema;
export type CompileKeywordFunc = (schema: any, parentSchema: AnySchemaObject, it: SchemaObjCxt) => DataValidateFunction;
export interface DataValidateFunction {
    (...args: Parameters<ValidateFunction>): boolean | Promise<any>;
    errors?: Partial<ErrorObject>[];
}
export interface SchemaValidateFunction {
    (schema: any, data: any, parentSchema?: AnySchemaObject, dataCxt?: DataValidationCxt): boolean | Promise<any>;
    errors?: Partial<ErrorObject>[];
}
export interface FuncKeywordDefinition extends _KeywordDef {
    validate?: SchemaValidateFunction | DataValidateFunction;
    compile?: CompileKeywordFunc;
    schema?: boolean;
    modifying?: boolean;
    async?: boolean;
    valid?: boolean;
    errors?: boolean | "full";
}
export interface MacroKeywordDefinition extends FuncKeywordDefinition {
    macro: MacroKeywordFunc;
}
export type KeywordDefinition = CodeKeywordDefinition | FuncKeywordDefinition | MacroKeywordDefinition;
export type AddedKeywordDefinition = KeywordDefinition & {
    type: JSONType[];
    schemaType: JSONType[];
};
export interface KeywordErrorDefinition {
    message: string | Code | ((cxt: KeywordErrorCxt) => string | Code);
    params?: Code | ((cxt: KeywordErrorCxt) => Code);
}
export type Vocabulary = (KeywordDefinition | string)[];
export interface KeywordErrorCxt {
    gen: CodeGen;
    keyword: string;
    data: Name;
    $data?: string | false;
    schema: any;
    parentSchema?: AnySchemaObject;
    schemaCode: Code | number | boolean;
    schemaValue: Code | number | boolean;
    schemaType?: JSONType[];
    errsCount?: Name;
    params: KeywordCxtParams;
    it: SchemaCxt;
}
export type KeywordCxtParams = {
    [P in string]?: Code | string | number;
};
export type FormatValidator<T extends string | number> = (data: T) => boolean;
export type FormatCompare<T extends string | number> = (data1: T, data2: T) => number | undefined;
export type AsyncFormatValidator<T extends string | number> = (data: T) => Promise<boolean>;
export interface FormatDefinition<T extends string | number> {
    type?: T extends string ? "string" | undefined : "number";
    validate: FormatValidator<T> | (T extends string ? string | RegExp : never);
    async?: false | undefined;
    compare?: FormatCompare<T>;
}
export interface AsyncFormatDefinition<T extends string | number> {
    type?: T extends string ? "string" | undefined : "number";
    validate: AsyncFormatValidator<T>;
    async: true;
    compare?: FormatCompare<T>;
}
export type AddedFormat = true | RegExp | FormatValidator<string> | FormatDefinition<string> | FormatDefinition<number> | AsyncFormatDefinition<string> | AsyncFormatDefinition<number>;
export type Format = AddedFormat | string;
export interface RegExpEngine {
    (pattern: string, u: string): RegExpLike;
    code: string;
}
export interface RegExpLike {
    test: (s: string) => boolean;
}
export interface UriResolver {
    parse(uri: string): URI.URIComponents;
    resolve(base: string, path: string): string;
    serialize(component: URI.URIComponents): string;
}
export {};


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=index.js.map


code:
type StrictNullChecksWrapper<Name extends string, Type> = undefined extends null ? `strictNullChecks must be true in tsconfig to use ${Name}` : Type;
type UnionToIntersection<U> = (U extends any ? (_: U) => void : never) extends (_: infer I) => void ? I : never;
export type SomeJSONSchema = UncheckedJSONSchemaType<Known, true>;
type UncheckedPartialSchema<T> = Partial<UncheckedJSONSchemaType<T, true>>;
export type PartialSchema<T> = StrictNullChecksWrapper<"PartialSchema", UncheckedPartialSchema<T>>;
type JSONType<T extends string, IsPartial extends boolean> = IsPartial extends true ? T | undefined : T;
interface NumberKeywords {
    minimum?: number;
    maximum?: number;
    exclusiveMinimum?: number;
    exclusiveMaximum?: number;
    multipleOf?: number;
    format?: string;
}
interface StringKeywords {
    minLength?: number;
    maxLength?: number;
    pattern?: string;
    format?: string;
}
type UncheckedJSONSchemaType<T, IsPartial extends boolean> = (// these two unions allow arbitrary unions of types
{
    anyOf: readonly UncheckedJSONSchemaType<T, IsPartial>[];
} | {
    oneOf: readonly UncheckedJSONSchemaType<T, IsPartial>[];
} | ({
    type: readonly (T extends number ? JSONType<"number" | "integer", IsPartial> : T extends string ? JSONType<"string", IsPartial> : T extends boolean ? JSONType<"boolean", IsPartial> : never)[];
} & UnionToIntersection<T extends number ? NumberKeywords : T extends string ? StringKeywords : T extends boolean ? {} : never>) | ((T extends number ? {
    type: JSONType<"number" | "integer", IsPartial>;
} & NumberKeywords : T extends string ? {
    type: JSONType<"string", IsPartial>;
} & StringKeywords : T extends boolean ? {
    type: JSONType<"boolean", IsPartial>;
} : T extends readonly [any, ...any[]] ? {
    type: JSONType<"array", IsPartial>;
    items: {
        readonly [K in keyof T]-?: UncheckedJSONSchemaType<T[K], false> & Nullable<T[K]>;
    } & {
        length: T["length"];
    };
    minItems: T["length"];
} & ({
    maxItems: T["length"];
} | {
    additionalItems: false;
}) : T extends readonly any[] ? {
    type: JSONType<"array", IsPartial>;
    items: UncheckedJSONSchemaType<T[0], false>;
    contains?: UncheckedPartialSchema<T[0]>;
    minItems?: number;
    maxItems?: number;
    minContains?: number;
    maxContains?: number;
    uniqueItems?: true;
    additionalItems?: never;
} : T extends Record<string, any> ? {
    type: JSONType<"object", IsPartial>;
    additionalProperties?: boolean | UncheckedJSONSchemaType<T[string], false>;
    unevaluatedProperties?: boolean | UncheckedJSONSchemaType<T[string], false>;
    properties?: IsPartial extends true ? Partial<UncheckedPropertiesSchema<T>> : UncheckedPropertiesSchema<T>;
    patternProperties?: Record<string, UncheckedJSONSchemaType<T[string], false>>;
    propertyNames?: Omit<UncheckedJSONSchemaType<string, false>, "type"> & {
        type?: "string";
    };
    dependencies?: {
        [K in keyof T]?: Readonly<(keyof T)[]> | UncheckedPartialSchema<T>;
    };
    dependentRequired?: {
        [K in keyof T]?: Readonly<(keyof T)[]>;
    };
    dependentSchemas?: {
        [K in keyof T]?: UncheckedPartialSchema<T>;
    };
    minProperties?: number;
    maxProperties?: number;
} & (IsPartial extends true ? {
    required: Readonly<(keyof T)[]>;
} : [UncheckedRequiredMembers<T>] extends [never] ? {
    required?: Readonly<UncheckedRequiredMembers<T>[]>;
} : {
    required: Readonly<UncheckedRequiredMembers<T>[]>;
}) : T extends null ? {
    type: JSONType<"null", IsPartial>;
    nullable: true;
} : never) & {
    allOf?: Readonly<UncheckedPartialSchema<T>[]>;
    anyOf?: Readonly<UncheckedPartialSchema<T>[]>;
    oneOf?: Readonly<UncheckedPartialSchema<T>[]>;
    if?: UncheckedPartialSchema<T>;
    then?: UncheckedPartialSchema<T>;
    else?: UncheckedPartialSchema<T>;
    not?: UncheckedPartialSchema<T>;
})) & {
    [keyword: string]: any;
    $id?: string;
    $ref?: string;
    $defs?: Record<string, UncheckedJSONSchemaType<Known, true>>;
    definitions?: Record<string, UncheckedJSONSchemaType<Known, true>>;
};
export type JSONSchemaType<T> = StrictNullChecksWrapper<"JSONSchemaType", UncheckedJSONSchemaType<T, false>>;
type Known = {
    [key: string]: Known;
} | [Known, ...Known[]] | Known[] | number | string | boolean | null;
type UncheckedPropertiesSchema<T> = {
    [K in keyof T]-?: (UncheckedJSONSchemaType<T[K], false> & Nullable<T[K]>) | {
        $ref: string;
    };
};
export type PropertiesSchema<T> = StrictNullChecksWrapper<"PropertiesSchema", UncheckedPropertiesSchema<T>>;
type UncheckedRequiredMembers<T> = {
    [K in keyof T]-?: undefined extends T[K] ? never : K;
}[keyof T];
export type RequiredMembers<T> = StrictNullChecksWrapper<"RequiredMembers", UncheckedRequiredMembers<T>>;
type Nullable<T> = undefined extends T ? {
    nullable: true;
    const?: null;
    enum?: Readonly<(T | null)[]>;
    default?: T | null;
} : {
    nullable?: false;
    const?: T;
    enum?: Readonly<T[]>;
    default?: T;
};
export {};


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=json-schema.js.map


code:
/** numeric strings */
type NumberType = "float32" | "float64" | "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32";
/** string strings */
type StringType = "string" | "timestamp";
/** Generic JTD Schema without inference of the represented type */
export type SomeJTDSchemaType = (// ref
{
    ref: string;
} | {
    type: NumberType | StringType | "boolean";
} | {
    enum: string[];
} | {
    elements: SomeJTDSchemaType;
} | {
    values: SomeJTDSchemaType;
} | {
    properties: Record<string, SomeJTDSchemaType>;
    optionalProperties?: Record<string, SomeJTDSchemaType>;
    additionalProperties?: boolean;
} | {
    properties?: Record<string, SomeJTDSchemaType>;
    optionalProperties: Record<string, SomeJTDSchemaType>;
    additionalProperties?: boolean;
} | {
    discriminator: string;
    mapping: Record<string, SomeJTDSchemaType>;
} | {}) & {
    nullable?: boolean;
    metadata?: Record<string, unknown>;
    definitions?: Record<string, SomeJTDSchemaType>;
};
/** required keys of an object, not undefined */
type RequiredKeys<T> = {
    [K in keyof T]-?: undefined extends T[K] ? never : K;
}[keyof T];
/** optional or undifined-able keys of an object */
type OptionalKeys<T> = {
    [K in keyof T]-?: undefined extends T[K] ? K : never;
}[keyof T];
/** type is true if T is a union type */
type IsUnion_<T, U extends T = T> = false extends (T extends unknown ? ([U] extends [T] ? false : true) : never) ? false : true;
type IsUnion<T> = IsUnion_<T>;
/** type is true if T is identically E */
type TypeEquality<T, E> = [T] extends [E] ? ([E] extends [T] ? true : false) : false;
/** type is true if T or null is identically E or null*/
type NullTypeEquality<T, E> = TypeEquality<T | null, E | null>;
/** gets only the string literals of a type or null if a type isn't a string literal */
type EnumString<T> = [T] extends [never] ? null : T extends string ? string extends T ? null : T : null;
/** true if type is a union of string literals */
type IsEnum<T> = null extends EnumString<T> ? false : true;
/** true only if all types are array types (not tuples) */
type IsElements<T> = false extends IsUnion<T> ? [T] extends [readonly unknown[]] ? undefined extends T[0.5] ? false : true : false : false;
/** true if the the type is a values type */
type IsValues<T> = false extends IsUnion<T> ? TypeEquality<keyof T, string> : false;
/** true if type is a properties type and Union is false, or type is a discriminator type and Union is true */
type IsRecord<T, Union extends boolean> = Union extends IsUnion<T> ? null extends EnumString<keyof T> ? false : true : false;
/** true if type represents an empty record */
type IsEmptyRecord<T> = [T] extends [Record<string, never>] ? [T] extends [never] ? false : true : false;
/** actual schema */
export type JTDSchemaType<T, D extends Record<string, unknown> = Record<string, never>> = (// refs - where null wasn't specified, must match exactly
(null extends EnumString<keyof D> ? never : ({
    [K in keyof D]: [T] extends [D[K]] ? {
        ref: K;
    } : never;
}[keyof D] & {
    nullable?: false;
}) | (null extends T ? {
    [K in keyof D]: [Exclude<T, null>] extends [Exclude<D[K], null>] ? {
        ref: K;
    } : never;
}[keyof D] & {
    nullable: true;
} : never)) | (unknown extends T ? {
    nullable?: boolean;
} : never) | ((true extends NullTypeEquality<T, number> ? {
    type: NumberType;
} : true extends NullTypeEquality<T, boolean> ? {
    type: "boolean";
} : true extends NullTypeEquality<T, string> ? {
    type: StringType;
} : true extends NullTypeEquality<T, Date> ? {
    type: "timestamp";
} : true extends IsEnum<Exclude<T, null>> ? {
    enum: EnumString<Exclude<T, null>>[];
} : true extends IsElements<Exclude<T, null>> ? T extends readonly (infer E)[] ? {
    elements: JTDSchemaType<E, D>;
} : never : true extends IsEmptyRecord<Exclude<T, null>> ? {
    properties: Record<string, never>;
    optionalProperties?: Record<string, never>;
} | {
    optionalProperties: Record<string, never>;
} : true extends IsValues<Exclude<T, null>> ? T extends Record<string, infer V> ? {
    values: JTDSchemaType<V, D>;
} : never : true extends IsRecord<Exclude<T, null>, false> ? ([RequiredKeys<Exclude<T, null>>] extends [never] ? {
    properties?: Record<string, never>;
} : {
    properties: {
        [K in RequiredKeys<T>]: JTDSchemaType<T[K], D>;
    };
}) & ([OptionalKeys<Exclude<T, null>>] extends [never] ? {
    optionalProperties?: Record<string, never>;
} : {
    optionalProperties: {
        [K in OptionalKeys<T>]: JTDSchemaType<Exclude<T[K], undefined>, D>;
    };
}) & {
    additionalProperties?: boolean;
} : true extends IsRecord<Exclude<T, null>, true> ? {
    [K in keyof Exclude<T, null>]-?: Exclude<T, null>[K] extends string ? {
        discriminator: K;
        mapping: {
            [M in Exclude<T, null>[K]]: JTDSchemaType<Omit<T extends Record<K, M> ? T : never, K>, D>;
        };
    } : never;
}[keyof Exclude<T, null>] : never) & (null extends T ? {
    nullable: true;
} : {
    nullable?: false;
}))) & {
    metadata?: Record<string, unknown>;
    definitions?: {
        [K in keyof D]: JTDSchemaType<D[K], D>;
    };
};
type JTDDataDef<S, D extends Record<string, unknown>> = // ref
(S extends {
    ref: string;
} ? D extends {
    [K in S["ref"]]: infer V;
} ? JTDDataDef<V, D> : never : S extends {
    type: NumberType;
} ? number : S extends {
    type: "boolean";
} ? boolean : S extends {
    type: "string";
} ? string : S extends {
    type: "timestamp";
} ? string | Date : S extends {
    enum: readonly (infer E)[];
} ? string extends E ? never : [E] extends [string] ? E : never : S extends {
    elements: infer E;
} ? JTDDataDef<E, D>[] : S extends {
    properties: Record<string, unknown>;
    optionalProperties?: Record<string, unknown>;
    additionalProperties?: boolean;
} ? {
    -readonly [K in keyof S["properties"]]-?: JTDDataDef<S["properties"][K], D>;
} & {
    -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef<S["optionalProperties"][K], D>;
} & ([S["additionalProperties"]] extends [true] ? Record<string, unknown> : unknown) : S extends {
    properties?: Record<string, unknown>;
    optionalProperties: Record<string, unknown>;
    additionalProperties?: boolean;
} ? {
    -readonly [K in keyof S["properties"]]-?: JTDDataDef<S["properties"][K], D>;
} & {
    -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef<S["optionalProperties"][K], D>;
} & ([S["additionalProperties"]] extends [true] ? Record<string, unknown> : unknown) : S extends {
    values: infer V;
} ? Record<string, JTDDataDef<V, D>> : S extends {
    discriminator: infer M;
    mapping: Record<string, unknown>;
} ? [M] extends [string] ? {
    [K in keyof S["mapping"]]: JTDDataDef<S["mapping"][K], D> & {
        [KM in M]: K;
    };
}[keyof S["mapping"]] : never : unknown) | (S extends {
    nullable: true;
} ? null : never);
export type JTDDataType<S> = S extends {
    definitions: Record<string, unknown>;
} ? JTDDataDef<S, S["definitions"]> : JTDDataDef<S, Record<string, never>>;
export {};


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=jtd-schema.js.map


code:
import type { CodeKeywordDefinition, ErrorObject, AnySchema } from "../../types";
import type { KeywordCxt } from "../../compile/validate";
export type AdditionalItemsError = ErrorObject<"additionalItems", {
    limit: number;
}, AnySchema>;
declare const def: CodeKeywordDefinition;
export declare function validateAdditionalItems(cxt: KeywordCxt, items: AnySchema[]): void;
export default def;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateAdditionalItems = void 0;
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
    keyword: "additionalItems",
    type: "array",
    schemaType: ["boolean", "object"],
    before: "uniqueItems",
    error,
    code(cxt) {
        const { parentSchema, it } = cxt;
        const { items } = parentSchema;
        if (!Array.isArray(items)) {
            (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
            return;
        }
        validateAdditionalItems(cxt, items);
    },
};
function validateAdditionalItems(cxt, items) {
    const { gen, schema, data, keyword, it } = cxt;
    it.items = true;
    const len = gen.const("len", (0, codegen_1._) `${data}.length`);
    if (schema === false) {
        cxt.setParams({ len: items.length });
        cxt.pass((0, codegen_1._) `${len} <= ${items.length}`);
    }
    else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
        const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var
        gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
        cxt.ok(valid);
    }
    function validateItems(valid) {
        gen.forRange("i", items.length, len, (i) => {
            cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
            if (!it.allErrors)
                gen.if((0, codegen_1.not)(valid), () => gen.break());
        });
    }
}
exports.validateAdditionalItems = validateAdditionalItems;
exports.default = def;
//# sourceMappingURL=additionalItems.js.map


code:
import type { CodeKeywordDefinition, AddedKeywordDefinition, ErrorObject, AnySchema } from "../../types";
export type AdditionalPropertiesError = ErrorObject<"additionalProperties", {
    additionalProperty: string;
}, AnySchema>;
declare const def: CodeKeywordDefinition & AddedKeywordDefinition;
export default def;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const util_1 = require("../../compile/util");
const error = {
    message: "must NOT have additional properties",
    params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`,
};
const def = {
    keyword: "additionalProperties",
    type: ["object"],
    schemaType: ["boolean", "object"],
    allowUndefined: true,
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it } = cxt;
        /* istanbul ignore if */
        if (!errsCount)
            throw new Error("ajv implementation error");
        const { allErrors, opts } = it;
        it.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
            return;
        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
        checkAdditionalProperties();
        cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
        function checkAdditionalProperties() {
            gen.forIn("key", data, (key) => {
                if (!props.length && !patProps.length)
                    additionalPropertyCode(key);
                else
                    gen.if(isAdditional(key), () => additionalPropertyCode(key));
            });
        }
        function isAdditional(key) {
            let definedProp;
            if (props.length > 8) {
                // TODO maybe an option instead of hard-coded 8?
                const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
                definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
            }
            else if (props.length) {
                definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`));
            }
            else {
                definedProp = codegen_1.nil;
            }
            if (patProps.length) {
                definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
            }
            return (0, codegen_1.not)(definedProp);
        }
        function deleteAdditional(key) {
            gen.code((0, codegen_1._) `delete ${data}[${key}]`);
        }
        function additionalPropertyCode(key) {
            if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) {
                deleteAdditional(key);
                return;
            }
            if (schema === false) {
                cxt.setParams({ additionalProperty: key });
                cxt.error();
                if (!allErrors)
                    gen.break();
                return;
            }
            if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
                const valid = gen.name("valid");
                if (opts.removeAdditional === "failing") {
                    applyAdditionalSchema(key, valid, false);
                    gen.if((0, codegen_1.not)(valid), () => {
                        cxt.reset();
                        deleteAdditional(key);
                    });
                }
                else {
                    applyAdditionalSchema(key, valid);
                    if (!allErrors)
                        gen.if((0, codegen_1.not)(valid), () => gen.break());
                }
            }
        }
        function applyAdditionalSchema(key, valid, errors) {
            const subschema = {
                keyword: "additionalProperties",
                dataProp: key,
                dataPropType: util_1.Type.Str,
            };
            if (errors === false) {
                Object.assign(subschema, {
                    compositeRule: true,
                    createErrors: false,
                    allErrors: false,
                });
            }
            cxt.subschema(subschema, valid);
        }
    },
};
exports.default = def;
//# sourceMappingURL=additionalProperties.js.map


code:
import type { CodeKeywordDefinition } from "../../types";
declare const def: CodeKeywordDefinition;
export default def;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: "allOf",
    schemaType: "array",
    code(cxt) {
        const { gen, schema, it } = cxt;
        /* istanbul ignore if */
        if (!Array.isArray(schema))
            throw new Error("ajv implementation error");
        const valid = gen.name("valid");
        schema.forEach((sch, i) => {
            if ((0, util_1.alwaysValidSchema)(it, sch))
                return;
            const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
            cxt.ok(valid);
            cxt.mergeEvaluated(schCxt);
        });
    },
};
exports.default = def;
//# sourceMappingURL=allOf.js.map


code:
import type { CodeKeywordDefinition, ErrorNoParams, AnySchema } from "../../types";
export type AnyOfError = ErrorNoParams<"anyOf", AnySchema[]>;
declare const def: CodeKeywordDefinition;
export default def;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const def = {
    keyword: "anyOf",
    schemaType: "array",
    trackErrors: true,
    code: code_1.validateUnion,
    error: { message: "must match a schema in anyOf" },
};
exports.default = def;
//# sourceMappingURL=anyOf.js.map


code:
import type { CodeKeywordDefinition, ErrorObject, AnySchema } from "../../types";
export type ContainsError = ErrorObject<"contains", {
    minContains: number;
    maxContains?: number;
}, AnySchema>;
declare const def: CodeKeywordDefinition;
export default def;