code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const sequences = {};
const DEFAULTS = {
    timestamp: () => () => Date.now(),
    datetime: () => () => new Date().toISOString(),
    date: () => () => new Date().toISOString().slice(0, 10),
    time: () => () => new Date().toISOString().slice(11),
    random: () => () => Math.random(),
    randomint: (args) => {
        var _a;
        const max = (_a = args === null || args === void 0 ? void 0 : args.max) !== null && _a !== void 0 ? _a : 2;
        return () => Math.floor(Math.random() * max);
    },
    seq: (args) => {
        var _a;
        const name = (_a = args === null || args === void 0 ? void 0 : args.name) !== null && _a !== void 0 ? _a : "";
        sequences[name] || (sequences[name] = 0);
        return () => sequences[name]++;
    },
};
const getDef = Object.assign(_getDef, { DEFAULTS });
function _getDef() {
    return {
        keyword: "dynamicDefaults",
        type: "object",
        schemaType: ["string", "object"],
        modifying: true,
        valid: true,
        compile(schema, _parentSchema, it) {
            if (!it.opts.useDefaults || it.compositeRule)
                return () => true;
            const fs = {};
            for (const key in schema)
                fs[key] = getDefault(schema[key]);
            const empty = it.opts.useDefaults === "empty";
            return (data) => {
                for (const prop in schema) {
                    if (data[prop] === undefined || (empty && (data[prop] === null || data[prop] === ""))) {
                        data[prop] = fs[prop]();
                    }
                }
                return true;
            };
        },
        metaSchema: {
            type: "object",
            additionalProperties: {
                anyOf: [
                    { type: "string" },
                    {
                        type: "object",
                        additionalProperties: false,
                        required: ["func", "args"],
                        properties: {
                            func: { type: "string" },
                            args: { type: "object" },
                        },
                    },
                ],
            },
        },
    };
}
function getDefault(d) {
    return typeof d == "object" ? getObjDefault(d) : getStrDefault(d);
}
function getObjDefault({ func, args }) {
    const def = DEFAULTS[func];
    assertDefined(func, def);
    return def(args);
}
function getStrDefault(d = "") {
    const def = DEFAULTS[d];
    assertDefined(d, def);
    return def();
}
function assertDefined(name, def) {
    if (!def)
        throw new Error(`invalid "dynamicDefaults" keyword property value: ${name}`);
}
exports.default = getDef;
module.exports = getDef;
//# sourceMappingURL=dynamicDefaults.js.map


code:
import type { MacroKeywordDefinition } from "ajv";
import type { GetDefinition } from "./_types";
declare const getDef: GetDefinition<MacroKeywordDefinition>;
export default getDef;

license: mit


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const _range_1 = __importDefault(require("./_range"));
const getDef = (0, _range_1.default)("exclusiveRange");
exports.default = getDef;
module.exports = getDef;
//# sourceMappingURL=exclusiveRange.js.map


code:
import type { Vocabulary, ErrorNoParams } from "ajv";
import type { DefinitionOptions } from "./_types";
import { PatternRequiredError } from "./patternRequired";
import { SelectError } from "./select";
export default function ajvKeywords(opts?: DefinitionOptions): Vocabulary;
export declare type AjvKeywordsError = PatternRequiredError | SelectError | ErrorNoParams<"range" | "exclusiveRange" | "anyRequired" | "oneRequired" | "allRequired" | "deepProperties" | "deepRequired" | "dynamicDefaults" | "instanceof" | "prohibited" | "regexp" | "transform" | "uniqueItemProperties">;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const typeof_1 = __importDefault(require("./typeof"));
const instanceof_1 = __importDefault(require("./instanceof"));
const range_1 = __importDefault(require("./range"));
const exclusiveRange_1 = __importDefault(require("./exclusiveRange"));
const regexp_1 = __importDefault(require("./regexp"));
const transform_1 = __importDefault(require("./transform"));
const uniqueItemProperties_1 = __importDefault(require("./uniqueItemProperties"));
const allRequired_1 = __importDefault(require("./allRequired"));
const anyRequired_1 = __importDefault(require("./anyRequired"));
const oneRequired_1 = __importDefault(require("./oneRequired"));
const patternRequired_1 = __importDefault(require("./patternRequired"));
const prohibited_1 = __importDefault(require("./prohibited"));
const deepProperties_1 = __importDefault(require("./deepProperties"));
const deepRequired_1 = __importDefault(require("./deepRequired"));
const dynamicDefaults_1 = __importDefault(require("./dynamicDefaults"));
const select_1 = __importDefault(require("./select"));
const definitions = [
    typeof_1.default,
    instanceof_1.default,
    range_1.default,
    exclusiveRange_1.default,
    regexp_1.default,
    transform_1.default,
    uniqueItemProperties_1.default,
    allRequired_1.default,
    anyRequired_1.default,
    oneRequired_1.default,
    patternRequired_1.default,
    prohibited_1.default,
    deepProperties_1.default,
    deepRequired_1.default,
    dynamicDefaults_1.default,
];
function ajvKeywords(opts) {
    return definitions.map((d) => d(opts)).concat((0, select_1.default)(opts));
}
exports.default = ajvKeywords;
module.exports = ajvKeywords;
//# sourceMappingURL=index.js.map


code:
import type { FuncKeywordDefinition } from "ajv";
declare type Constructor = new (...args: any[]) => any;
declare const CONSTRUCTORS: Record<string, Constructor | undefined>;
declare const getDef: (() => FuncKeywordDefinition) & {
    CONSTRUCTORS: typeof CONSTRUCTORS;
};
export default getDef;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const CONSTRUCTORS = {
    Object,
    Array,
    Function,
    Number,
    String,
    Date,
    RegExp,
};
/* istanbul ignore else */
if (typeof Buffer != "undefined")
    CONSTRUCTORS.Buffer = Buffer;
/* istanbul ignore else */
if (typeof Promise != "undefined")
    CONSTRUCTORS.Promise = Promise;
const getDef = Object.assign(_getDef, { CONSTRUCTORS });
function _getDef() {
    return {
        keyword: "instanceof",
        schemaType: ["string", "array"],
        compile(schema) {
            if (typeof schema == "string") {
                const C = getConstructor(schema);
                return (data) => data instanceof C;
            }
            if (Array.isArray(schema)) {
                const constructors = schema.map(getConstructor);
                return (data) => {
                    for (const C of constructors) {
                        if (data instanceof C)
                            return true;
                    }
                    return false;
                };
            }
            /* istanbul ignore next */
            throw new Error("ajv implementation error");
        },
        metaSchema: {
            anyOf: [{ type: "string" }, { type: "array", items: { type: "string" } }],
        },
    };
}
function getConstructor(c) {
    const C = CONSTRUCTORS[c];
    if (C)
        return C;
    throw new Error(`invalid "instanceof" keyword value ${c}`);
}
exports.default = getDef;
module.exports = getDef;
//# sourceMappingURL=instanceof.js.map


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const _required_1 = __importDefault(require("./_required"));
const getDef = (0, _required_1.default)("oneRequired");
exports.default = getDef;
module.exports = getDef;
//# sourceMappingURL=oneRequired.js.map


code:
import type { CodeKeywordDefinition, ErrorObject } from "ajv";
export declare type PatternRequiredError = ErrorObject<"patternRequired", {
    missingPattern: string;
}>;
export default function getDef(): CodeKeywordDefinition;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("ajv/dist/compile/codegen");
const _util_1 = require("./_util");
const error = {
    message: ({ params: { missingPattern } }) => (0, codegen_1.str) `should have property matching pattern '${missingPattern}'`,
    params: ({ params: { missingPattern } }) => (0, codegen_1._) `{missingPattern: ${missingPattern}}`,
};
function getDef() {
    return {
        keyword: "patternRequired",
        type: "object",
        schemaType: "array",
        error,
        code(cxt) {
            const { gen, schema, data } = cxt;
            if (schema.length === 0)
                return;
            const valid = gen.let("valid", true);
            for (const pat of schema)
                validateProperties(pat);
            function validateProperties(pattern) {
                const matched = gen.let("matched", false);
                gen.forIn("key", data, (key) => {
                    gen.assign(matched, (0, codegen_1._) `${(0, _util_1.usePattern)(cxt, pattern)}.test(${key})`);
                    gen.if(matched, () => gen.break());
                });
                cxt.setParams({ missingPattern: pattern });
                gen.assign(valid, (0, codegen_1.and)(valid, matched));
                cxt.pass(valid);
            }
        },
        metaSchema: {
            type: "array",
            items: { type: "string", format: "regex" },
            uniqueItems: true,
        },
    };
}
exports.default = getDef;
module.exports = getDef;
//# sourceMappingURL=patternRequired.js.map


code:
import type { MacroKeywordDefinition } from "ajv";
export default function getDef(): MacroKeywordDefinition;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function getDef() {
    return {
        keyword: "prohibited",
        type: "object",
        schemaType: "array",
        macro: function (schema) {
            if (schema.length === 0)
                return true;
            if (schema.length === 1)
                return { not: { required: schema } };
            return { not: { anyOf: schema.map((p) => ({ required: [p] })) } };
        },
        metaSchema: {
            type: "array",
            items: { type: "string" },
        },
    };
}
exports.default = getDef;
module.exports = getDef;
//# sourceMappingURL=prohibited.js.map


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const _range_1 = __importDefault(require("./_range"));
const getDef = (0, _range_1.default)("range");
exports.default = getDef;
module.exports = getDef;
//# sourceMappingURL=range.js.map


code:
import type { CodeKeywordDefinition } from "ajv";
export default function getDef(): CodeKeywordDefinition;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("ajv/dist/compile/codegen");
const _util_1 = require("./_util");
const regexpMetaSchema = {
    type: "object",
    properties: {
        pattern: { type: "string" },
        flags: { type: "string", nullable: true },
    },
    required: ["pattern"],
    additionalProperties: false,
};
const metaRegexp = /^\/(.*)\/([gimuy]*)$/;
function getDef() {
    return {
        keyword: "regexp",
        type: "string",
        schemaType: ["string", "object"],
        code(cxt) {
            const { data, schema } = cxt;
            const regx = getRegExp(schema);
            cxt.pass((0, codegen_1._) `${regx}.test(${data})`);
            function getRegExp(sch) {
                if (typeof sch == "object")
                    return (0, _util_1.usePattern)(cxt, sch.pattern, sch.flags);
                const rx = metaRegexp.exec(sch);
                if (rx)
                    return (0, _util_1.usePattern)(cxt, rx[1], rx[2]);
                throw new Error("cannot parse string into RegExp");
            }
        },
        metaSchema: {
            anyOf: [{ type: "string" }, regexpMetaSchema],
        },
    };
}
exports.default = getDef;
module.exports = getDef;
//# sourceMappingURL=regexp.js.map


code:
import type { KeywordDefinition, ErrorObject } from "ajv";
import type { DefinitionOptions } from "./_types";
export declare type SelectError = ErrorObject<"select", {
    failingCase?: string;
    failingDefault?: true;
}>;
export default function getDef(opts?: DefinitionOptions): KeywordDefinition[];


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("ajv/dist/compile/codegen");
const _util_1 = require("./_util");
const error = {
    message: ({ params: { schemaProp } }) => schemaProp
        ? (0, codegen_1.str) `should match case "${schemaProp}" schema`
        : (0, codegen_1.str) `should match default case schema`,
    params: ({ params: { schemaProp } }) => schemaProp ? (0, codegen_1._) `{failingCase: ${schemaProp}}` : (0, codegen_1._) `{failingDefault: true}`,
};
function getDef(opts) {
    const metaSchema = (0, _util_1.metaSchemaRef)(opts);
    return [
        {
            keyword: "select",
            schemaType: ["string", "number", "boolean", "null"],
            $data: true,
            error,
            dependencies: ["selectCases"],
            code(cxt) {
                const { gen, schemaCode, parentSchema } = cxt;
                cxt.block$data(codegen_1.nil, () => {
                    const valid = gen.let("valid", true);
                    const schValid = gen.name("_valid");
                    const value = gen.const("value", (0, codegen_1._) `${schemaCode} === null ? "null" : ${schemaCode}`);
                    gen.if(false); // optimizer should remove it from generated code
                    for (const schemaProp in parentSchema.selectCases) {
                        cxt.setParams({ schemaProp });
                        gen.elseIf((0, codegen_1._) `"" + ${value} == ${schemaProp}`); // intentional ==, to match numbers and booleans
                        const schCxt = cxt.subschema({ keyword: "selectCases", schemaProp }, schValid);
                        cxt.mergeEvaluated(schCxt, codegen_1.Name);
                        gen.assign(valid, schValid);
                    }
                    gen.else();
                    if (parentSchema.selectDefault !== undefined) {
                        cxt.setParams({ schemaProp: undefined });
                        const schCxt = cxt.subschema({ keyword: "selectDefault" }, schValid);
                        cxt.mergeEvaluated(schCxt, codegen_1.Name);
                        gen.assign(valid, schValid);
                    }
                    gen.endIf();
                    cxt.pass(valid);
                });
            },
        },
        {
            keyword: "selectCases",
            dependencies: ["select"],
            metaSchema: {
                type: "object",
                additionalProperties: metaSchema,
            },
        },
        {
            keyword: "selectDefault",
            dependencies: ["select", "selectCases"],
            metaSchema,
        },
    ];
}
exports.default = getDef;
module.exports = getDef;
//# sourceMappingURL=select.js.map


code:
import type { CodeKeywordDefinition } from "ajv";
declare type TransformName = "trimStart" | "trimEnd" | "trimLeft" | "trimRight" | "trim" | "toLowerCase" | "toUpperCase" | "toEnumCase";
interface TransformConfig {
    hash: Record<string, string | undefined>;
}
declare type Transform = (s: string, cfg?: TransformConfig) => string;
declare const transform: {
    [key in TransformName]: Transform;
};
declare const getDef: (() => CodeKeywordDefinition) & {
    transform: typeof transform;
};
export default getDef;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("ajv/dist/compile/codegen");
const transform = {
    trimStart: (s) => s.trimStart(),
    trimEnd: (s) => s.trimEnd(),
    trimLeft: (s) => s.trimStart(),
    trimRight: (s) => s.trimEnd(),
    trim: (s) => s.trim(),
    toLowerCase: (s) => s.toLowerCase(),
    toUpperCase: (s) => s.toUpperCase(),
    toEnumCase: (s, cfg) => (cfg === null || cfg === void 0 ? void 0 : cfg.hash[configKey(s)]) || s,
};
const getDef = Object.assign(_getDef, { transform });
function _getDef() {
    return {
        keyword: "transform",
        schemaType: "array",
        before: "enum",
        code(cxt) {
            const { gen, data, schema, parentSchema, it } = cxt;
            const { parentData, parentDataProperty } = it;
            const tNames = schema;
            if (!tNames.length)
                return;
            let cfg;
            if (tNames.includes("toEnumCase")) {
                const config = getEnumCaseCfg(parentSchema);
                cfg = gen.scopeValue("obj", { ref: config, code: (0, codegen_1.stringify)(config) });
            }
            gen.if((0, codegen_1._) `typeof ${data} == "string" && ${parentData} !== undefined`, () => {
                gen.assign(data, transformExpr(tNames.slice()));
                gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, data);
            });
            function transformExpr(ts) {
                if (!ts.length)
                    return data;
                const t = ts.pop();
                if (!(t in transform))
                    throw new Error(`transform: unknown transformation ${t}`);
                const func = gen.scopeValue("func", {
                    ref: transform[t],
                    code: (0, codegen_1._) `require("ajv-keywords/dist/definitions/transform").transform${(0, codegen_1.getProperty)(t)}`,
                });
                const arg = transformExpr(ts);
                return cfg && t === "toEnumCase" ? (0, codegen_1._) `${func}(${arg}, ${cfg})` : (0, codegen_1._) `${func}(${arg})`;
            }
        },
        metaSchema: {
            type: "array",
            items: { type: "string", enum: Object.keys(transform) },
        },
    };
}
function getEnumCaseCfg(parentSchema) {
    // build hash table to enum values
    const cfg = { hash: {} };
    // requires `enum` in the same schema as transform
    if (!parentSchema.enum)
        throw new Error('transform: "toEnumCase" requires "enum"');
    for (const v of parentSchema.enum) {
        if (typeof v !== "string")
            continue;
        const k = configKey(v);
        // requires all `enum` values have unique keys
        if (cfg.hash[k]) {
            throw new Error('transform: "toEnumCase" requires all lowercased "enum" values to be unique');
        }
        cfg.hash[k] = v;
    }
    return cfg;
}
function configKey(s) {
    return s.toLowerCase();
}
exports.default = getDef;
module.exports = getDef;
//# sourceMappingURL=transform.js.map


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("ajv/dist/compile/codegen");
const TYPES = ["undefined", "string", "number", "object", "function", "boolean", "symbol"];
function getDef() {
    return {
        keyword: "typeof",
        schemaType: ["string", "array"],
        code(cxt) {
            const { data, schema, schemaValue } = cxt;
            cxt.fail(typeof schema == "string"
                ? (0, codegen_1._) `typeof ${data} != ${schema}`
                : (0, codegen_1._) `${schemaValue}.indexOf(typeof ${data}) < 0`);
        },
        metaSchema: {
            anyOf: [
                { type: "string", enum: TYPES },
                { type: "array", items: { type: "string", enum: TYPES } },
            ],
        },
    };
}
exports.default = getDef;
module.exports = getDef;
//# sourceMappingURL=typeof.js.map


code:
import type { FuncKeywordDefinition } from "ajv";
export default function getDef(): FuncKeywordDefinition;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const equal = require("fast-deep-equal");
const SCALAR_TYPES = ["number", "integer", "string", "boolean", "null"];
function getDef() {
    return {
        keyword: "uniqueItemProperties",
        type: "array",
        schemaType: "array",
        compile(keys, parentSchema) {
            const scalar = getScalarKeys(keys, parentSchema);
            return (data) => {
                if (data.length <= 1)
                    return true;
                for (let k = 0; k < keys.length; k++) {
                    const key = keys[k];
                    if (scalar[k]) {
                        const hash = {};
                        for (const x of data) {
                            if (!x || typeof x != "object")
                                continue;
                            let p = x[key];
                            if (p && typeof p == "object")
                                continue;
                            if (typeof p == "string")
                                p = '"' + p;
                            if (hash[p])
                                return false;
                            hash[p] = true;
                        }
                    }
                    else {
                        for (let i = data.length; i--;) {
                            const x = data[i];
                            if (!x || typeof x != "object")
                                continue;
                            for (let j = i; j--;) {
                                const y = data[j];
                                if (y && typeof y == "object" && equal(x[key], y[key]))
                                    return false;
                            }
                        }
                    }
                }
                return true;
            };
        },
        metaSchema: {
            type: "array",
            items: { type: "string" },
        },
    };
}
exports.default = getDef;
function getScalarKeys(keys, schema) {
    return keys.map((key) => {
        var _a, _b, _c;
        const t = (_c = (_b = (_a = schema.items) === null || _a === void 0 ? void 0 : _a.properties) === null || _b === void 0 ? void 0 : _b[key]) === null || _c === void 0 ? void 0 : _c.type;
        return Array.isArray(t)
            ? !t.includes("object") && !t.includes("array")
            : SCALAR_TYPES.includes(t);
    });
}
module.exports = getDef;
//# sourceMappingURL=uniqueItemProperties.js.map


code:
import type { Plugin } from "ajv";
export { AjvKeywordsError } from "./definitions";
declare const ajvKeywords: Plugin<string | string[]>;
export default ajvKeywords;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const keywords_1 = __importDefault(require("./keywords"));
const ajvKeywords = (ajv, keyword) => {
    if (Array.isArray(keyword)) {
        for (const k of keyword)
            get(k)(ajv);
        return ajv;
    }
    if (keyword) {
        get(keyword)(ajv);
        return ajv;
    }
    for (keyword in keywords_1.default)
        get(keyword)(ajv);
    return ajv;
};
ajvKeywords.get = get;
function get(keyword) {
    const defFunc = keywords_1.default[keyword];
    if (!defFunc)
        throw new Error("Unknown keyword " + keyword);
    return defFunc;
}
exports.default = ajvKeywords;
module.exports = ajvKeywords;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
module.exports.default = ajvKeywords;
//# sourceMappingURL=index.js.map


code:
import type { Plugin } from "ajv";
declare const allRequired: Plugin<undefined>;
export default allRequired;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const allRequired_1 = __importDefault(require("../definitions/allRequired"));
const allRequired = (ajv) => ajv.addKeyword((0, allRequired_1.default)());
exports.default = allRequired;
module.exports = allRequired;
//# sourceMappingURL=allRequired.js.map


code:
import type { Plugin } from "ajv";
declare const anyRequired: Plugin<undefined>;
export default anyRequired;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const anyRequired_1 = __importDefault(require("../definitions/anyRequired"));
const anyRequired = (ajv) => ajv.addKeyword((0, anyRequired_1.default)());
exports.default = anyRequired;
module.exports = anyRequired;
//# sourceMappingURL=anyRequired.js.map


code:
import type { Plugin } from "ajv";
import type { DefinitionOptions } from "../definitions/_types";
declare const deepProperties: Plugin<DefinitionOptions>;
export default deepProperties;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const deepProperties_1 = __importDefault(require("../definitions/deepProperties"));
const deepProperties = (ajv, opts) => ajv.addKeyword((0, deepProperties_1.default)(opts));
exports.default = deepProperties;
module.exports = deepProperties;
//# sourceMappingURL=deepProperties.js.map


code:
import type { Plugin } from "ajv";
declare const deepRequired: Plugin<undefined>;
export default deepRequired;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const deepRequired_1 = __importDefault(require("../definitions/deepRequired"));
const deepRequired = (ajv) => ajv.addKeyword((0, deepRequired_1.default)());
exports.default = deepRequired;
module.exports = deepRequired;
//# sourceMappingURL=deepRequired.js.map


code:
import type { Plugin } from "ajv";
declare const dynamicDefaults: Plugin<undefined>;
export default dynamicDefaults;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const dynamicDefaults_1 = __importDefault(require("../definitions/dynamicDefaults"));
const dynamicDefaults = (ajv) => ajv.addKeyword((0, dynamicDefaults_1.default)());
exports.default = dynamicDefaults;
module.exports = dynamicDefaults;
//# sourceMappingURL=dynamicDefaults.js.map


code:
import type { Plugin } from "ajv";
declare const exclusiveRange: Plugin<undefined>;
export default exclusiveRange;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const exclusiveRange_1 = __importDefault(require("../definitions/exclusiveRange"));
const exclusiveRange = (ajv) => ajv.addKeyword((0, exclusiveRange_1.default)());
exports.default = exclusiveRange;
module.exports = exclusiveRange;
//# sourceMappingURL=exclusiveRange.js.map


code:
import type { Plugin } from "ajv";
declare const ajvKeywords: Record<string, Plugin<any> | undefined>;
export default ajvKeywords;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const typeof_1 = __importDefault(require("./typeof"));
const instanceof_1 = __importDefault(require("./instanceof"));
const range_1 = __importDefault(require("./range"));
const exclusiveRange_1 = __importDefault(require("./exclusiveRange"));
const regexp_1 = __importDefault(require("./regexp"));
const transform_1 = __importDefault(require("./transform"));
const uniqueItemProperties_1 = __importDefault(require("./uniqueItemProperties"));
const allRequired_1 = __importDefault(require("./allRequired"));
const anyRequired_1 = __importDefault(require("./anyRequired"));
const oneRequired_1 = __importDefault(require("./oneRequired"));
const patternRequired_1 = __importDefault(require("./patternRequired"));
const prohibited_1 = __importDefault(require("./prohibited"));
const deepProperties_1 = __importDefault(require("./deepProperties"));
const deepRequired_1 = __importDefault(require("./deepRequired"));
const dynamicDefaults_1 = __importDefault(require("./dynamicDefaults"));
const select_1 = __importDefault(require("./select"));
// TODO type
const ajvKeywords = {
    typeof: typeof_1.default,
    instanceof: instanceof_1.default,
    range: range_1.default,
    exclusiveRange: exclusiveRange_1.default,
    regexp: regexp_1.default,
    transform: transform_1.default,
    uniqueItemProperties: uniqueItemProperties_1.default,
    allRequired: allRequired_1.default,
    anyRequired: anyRequired_1.default,
    oneRequired: oneRequired_1.default,
    patternRequired: patternRequired_1.default,
    prohibited: prohibited_1.default,
    deepProperties: deepProperties_1.default,
    deepRequired: deepRequired_1.default,
    dynamicDefaults: dynamicDefaults_1.default,
    select: select_1.default,
};
exports.default = ajvKeywords;
module.exports = ajvKeywords;
//# sourceMappingURL=index.js.map


code:
import type { Plugin } from "ajv";
declare const instanceofPlugin: Plugin<undefined>;
export default instanceofPlugin;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const instanceof_1 = __importDefault(require("../definitions/instanceof"));
const instanceofPlugin = (ajv) => ajv.addKeyword((0, instanceof_1.default)());
exports.default = instanceofPlugin;
module.exports = instanceofPlugin;
//# sourceMappingURL=instanceof.js.map


code:
import type { Plugin } from "ajv";
declare const oneRequired: Plugin<undefined>;
export default oneRequired;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const oneRequired_1 = __importDefault(require("../definitions/oneRequired"));
const oneRequired = (ajv) => ajv.addKeyword((0, oneRequired_1.default)());
exports.default = oneRequired;
module.exports = oneRequired;
//# sourceMappingURL=oneRequired.js.map


code:
import type { Plugin } from "ajv";
declare const patternRequired: Plugin<undefined>;
export default patternRequired;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const patternRequired_1 = __importDefault(require("../definitions/patternRequired"));
const patternRequired = (ajv) => ajv.addKeyword((0, patternRequired_1.default)());
exports.default = patternRequired;
module.exports = patternRequired;
//# sourceMappingURL=patternRequired.js.map


code:
import type { Plugin } from "ajv";
declare const prohibited: Plugin<undefined>;
export default prohibited;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const prohibited_1 = __importDefault(require("../definitions/prohibited"));
const prohibited = (ajv) => ajv.addKeyword((0, prohibited_1.default)());
exports.default = prohibited;
module.exports = prohibited;
//# sourceMappingURL=prohibited.js.map


code:
import type { Plugin } from "ajv";
declare const range: Plugin<undefined>;
export default range;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const range_1 = __importDefault(require("../definitions/range"));
const range = (ajv) => ajv.addKeyword((0, range_1.default)());
exports.default = range;
module.exports = range;
//# sourceMappingURL=range.js.map


code:
import type { Plugin } from "ajv";
declare const regexp: Plugin<undefined>;
export default regexp;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const regexp_1 = __importDefault(require("../definitions/regexp"));
const regexp = (ajv) => ajv.addKeyword((0, regexp_1.default)());
exports.default = regexp;
module.exports = regexp;
//# sourceMappingURL=regexp.js.map


code:
import type { Plugin } from "ajv";
import type { DefinitionOptions } from "../definitions/_types";
declare const select: Plugin<DefinitionOptions>;
export default select;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const select_1 = __importDefault(require("../definitions/select"));
const select = (ajv, opts) => {
    (0, select_1.default)(opts).forEach((d) => ajv.addKeyword(d));
    return ajv;
};
exports.default = select;
module.exports = select;
//# sourceMappingURL=select.js.map


code:
import type { Plugin } from "ajv";
declare const transform: Plugin<undefined>;
export default transform;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const transform_1 = __importDefault(require("../definitions/transform"));
const transform = (ajv) => ajv.addKeyword((0, transform_1.default)());
exports.default = transform;
module.exports = transform;
//# sourceMappingURL=transform.js.map


code:
import type { Plugin } from "ajv";
declare const typeofPlugin: Plugin<undefined>;
export default typeofPlugin;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const typeof_1 = __importDefault(require("../definitions/typeof"));
const typeofPlugin = (ajv) => ajv.addKeyword((0, typeof_1.default)());
exports.default = typeofPlugin;
module.exports = typeofPlugin;
//# sourceMappingURL=typeof.js.map


code:
import type { Plugin } from "ajv";
declare const uniqueItemProperties: Plugin<undefined>;
export default uniqueItemProperties;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const uniqueItemProperties_1 = __importDefault(require("../definitions/uniqueItemProperties"));
const uniqueItemProperties = (ajv) => ajv.addKeyword((0, uniqueItemProperties_1.default)());
exports.default = uniqueItemProperties;
module.exports = uniqueItemProperties;
//# sourceMappingURL=uniqueItemProperties.js.map


ajv-keywords

description: Additional JSON-Schema keywords for Ajv JSON validator

build: rm -rf dist && tsc

prepublish: npm run build

test: npm link && npm link ajv-keywords && npm run eslint && npm run test-cov

test-spec: jest spec/*.ts

test-cov: jest spec/*.ts --coverage

type: git

keywords: JSON-Schema ajv keywords

files: src dist ajv-keywords.d.ts

author: Evgeny Poberezkin

license: MIT

pre-commit: lint-staged && npm test

*.{md,json,yaml,js,ts}: prettier --write


code:
import type {MacroKeywordDefinition} from "ajv"
import type {GetDefinition} from "./_types"

type RangeKwd = "range" | "exclusiveRange"

export default function getRangeDef(keyword: RangeKwd): GetDefinition<MacroKeywordDefinition> {
  return () => ({
    keyword,
    type: "number",
    schemaType: "array",
    macro: function ([min, max]: [number, number]) {
      validateRangeSchema(min, max)
      return keyword === "range"
        ? {minimum: min, maximum: max}
        : {exclusiveMinimum: min, exclusiveMaximum: max}
    },
    metaSchema: {
      type: "array",
      minItems: 2,
      maxItems: 2,
      items: {type: "number"},
    },
  })

  function validateRangeSchema(min: number, max: number): void {
    if (min > max || (keyword === "exclusiveRange" && min === max)) {
      throw new Error("There are no numbers in range")
    }
  }
}


code:
import type {MacroKeywordDefinition} from "ajv"
import type {GetDefinition} from "./_types"

type RequiredKwd = "anyRequired" | "oneRequired"

export default function getRequiredDef(
  keyword: RequiredKwd
): GetDefinition<MacroKeywordDefinition> {
  return () => ({
    keyword,
    type: "object",
    schemaType: "array",
    macro(schema: string[]) {
      if (schema.length === 0) return true
      if (schema.length === 1) return {required: schema}
      const comb = keyword === "anyRequired" ? "anyOf" : "oneOf"
      return {[comb]: schema.map((p) => ({required: [p]}))}
    },
    metaSchema: {
      type: "array",
      items: {type: "string"},
    },
  })
}


code:
import type {KeywordDefinition} from "ajv"

export interface DefinitionOptions {
  defaultMeta?: string | boolean
}

export type GetDefinition<T extends KeywordDefinition> = (opts?: DefinitionOptions) => T


code:
import type {DefinitionOptions} from "./_types"
import type {SchemaObject, KeywordCxt, Name} from "ajv"
import {_} from "ajv/dist/compile/codegen"

const META_SCHEMA_ID = "http://json-schema.org/schema"

export function metaSchemaRef({defaultMeta}: DefinitionOptions = {}): SchemaObject {
  return defaultMeta === false ? {} : {$ref: defaultMeta || META_SCHEMA_ID}
}

export function usePattern(
  {gen, it: {opts}}: KeywordCxt,
  pattern: string,
  flags = opts.unicodeRegExp ? "u" : ""
): Name {
  const rx = new RegExp(pattern, flags)
  return gen.scopeValue("pattern", {
    key: rx.toString(),
    ref: rx,
    code: _`new RegExp(${pattern}, ${flags})`,
  })
}


code:
import type {MacroKeywordDefinition} from "ajv"

export default function getDef(): MacroKeywordDefinition {
  return {
    keyword: "allRequired",
    type: "object",
    schemaType: "boolean",
    macro(schema: boolean, parentSchema) {
      if (!schema) return true
      const required = Object.keys(parentSchema.properties)
      if (required.length === 0) return true
      return {required}
    },
    dependencies: ["properties"],
  }
}

module.exports = getDef


code:
import type {MacroKeywordDefinition} from "ajv"
import type {GetDefinition} from "./_types"
import getRequiredDef from "./_required"

const getDef: GetDefinition<MacroKeywordDefinition> = getRequiredDef("anyRequired")

export default getDef
module.exports = getDef


code:
import type {MacroKeywordDefinition, SchemaObject, Schema} from "ajv"
import type {DefinitionOptions} from "./_types"
import {metaSchemaRef} from "./_util"

export default function getDef(opts?: DefinitionOptions): MacroKeywordDefinition {
  return {
    keyword: "deepProperties",
    type: "object",
    schemaType: "object",
    macro: function (schema: Record<string, SchemaObject>) {
      const allOf = []
      for (const pointer in schema) allOf.push(getSchema(pointer, schema[pointer]))
      return {allOf}
    },
    metaSchema: {
      type: "object",
      propertyNames: {type: "string", format: "json-pointer"},
      additionalProperties: metaSchemaRef(opts),
    },
  }
}

function getSchema(jsonPointer: string, schema: SchemaObject): SchemaObject {
  const segments = jsonPointer.split("/")
  const rootSchema: SchemaObject = {}
  let pointerSchema: SchemaObject = rootSchema
  for (let i = 1; i < segments.length; i++) {
    let segment: string = segments[i]
    const isLast = i === segments.length - 1
    segment = unescapeJsonPointer(segment)
    const properties: Record<string, Schema> = (pointerSchema.properties = {})
    let items: SchemaObject[] | undefined
    if (/[0-9]+/.test(segment)) {
      let count = +segment
      items = pointerSchema.items = []
      pointerSchema.type = ["object", "array"]
      while (count--) items.push({})
    } else {
      pointerSchema.type = "object"
    }
    pointerSchema = isLast ? schema : {}
    properties[segment] = pointerSchema
    if (items) items.push(pointerSchema)
  }
  return rootSchema
}

function unescapeJsonPointer(str: string): string {
  return str.replace(/~1/g, "/").replace(/~0/g, "~")
}

module.exports = getDef


code:
import type {CodeKeywordDefinition, KeywordCxt} from "ajv"
import {_, or, and, getProperty, Code} from "ajv/dist/compile/codegen"

export default function getDef(): CodeKeywordDefinition {
  return {
    keyword: "deepRequired",
    type: "object",
    schemaType: "array",
    code(ctx: KeywordCxt) {
      const {schema, data} = ctx
      const props = (schema as string[]).map((jp: string) => _`(${getData(jp)}) === undefined`)
      ctx.fail(or(...props))

      function getData(jsonPointer: string): Code {
        if (jsonPointer === "") throw new Error("empty JSON pointer not allowed")
        const segments = jsonPointer.split("/")
        let x: Code = data
        const xs = segments.map((s, i) =>
          i ? (x = _`${x}${getProperty(unescapeJPSegment(s))}`) : x
        )
        return and(...xs)
      }
    },
    metaSchema: {
      type: "array",
      items: {type: "string", format: "json-pointer"},
    },
  }
}

function unescapeJPSegment(s: string): string {
  return s.replace(/~1/g, "/").replace(/~0/g, "~")
}

module.exports = getDef


code:
import type {FuncKeywordDefinition, SchemaCxt} from "ajv"

const sequences: Record<string, number | undefined> = {}

export type DynamicDefaultFunc = (args?: Record<string, any>) => () => any

const DEFAULTS: Record<string, DynamicDefaultFunc | undefined> = {
  timestamp: () => () => Date.now(),
  datetime: () => () => new Date().toISOString(),
  date: () => () => new Date().toISOString().slice(0, 10),
  time: () => () => new Date().toISOString().slice(11),
  random: () => () => Math.random(),
  randomint: (args?: {max?: number}) => {
    const max = args?.max ?? 2
    return () => Math.floor(Math.random() * max)
  },
  seq: (args?: {name?: string}) => {
    const name = args?.name ?? ""
    sequences[name] ||= 0
    return () => (sequences[name] as number)++
  },
}

interface PropertyDefaultSchema {
  func: string
  args: Record<string, any>
}

type DefaultSchema = Record<string, string | PropertyDefaultSchema | undefined>

const getDef: (() => FuncKeywordDefinition) & {
  DEFAULTS: typeof DEFAULTS
} = Object.assign(_getDef, {DEFAULTS})

function _getDef(): FuncKeywordDefinition {
  return {
    keyword: "dynamicDefaults",
    type: "object",
    schemaType: ["string", "object"],
    modifying: true,
    valid: true,
    compile(schema: DefaultSchema, _parentSchema, it: SchemaCxt) {
      if (!it.opts.useDefaults || it.compositeRule) return () => true
      const fs: Record<string, () => any> = {}
      for (const key in schema) fs[key] = getDefault(schema[key])
      const empty = it.opts.useDefaults === "empty"

      return (data: Record<string, any>) => {
        for (const prop in schema) {
          if (data[prop] === undefined || (empty && (data[prop] === null || data[prop] === ""))) {
            data[prop] = fs[prop]()
          }
        }
        return true
      }
    },
    metaSchema: {
      type: "object",
      additionalProperties: {
        anyOf: [
          {type: "string"},
          {
            type: "object",
            additionalProperties: false,
            required: ["func", "args"],
            properties: {
              func: {type: "string"},
              args: {type: "object"},
            },
          },
        ],
      },
    },
  }
}

function getDefault(d: string | PropertyDefaultSchema | undefined): () => any {
  return typeof d == "object" ? getObjDefault(d) : getStrDefault(d)
}

function getObjDefault({func, args}: PropertyDefaultSchema): () => any {
  const def = DEFAULTS[func]
  assertDefined(func, def)
  return def(args)
}

function getStrDefault(d = ""): () => any {
  const def = DEFAULTS[d]
  assertDefined(d, def)
  return def()
}

function assertDefined(name: string, def?: DynamicDefaultFunc): asserts def is DynamicDefaultFunc {
  if (!def) throw new Error(`invalid "dynamicDefaults" keyword property value: ${name}`)
}

export default getDef
module.exports = getDef


code:
import type {MacroKeywordDefinition} from "ajv"
import type {GetDefinition} from "./_types"
import getRangeDef from "./_range"

const getDef: GetDefinition<MacroKeywordDefinition> = getRangeDef("exclusiveRange")

export default getDef
module.exports = getDef


code:
import type {Vocabulary, KeywordDefinition, ErrorNoParams} from "ajv"
import type {DefinitionOptions, GetDefinition} from "./_types"
import typeofDef from "./typeof"
import instanceofDef from "./instanceof"
import range from "./range"
import exclusiveRange from "./exclusiveRange"
import regexp from "./regexp"
import transform from "./transform"
import uniqueItemProperties from "./uniqueItemProperties"
import allRequired from "./allRequired"
import anyRequired from "./anyRequired"
import oneRequired from "./oneRequired"
import patternRequired, {PatternRequiredError} from "./patternRequired"
import prohibited from "./prohibited"
import deepProperties from "./deepProperties"
import deepRequired from "./deepRequired"
import dynamicDefaults from "./dynamicDefaults"
import selectDef, {SelectError} from "./select"

const definitions: GetDefinition<KeywordDefinition>[] = [
  typeofDef,
  instanceofDef,
  range,
  exclusiveRange,
  regexp,
  transform,
  uniqueItemProperties,
  allRequired,
  anyRequired,
  oneRequired,
  patternRequired,
  prohibited,
  deepProperties,
  deepRequired,
  dynamicDefaults,
]

export default function ajvKeywords(opts?: DefinitionOptions): Vocabulary {
  return definitions.map((d) => d(opts)).concat(selectDef(opts))
}

export type AjvKeywordsError =
  | PatternRequiredError
  | SelectError
  | ErrorNoParams<
      | "range"
      | "exclusiveRange"
      | "anyRequired"
      | "oneRequired"
      | "allRequired"
      | "deepProperties"
      | "deepRequired"
      | "dynamicDefaults"
      | "instanceof"
      | "prohibited"
      | "regexp"
      | "transform"
      | "uniqueItemProperties"
    >

module.exports = ajvKeywords


code:
import type {FuncKeywordDefinition} from "ajv"

type Constructor = new (...args: any[]) => any

const CONSTRUCTORS: Record<string, Constructor | undefined> = {
  Object,
  Array,
  Function,
  Number,
  String,
  Date,
  RegExp,
}

/* istanbul ignore else */
if (typeof Buffer != "undefined") CONSTRUCTORS.Buffer = Buffer

/* istanbul ignore else */
if (typeof Promise != "undefined") CONSTRUCTORS.Promise = Promise

const getDef: (() => FuncKeywordDefinition) & {
  CONSTRUCTORS: typeof CONSTRUCTORS
} = Object.assign(_getDef, {CONSTRUCTORS})

function _getDef(): FuncKeywordDefinition {
  return {
    keyword: "instanceof",
    schemaType: ["string", "array"],
    compile(schema: string | string[]) {
      if (typeof schema == "string") {
        const C = getConstructor(schema)
        return (data) => data instanceof C
      }

      if (Array.isArray(schema)) {
        const constructors = schema.map(getConstructor)
        return (data) => {
          for (const C of constructors) {
            if (data instanceof C) return true
          }
          return false
        }
      }

      /* istanbul ignore next */
      throw new Error("ajv implementation error")
    },
    metaSchema: {
      anyOf: [{type: "string"}, {type: "array", items: {type: "string"}}],
    },
  }
}

function getConstructor(c: string): Constructor {
  const C = CONSTRUCTORS[c]
  if (C) return C
  throw new Error(`invalid "instanceof" keyword value ${c}`)
}

export default getDef
module.exports = getDef


code:
import type {MacroKeywordDefinition} from "ajv"
import type {GetDefinition} from "./_types"
import getRequiredDef from "./_required"

const getDef: GetDefinition<MacroKeywordDefinition> = getRequiredDef("oneRequired")

export default getDef
module.exports = getDef


code:
import type {CodeKeywordDefinition, KeywordCxt, KeywordErrorDefinition, ErrorObject} from "ajv"
import {_, str, and} from "ajv/dist/compile/codegen"
import {usePattern} from "./_util"

export type PatternRequiredError = ErrorObject<"patternRequired", {missingPattern: string}>

const error: KeywordErrorDefinition = {
  message: ({params: {missingPattern}}) =>
    str`should have property matching pattern '${missingPattern}'`,
  params: ({params: {missingPattern}}) => _`{missingPattern: ${missingPattern}}`,
}

export default function getDef(): CodeKeywordDefinition {
  return {
    keyword: "patternRequired",
    type: "object",
    schemaType: "array",
    error,
    code(cxt: KeywordCxt) {
      const {gen, schema, data} = cxt
      if (schema.length === 0) return
      const valid = gen.let("valid", true)
      for (const pat of schema) validateProperties(pat)

      function validateProperties(pattern: string): void {
        const matched = gen.let("matched", false)

        gen.forIn("key", data, (key) => {
          gen.assign(matched, _`${usePattern(cxt, pattern)}.test(${key})`)
          gen.if(matched, () => gen.break())
        })

        cxt.setParams({missingPattern: pattern})
        gen.assign(valid, and(valid, matched))
        cxt.pass(valid)
      }
    },
    metaSchema: {
      type: "array",
      items: {type: "string", format: "regex"},
      uniqueItems: true,
    },
  }
}

module.exports = getDef


code:
import type {MacroKeywordDefinition} from "ajv"

export default function getDef(): MacroKeywordDefinition {
  return {
    keyword: "prohibited",
    type: "object",
    schemaType: "array",
    macro: function (schema: string[]) {
      if (schema.length === 0) return true
      if (schema.length === 1) return {not: {required: schema}}
      return {not: {anyOf: schema.map((p) => ({required: [p]}))}}
    },
    metaSchema: {
      type: "array",
      items: {type: "string"},
    },
  }
}

module.exports = getDef


code:
import type {MacroKeywordDefinition} from "ajv"
import type {GetDefinition} from "./_types"
import getRangeDef from "./_range"

const getDef: GetDefinition<MacroKeywordDefinition> = getRangeDef("range")

export default getDef
module.exports = getDef


code:
import type {CodeKeywordDefinition, KeywordCxt, JSONSchemaType, Name} from "ajv"
import {_} from "ajv/dist/compile/codegen"
import {usePattern} from "./_util"

interface RegexpSchema {
  pattern: string
  flags?: string
}

const regexpMetaSchema: JSONSchemaType<RegexpSchema> = {
  type: "object",
  properties: {
    pattern: {type: "string"},
    flags: {type: "string", nullable: true},
  },
  required: ["pattern"],
  additionalProperties: false,
}

const metaRegexp = /^\/(.*)\/([gimuy]*)$/

export default function getDef(): CodeKeywordDefinition {
  return {
    keyword: "regexp",
    type: "string",
    schemaType: ["string", "object"],
    code(cxt: KeywordCxt) {
      const {data, schema} = cxt
      const regx = getRegExp(schema)
      cxt.pass(_`${regx}.test(${data})`)

      function getRegExp(sch: string | RegexpSchema): Name {
        if (typeof sch == "object") return usePattern(cxt, sch.pattern, sch.flags)
        const rx = metaRegexp.exec(sch)
        if (rx) return usePattern(cxt, rx[1], rx[2])
        throw new Error("cannot parse string into RegExp")
      }
    },
    metaSchema: {
      anyOf: [{type: "string"}, regexpMetaSchema],
    },
  }
}

module.exports = getDef


code:
import type {KeywordDefinition, KeywordErrorDefinition, KeywordCxt, ErrorObject} from "ajv"
import {_, str, nil, Name} from "ajv/dist/compile/codegen"
import type {DefinitionOptions} from "./_types"
import {metaSchemaRef} from "./_util"

export type SelectError = ErrorObject<"select", {failingCase?: string; failingDefault?: true}>

const error: KeywordErrorDefinition = {
  message: ({params: {schemaProp}}) =>
    schemaProp
      ? str`should match case "${schemaProp}" schema`
      : str`should match default case schema`,
  params: ({params: {schemaProp}}) =>
    schemaProp ? _`{failingCase: ${schemaProp}}` : _`{failingDefault: true}`,
}

export default function getDef(opts?: DefinitionOptions): KeywordDefinition[] {
  const metaSchema = metaSchemaRef(opts)

  return [
    {
      keyword: "select",
      schemaType: ["string", "number", "boolean", "null"],
      $data: true,
      error,
      dependencies: ["selectCases"],
      code(cxt: KeywordCxt) {
        const {gen, schemaCode, parentSchema} = cxt
        cxt.block$data(nil, () => {
          const valid = gen.let("valid", true)
          const schValid = gen.name("_valid")
          const value = gen.const("value", _`${schemaCode} === null ? "null" : ${schemaCode}`)
          gen.if(false) // optimizer should remove it from generated code
          for (const schemaProp in parentSchema.selectCases) {
            cxt.setParams({schemaProp})
            gen.elseIf(_`"" + ${value} == ${schemaProp}`) // intentional ==, to match numbers and booleans
            const schCxt = cxt.subschema({keyword: "selectCases", schemaProp}, schValid)
            cxt.mergeEvaluated(schCxt, Name)
            gen.assign(valid, schValid)
          }
          gen.else()
          if (parentSchema.selectDefault !== undefined) {
            cxt.setParams({schemaProp: undefined})
            const schCxt = cxt.subschema({keyword: "selectDefault"}, schValid)
            cxt.mergeEvaluated(schCxt, Name)
            gen.assign(valid, schValid)
          }
          gen.endIf()
          cxt.pass(valid)
        })
      },
    },
    {
      keyword: "selectCases",
      dependencies: ["select"],
      metaSchema: {
        type: "object",
        additionalProperties: metaSchema,
      },
    },
    {
      keyword: "selectDefault",
      dependencies: ["select", "selectCases"],
      metaSchema,
    },
  ]
}

module.exports = getDef


code:
import type {CodeKeywordDefinition, AnySchemaObject, KeywordCxt, Code, Name} from "ajv"
import {_, stringify, getProperty} from "ajv/dist/compile/codegen"

type TransformName =
  | "trimStart"
  | "trimEnd"
  | "trimLeft"
  | "trimRight"
  | "trim"
  | "toLowerCase"
  | "toUpperCase"
  | "toEnumCase"

interface TransformConfig {
  hash: Record<string, string | undefined>
}

type Transform = (s: string, cfg?: TransformConfig) => string

const transform: {[key in TransformName]: Transform} = {
  trimStart: (s) => s.trimStart(),
  trimEnd: (s) => s.trimEnd(),
  trimLeft: (s) => s.trimStart(),
  trimRight: (s) => s.trimEnd(),
  trim: (s) => s.trim(),
  toLowerCase: (s) => s.toLowerCase(),
  toUpperCase: (s) => s.toUpperCase(),
  toEnumCase: (s, cfg) => cfg?.hash[configKey(s)] || s,
}

const getDef: (() => CodeKeywordDefinition) & {
  transform: typeof transform
} = Object.assign(_getDef, {transform})

function _getDef(): CodeKeywordDefinition {
  return {
    keyword: "transform",
    schemaType: "array",
    before: "enum",
    code(cxt: KeywordCxt) {
      const {gen, data, schema, parentSchema, it} = cxt
      const {parentData, parentDataProperty} = it
      const tNames: string[] = schema
      if (!tNames.length) return
      let cfg: Name | undefined
      if (tNames.includes("toEnumCase")) {
        const config = getEnumCaseCfg(parentSchema)
        cfg = gen.scopeValue("obj", {ref: config, code: stringify(config)})
      }
      gen.if(_`typeof ${data} == "string" && ${parentData} !== undefined`, () => {
        gen.assign(data, transformExpr(tNames.slice()))
        gen.assign(_`${parentData}[${parentDataProperty}]`, data)
      })

      function transformExpr(ts: string[]): Code {
        if (!ts.length) return data
        const t = ts.pop() as string
        if (!(t in transform)) throw new Error(`transform: unknown transformation ${t}`)
        const func = gen.scopeValue("func", {
          ref: transform[t as TransformName],
          code: _`require("ajv-keywords/dist/definitions/transform").transform${getProperty(t)}`,
        })
        const arg = transformExpr(ts)
        return cfg && t === "toEnumCase" ? _`${func}(${arg}, ${cfg})` : _`${func}(${arg})`
      }
    },
    metaSchema: {
      type: "array",
      items: {type: "string", enum: Object.keys(transform)},
    },
  }
}

function getEnumCaseCfg(parentSchema: AnySchemaObject): TransformConfig {
  // build hash table to enum values
  const cfg: TransformConfig = {hash: {}}

  // requires `enum` in the same schema as transform
  if (!parentSchema.enum) throw new Error('transform: "toEnumCase" requires "enum"')
  for (const v of parentSchema.enum) {
    if (typeof v !== "string") continue
    const k = configKey(v)
    // requires all `enum` values have unique keys
    if (cfg.hash[k]) {
      throw new Error('transform: "toEnumCase" requires all lowercased "enum" values to be unique')
    }
    cfg.hash[k] = v
  }

  return cfg
}

function configKey(s: string): string {
  return s.toLowerCase()
}

export default getDef
module.exports = getDef


code:
import type {CodeKeywordDefinition, KeywordCxt} from "ajv"
import {_} from "ajv/dist/compile/codegen"

const TYPES = ["undefined", "string", "number", "object", "function", "boolean", "symbol"]

export default function getDef(): CodeKeywordDefinition {
  return {
    keyword: "typeof",
    schemaType: ["string", "array"],
    code(cxt: KeywordCxt) {
      const {data, schema, schemaValue} = cxt
      cxt.fail(
        typeof schema == "string"
          ? _`typeof ${data} != ${schema}`
          : _`${schemaValue}.indexOf(typeof ${data}) < 0`
      )
    },
    metaSchema: {
      anyOf: [
        {type: "string", enum: TYPES},
        {type: "array", items: {type: "string", enum: TYPES}},
      ],
    },
  }
}

module.exports = getDef


code:
import type {FuncKeywordDefinition, AnySchemaObject} from "ajv"
import equal = require("fast-deep-equal")

const SCALAR_TYPES = ["number", "integer", "string", "boolean", "null"]

export default function getDef(): FuncKeywordDefinition {
  return {
    keyword: "uniqueItemProperties",
    type: "array",
    schemaType: "array",
    compile(keys: string[], parentSchema: AnySchemaObject) {
      const scalar = getScalarKeys(keys, parentSchema)

      return (data) => {
        if (data.length <= 1) return true
        for (let k = 0; k < keys.length; k++) {
          const key = keys[k]
          if (scalar[k]) {
            const hash: Record<string, any> = {}
            for (const x of data) {
              if (!x || typeof x != "object") continue
              let p = x[key]
              if (p && typeof p == "object") continue
              if (typeof p == "string") p = '"' + p
              if (hash[p]) return false
              hash[p] = true
            }
          } else {
            for (let i = data.length; i--; ) {
              const x = data[i]
              if (!x || typeof x != "object") continue
              for (let j = i; j--; ) {
                const y = data[j]
                if (y && typeof y == "object" && equal(x[key], y[key])) return false
              }
            }
          }
        }
        return true
      }
    },
    metaSchema: {
      type: "array",
      items: {type: "string"},
    },
  }
}

function getScalarKeys(keys: string[], schema: AnySchemaObject): boolean[] {
  return keys.map((key) => {
    const t = schema.items?.properties?.[key]?.type
    return Array.isArray(t)
      ? !t.includes("object") && !t.includes("array")
      : SCALAR_TYPES.includes(t)
  })
}

module.exports = getDef


code:
import type Ajv from "ajv"
import type {Plugin} from "ajv"
import plugins from "./keywords"

export {AjvKeywordsError} from "./definitions"

const ajvKeywords: Plugin<string | string[]> = (ajv: Ajv, keyword?: string | string[]): Ajv => {
  if (Array.isArray(keyword)) {
    for (const k of keyword) get(k)(ajv)
    return ajv
  }
  if (keyword) {
    get(keyword)(ajv)
    return ajv
  }
  for (keyword in plugins) get(keyword)(ajv)
  return ajv
}

ajvKeywords.get = get

function get(keyword: string): Plugin<any> {
  const defFunc = plugins[keyword]
  if (!defFunc) throw new Error("Unknown keyword " + keyword)
  return defFunc
}

export default ajvKeywords
module.exports = ajvKeywords

// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
module.exports.default = ajvKeywords


code:
import type {Plugin} from "ajv"
import getDef from "../definitions/allRequired"

const allRequired: Plugin<undefined> = (ajv) => ajv.addKeyword(getDef())

export default allRequired
module.exports = allRequired


code:
import type {Plugin} from "ajv"
import getDef from "../definitions/anyRequired"

const anyRequired: Plugin<undefined> = (ajv) => ajv.addKeyword(getDef())

export default anyRequired
module.exports = anyRequired


code:
import type {Plugin} from "ajv"
import getDef from "../definitions/deepProperties"
import type {DefinitionOptions} from "../definitions/_types"

const deepProperties: Plugin<DefinitionOptions> = (ajv, opts?: DefinitionOptions) =>
  ajv.addKeyword(getDef(opts))

export default deepProperties
module.exports = deepProperties


code:
import type {Plugin} from "ajv"
import getDef from "../definitions/deepRequired"

const deepRequired: Plugin<undefined> = (ajv) => ajv.addKeyword(getDef())

export default deepRequired
module.exports = deepRequired


code:
import type {Plugin} from "ajv"
import getDef from "../definitions/dynamicDefaults"

const dynamicDefaults: Plugin<undefined> = (ajv) => ajv.addKeyword(getDef())

export default dynamicDefaults
module.exports = dynamicDefaults


code:
import type {Plugin} from "ajv"
import getDef from "../definitions/exclusiveRange"

const exclusiveRange: Plugin<undefined> = (ajv) => ajv.addKeyword(getDef())

export default exclusiveRange
module.exports = exclusiveRange


code:
import type {Plugin} from "ajv"
import typeofPlugin from "./typeof"
import instanceofPlugin from "./instanceof"
import range from "./range"
import exclusiveRange from "./exclusiveRange"
import regexp from "./regexp"
import transform from "./transform"
import uniqueItemProperties from "./uniqueItemProperties"
import allRequired from "./allRequired"
import anyRequired from "./anyRequired"
import oneRequired from "./oneRequired"
import patternRequired from "./patternRequired"
import prohibited from "./prohibited"
import deepProperties from "./deepProperties"
import deepRequired from "./deepRequired"
import dynamicDefaults from "./dynamicDefaults"
import select from "./select"

// TODO type
const ajvKeywords: Record<string, Plugin<any> | undefined> = {
  typeof: typeofPlugin,
  instanceof: instanceofPlugin,
  range,
  exclusiveRange,
  regexp,
  transform,
  uniqueItemProperties,
  allRequired,
  anyRequired,
  oneRequired,
  patternRequired,
  prohibited,
  deepProperties,
  deepRequired,
  dynamicDefaults,
  select,
}

export default ajvKeywords
module.exports = ajvKeywords


code:
import type {Plugin} from "ajv"
import getDef from "../definitions/instanceof"

const instanceofPlugin: Plugin<undefined> = (ajv) => ajv.addKeyword(getDef())

export default instanceofPlugin
module.exports = instanceofPlugin


code:
import type {Plugin} from "ajv"
import getDef from "../definitions/oneRequired"

const oneRequired: Plugin<undefined> = (ajv) => ajv.addKeyword(getDef())

export default oneRequired
module.exports = oneRequired


code:
import type {Plugin} from "ajv"
import getDef from "../definitions/patternRequired"

const patternRequired: Plugin<undefined> = (ajv) => ajv.addKeyword(getDef())

export default patternRequired
module.exports = patternRequired


code:
import type {Plugin} from "ajv"
import getDef from "../definitions/prohibited"

const prohibited: Plugin<undefined> = (ajv) => ajv.addKeyword(getDef())

export default prohibited
module.exports = prohibited


code:
import type {Plugin} from "ajv"
import getDef from "../definitions/range"

const range: Plugin<undefined> = (ajv) => ajv.addKeyword(getDef())

export default range
module.exports = range


code:
import type {Plugin} from "ajv"
import getDef from "../definitions/regexp"

const regexp: Plugin<undefined> = (ajv) => ajv.addKeyword(getDef())

export default regexp
module.exports = regexp


code:
import type {Plugin} from "ajv"
import getDefs from "../definitions/select"
import type {DefinitionOptions} from "../definitions/_types"

const select: Plugin<DefinitionOptions> = (ajv, opts?: DefinitionOptions) => {
  getDefs(opts).forEach((d) => ajv.addKeyword(d))
  return ajv
}

export default select
module.exports = select


code:
import type {Plugin} from "ajv"
import getDef from "../definitions/transform"

const transform: Plugin<undefined> = (ajv) => ajv.addKeyword(getDef())

export default transform
module.exports = transform


code:
import type {Plugin} from "ajv"
import getDef from "../definitions/typeof"

const typeofPlugin: Plugin<undefined> = (ajv) => ajv.addKeyword(getDef())

export default typeofPlugin
module.exports = typeofPlugin


code:
import type {Plugin} from "ajv"
import getDef from "../definitions/uniqueItemProperties"

const uniqueItemProperties: Plugin<undefined> = (ajv) => ajv.addKeyword(getDef())

export default uniqueItemProperties
module.exports = uniqueItemProperties


code:
const Ajv = require("ajv")
const ajv = new Ajv({allErrors: true})

const schema = {
  type: "object",
  properties: {
    foo: {type: "string"},
    bar: {type: "number", maximum: 3},
  },
  required: ["foo", "bar"],
  additionalProperties: false,
}

const validate = ajv.compile(schema)

test({foo: "abc", bar: 2})
test({foo: 2, bar: 4})

function test(data) {
  const valid = validate(data)
  if (valid) console.log("Valid!")
  else console.log("Invalid: " + ajv.errorsText(validate.errors))
}


code:
# Ajv JSON schema validator

The fastest JSON validator for Node.js and browser.

Supports JSON Schema draft-04/06/07/2019-09/2020-12 ([draft-04 support](https://ajv.js.org/json-schema.html#draft-04) requires ajv-draft-04 package) and JSON Type Definition [RFC8927](https://datatracker.ietf.org/doc/rfc8927/).

[![build](https://github.com/ajv-validator/ajv/actions/workflows/build.yml/badge.svg)](https://github.com/ajv-validator/ajv/actions?query=workflow%3Abuild)
[![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv)
[![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv)
[![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master)
[![SimpleX](https://img.shields.io/badge/chat-on%20SimpleX-70F0F9)](https://simplex.chat/contact#/?v=1-2&smp=smp%3A%2F%2Fu2dS9sG8nMNURyZwqASV4yROM28Er0luVTx5X1CsMrU%3D%40smp4.simplex.im%2F8KvvURM6J38Gdq9dCuPswMOkMny0xCOJ%23%2F%3Fv%3D1-2%26dh%3DMCowBQYDK2VuAyEAr8rPVRuMOXv6kwF2yUAap-eoVg-9ssOFCi1fIrxTUw0%253D%26srv%3Do5vmywmrnaxalvz6wi3zicyftgio6psuvyniis6gco6bp6ekl4cqj4id.onion&data=%7B%22type%22%3A%22group%22%2C%22groupLinkId%22%3A%224pwLRgWHU9tlroMWHz0uOg%3D%3D%22%7D)
[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv)
[![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin)

## Ajv sponsors

[](https://www.mozilla.org)[](https://opencollective.com/ajv)

[](https://opensource.microsoft.com)[](https://opencollective.com/ajv)[](https://opencollective.com/ajv)

[](https://retool.com/?utm_source=sponsor&utm_campaign=ajv)[](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=enterprise)[](https://github.com/simplex-chat/simplex-chat)[](https://opencollective.com/ajv)

## Contributing

More than 100 people contributed to Ajv, and we would love to have you join the development. We welcome implementing new features that will benefit many users and ideas to improve our documentation.

Please review [Contributing guidelines](./CONTRIBUTING.md) and [Code components](https://ajv.js.org/components.html).

## Documentation

All documentation is available on the [Ajv website](https://ajv.js.org).

Some useful site links:

- [Getting started](https://ajv.js.org/guide/getting-started.html)
- [JSON Schema vs JSON Type Definition](https://ajv.js.org/guide/schema-language.html)
- [API reference](https://ajv.js.org/api.html)
- [Strict mode](https://ajv.js.org/strict-mode.html)
- [Standalone validation code](https://ajv.js.org/standalone.html)
- [Security considerations](https://ajv.js.org/security.html)
- [Command line interface](https://ajv.js.org/packages/ajv-cli.html)
- [Frequently Asked Questions](https://ajv.js.org/faq.html)

## Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin)

Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant!

Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released.

Please sponsor Ajv via:

- [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it)
- [Ajv Open Collective](https://opencollective.com/ajv)

Thank you.

#### Open Collective sponsors

## Performance

Ajv generates code to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization.

Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks:

- [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place
- [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster
- [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html)
- [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html)

Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark):

[![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=62,4,1&chs=600x416&chxl=-1:|ajv|@exodus/schemasafe|is-my-json-valid|djv|@cfworker/json-schema|jsonschema/=t:100,69.2,51.5,13.1,5.1,1.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance)

## Features

- Ajv implements JSON Schema [draft-06/07/2019-09/2020-12](http://json-schema.org/) standards (draft-04 is supported in v6):
  - all validation keywords (see [JSON Schema validation keywords](https://ajv.js.org/json-schema.html))
  - [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md) extensions:
    - NEW: keyword [discriminator](https://ajv.js.org/json-schema.html#discriminator).
    - keyword [nullable](https://ajv.js.org/json-schema.html#nullable).
  - full support of remote references (remote schemas have to be added with `addSchema` or compiled to be available)
  - support of recursive references between schemas
  - correct string lengths for strings with unicode pairs
  - JSON Schema [formats](https://ajv.js.org/guide/formats.html) (with [ajv-formats](https://github.com/ajv-validator/ajv-formats) plugin).
  - [validates schemas against meta-schema](https://ajv.js.org/api.html#api-validateschema)
- NEW: supports [JSON Type Definition](https://datatracker.ietf.org/doc/rfc8927/):
  - all keywords (see [JSON Type Definition schema forms](https://ajv.js.org/json-type-definition.html))
  - meta-schema for JTD schemas
  - "union" keyword and user-defined keywords (can be used inside "metadata" member of the schema)
- supports [browsers](https://ajv.js.org/guide/environments.html#browsers) and Node.js 10.x - current
- [asynchronous loading](https://ajv.js.org/guide/managing-schemas.html#asynchronous-schema-loading) of referenced schemas during compilation
- "All errors" validation mode with [option allErrors](https://ajv.js.org/options.html#allerrors)
- [error messages with parameters](https://ajv.js.org/api.html#validation-errors) describing error reasons to allow error message generation
- i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package
- [removing-additional-properties](https://ajv.js.org/guide/modifying-data.html#removing-additional-properties)
- [assigning defaults](https://ajv.js.org/guide/modifying-data.html#assigning-defaults) to missing properties and items
- [coercing data](https://ajv.js.org/guide/modifying-data.html#coercing-data-types) to the types specified in `type` keywords
- [user-defined keywords](https://ajv.js.org/guide/user-keywords.html)
- additional extension keywords with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package
- [\$data reference](https://ajv.js.org/guide/combining-schemas.html#data-reference) to use values from the validated data as values for the schema keywords
- [asynchronous validation](https://ajv.js.org/guide/async-validation.html) of user-defined formats and keywords

## Install

To install version 8:

```
npm install ajv
```

## Getting started

Try it in the Node.js REPL: https://runkit.com/npm/ajv

In JavaScript:

```javascript
// or ESM/TypeScript import
import Ajv from "ajv"
// Node.js require:
const Ajv = require("ajv")

const ajv = new Ajv() // options can be passed, e.g. {allErrors: true}

const schema = {
  type: "object",
  properties: {
    foo: {type: "integer"},
    bar: {type: "string"},
  },
  required: ["foo"],
  additionalProperties: false,
}

const data = {
  foo: 1,
  bar: "abc",
}

const validate = ajv.compile(schema)
const valid = validate(data)
if (!valid) console.log(validate.errors)
```

Learn how to use Ajv and see more examples in the [Guide: getting started](https://ajv.js.org/guide/getting-started.html)

## Changes history

See [https://github.com/ajv-validator/ajv/releases](https://github.com/ajv-validator/ajv/releases)

**Please note**: [Changes in version 8.0.0](https://github.com/ajv-validator/ajv/releases/tag/v8.0.0)

[Version 7.0.0](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0)

[Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0).

## Code of conduct

Please review and follow the [Code of conduct](./CODE_OF_CONDUCT.md).

Please report any unacceptable behaviour to ajv.validator@gmail.com - it will be reviewed by the project team.

## Security contact

To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues.

## Open-source software support

Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers.

## License

[MIT](./LICENSE)


code:
import type { AnySchemaObject } from "./types";
import AjvCore, { Options } from "./core";
export declare class Ajv2019 extends AjvCore {
    constructor(opts?: Options);
    _addVocabularies(): void;
    _addDefaultMetaSchema(): void;
    defaultMeta(): string | AnySchemaObject | undefined;
}
export default Ajv2019;
export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, ErrorObject, ErrorNoParams, } from "./types";
export { Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions } from "./core";
export { SchemaCxt, SchemaObjCxt } from "./compile";
export { KeywordCxt } from "./compile/validate";
export { DefinedError } from "./vocabularies/errors";
export { JSONType } from "./compile/rules";
export { JSONSchemaType } from "./types/json-schema";
export { _, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions } from "./compile/codegen";
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.Ajv2019 = void 0;
const core_1 = require("./core");
const draft7_1 = require("./vocabularies/draft7");
const dynamic_1 = require("./vocabularies/dynamic");
const next_1 = require("./vocabularies/next");
const unevaluated_1 = require("./vocabularies/unevaluated");
const discriminator_1 = require("./vocabularies/discriminator");
const json_schema_2019_09_1 = require("./refs/json-schema-2019-09");
const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema";
class Ajv2019 extends core_1.default {
    constructor(opts = {}) {
        super({
            ...opts,
            dynamicRef: true,
            next: true,
            unevaluated: true,
        });
    }
    _addVocabularies() {
        super._addVocabularies();
        this.addVocabulary(dynamic_1.default);
        draft7_1.default.forEach((v) => this.addVocabulary(v));
        this.addVocabulary(next_1.default);
        this.addVocabulary(unevaluated_1.default);
        if (this.opts.discriminator)
            this.addKeyword(discriminator_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        const { $data, meta } = this.opts;
        if (!meta)
            return;
        json_schema_2019_09_1.default.call(this, $data);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
}
exports.Ajv2019 = Ajv2019;
module.exports = exports = Ajv2019;
module.exports.Ajv2019 = Ajv2019;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv2019;
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=2019.js.map


code:
import type { AnySchemaObject } from "./types";
import AjvCore, { Options } from "./core";
export declare class Ajv2020 extends AjvCore {
    constructor(opts?: Options);
    _addVocabularies(): void;
    _addDefaultMetaSchema(): void;
    defaultMeta(): string | AnySchemaObject | undefined;
}
export default Ajv2020;
export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, ErrorObject, ErrorNoParams, } from "./types";
export { Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions } from "./core";
export { SchemaCxt, SchemaObjCxt } from "./compile";
export { KeywordCxt } from "./compile/validate";
export { DefinedError } from "./vocabularies/errors";
export { JSONType } from "./compile/rules";
export { JSONSchemaType } from "./types/json-schema";
export { _, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions } from "./compile/codegen";
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.Ajv2020 = void 0;
const core_1 = require("./core");
const draft2020_1 = require("./vocabularies/draft2020");
const discriminator_1 = require("./vocabularies/discriminator");
const json_schema_2020_12_1 = require("./refs/json-schema-2020-12");
const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema";
class Ajv2020 extends core_1.default {
    constructor(opts = {}) {
        super({
            ...opts,
            dynamicRef: true,
            next: true,
            unevaluated: true,
        });
    }
    _addVocabularies() {
        super._addVocabularies();
        draft2020_1.default.forEach((v) => this.addVocabulary(v));
        if (this.opts.discriminator)
            this.addKeyword(discriminator_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        const { $data, meta } = this.opts;
        if (!meta)
            return;
        json_schema_2020_12_1.default.call(this, $data);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
}
exports.Ajv2020 = Ajv2020;
module.exports = exports = Ajv2020;
module.exports.Ajv2020 = Ajv2020;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv2020;
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=2020.js.map


code:
import type { AnySchemaObject } from "./types";
import AjvCore from "./core";
export declare class Ajv extends AjvCore {
    _addVocabularies(): void;
    _addDefaultMetaSchema(): void;
    defaultMeta(): string | AnySchemaObject | undefined;
}
export default Ajv;
export { Format, FormatDefinition, AsyncFormatDefinition, KeywordDefinition, KeywordErrorDefinition, CodeKeywordDefinition, MacroKeywordDefinition, FuncKeywordDefinition, Vocabulary, Schema, SchemaObject, AnySchemaObject, AsyncSchema, AnySchema, ValidateFunction, AsyncValidateFunction, SchemaValidateFunction, ErrorObject, ErrorNoParams, } from "./types";
export { Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions } from "./core";
export { SchemaCxt, SchemaObjCxt } from "./compile";
export { KeywordCxt } from "./compile/validate";
export { DefinedError } from "./vocabularies/errors";
export { JSONType } from "./compile/rules";
export { JSONSchemaType } from "./types/json-schema";
export { _, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions } from "./compile/codegen";
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 draft7_1 = require("./vocabularies/draft7");
const discriminator_1 = require("./vocabularies/discriminator");
const draft7MetaSchema = require("./refs/json-schema-draft-07.json");
const META_SUPPORT_DATA = ["/properties"];
const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
class Ajv extends core_1.default {
    _addVocabularies() {
        super._addVocabularies();
        draft7_1.default.forEach((v) => this.addVocabulary(v));
        if (this.opts.discriminator)
            this.addKeyword(discriminator_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        if (!this.opts.meta)
            return;
        const metaSchema = this.opts.$data
            ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
            : draft7MetaSchema;
        this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
}
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=ajv.js.map


code:
export declare abstract class _CodeOrName {
    abstract readonly str: string;
    abstract readonly names: UsedNames;
    abstract toString(): string;
    abstract emptyStr(): boolean;
}
export declare const IDENTIFIER: RegExp;
export declare class Name extends _CodeOrName {
    readonly str: string;
    constructor(s: string);
    toString(): string;
    emptyStr(): boolean;
    get names(): UsedNames;
}
export declare class _Code extends _CodeOrName {
    readonly _items: readonly CodeItem[];
    private _str?;
    private _names?;
    constructor(code: string | readonly CodeItem[]);
    toString(): string;
    emptyStr(): boolean;
    get str(): string;
    get names(): UsedNames;
}
export type CodeItem = Name | string | number | boolean | null;
export type UsedNames = Record<string, number | undefined>;
export type Code = _Code | Name;
export type SafeExpr = Code | number | boolean | null;
export declare const nil: _Code;
type CodeArg = SafeExpr | string | undefined;
export declare function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code;
export declare function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code;
export declare function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void;
export declare function strConcat(c1: Code, c2: Code): Code;
export declare function stringify(x: unknown): Code;
export declare function safeStringify(x: unknown): string;
export declare function getProperty(key: Code | string | number): Code;
export declare function getEsmExportName(key: Code | string | number): Code;
export declare function regexpCode(rx: RegExp): Code;
export {};


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
class _CodeOrName {
}
exports._CodeOrName = _CodeOrName;
exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
class Name extends _CodeOrName {
    constructor(s) {
        super();
        if (!exports.IDENTIFIER.test(s))
            throw new Error("CodeGen: name must be a valid identifier");
        this.str = s;
    }
    toString() {
        return this.str;
    }
    emptyStr() {
        return false;
    }
    get names() {
        return { [this.str]: 1 };
    }
}
exports.Name = Name;
class _Code extends _CodeOrName {
    constructor(code) {
        super();
        this._items = typeof code === "string" ? [code] : code;
    }
    toString() {
        return this.str;
    }
    emptyStr() {
        if (this._items.length > 1)
            return false;
        const item = this._items[0];
        return item === "" || item === '""';
    }
    get str() {
        var _a;
        return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, "")));
    }
    get names() {
        var _a;
        return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => {
            if (c instanceof Name)
                names[c.str] = (names[c.str] || 0) + 1;
            return names;
        }, {})));
    }
}
exports._Code = _Code;
exports.nil = new _Code("");
function _(strs, ...args) {
    const code = [strs[0]];
    let i = 0;
    while (i < args.length) {
        addCodeArg(code, args[i]);
        code.push(strs[++i]);
    }
    return new _Code(code);
}
exports._ = _;
const plus = new _Code("+");
function str(strs, ...args) {
    const expr = [safeStringify(strs[0])];
    let i = 0;
    while (i < args.length) {
        expr.push(plus);
        addCodeArg(expr, args[i]);
        expr.push(plus, safeStringify(strs[++i]));
    }
    optimize(expr);
    return new _Code(expr);
}
exports.str = str;
function addCodeArg(code, arg) {
    if (arg instanceof _Code)
        code.push(...arg._items);
    else if (arg instanceof Name)
        code.push(arg);
    else
        code.push(interpolate(arg));
}
exports.addCodeArg = addCodeArg;
function optimize(expr) {
    let i = 1;
    while (i < expr.length - 1) {
        if (expr[i] === plus) {
            const res = mergeExprItems(expr[i - 1], expr[i + 1]);
            if (res !== undefined) {
                expr.splice(i - 1, 3, res);
                continue;
            }
            expr[i++] = "+";
        }
        i++;
    }
}
function mergeExprItems(a, b) {
    if (b === '""')
        return a;
    if (a === '""')
        return b;
    if (typeof a == "string") {
        if (b instanceof Name || a[a.length - 1] !== '"')
            return;
        if (typeof b != "string")
            return `${a.slice(0, -1)}${b}"`;
        if (b[0] === '"')
            return a.slice(0, -1) + b.slice(1);
        return;
    }
    if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
        return `"${a}${b.slice(1)}`;
    return;
}
function strConcat(c1, c2) {
    return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`;
}
exports.strConcat = strConcat;
// TODO do not allow arrays here
function interpolate(x) {
    return typeof x == "number" || typeof x == "boolean" || x === null
        ? x
        : safeStringify(Array.isArray(x) ? x.join(",") : x);
}
function stringify(x) {
    return new _Code(safeStringify(x));
}
exports.stringify = stringify;
function safeStringify(x) {
    return JSON.stringify(x)
        .replace(/\u2028/g, "\\u2028")
        .replace(/\u2029/g, "\\u2029");
}
exports.safeStringify = safeStringify;
function getProperty(key) {
    return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;
}
exports.getProperty = getProperty;
//Does best effort to format the name properly
function getEsmExportName(key) {
    if (typeof key == "string" && exports.IDENTIFIER.test(key)) {
        return new _Code(`${key}`);
    }
    throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
}
exports.getEsmExportName = getEsmExportName;
function regexpCode(rx) {
    return new _Code(rx.toString());
}
exports.regexpCode = regexpCode;
//# sourceMappingURL=code.js.map


code:
import type { ScopeValueSets, NameValue, ValueScope, ValueScopeName } from "./scope";
import { _Code, Code, Name } from "./code";
import { Scope } from "./scope";
export { _, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code } from "./code";
export { Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds } from "./scope";
export type SafeExpr = Code | number | boolean | null;
export type Block = Code | (() => void);
export declare const operators: {
    GT: _Code;
    GTE: _Code;
    LT: _Code;
    LTE: _Code;
    EQ: _Code;
    NEQ: _Code;
    NOT: _Code;
    OR: _Code;
    AND: _Code;
    ADD: _Code;
};
export interface CodeGenOptions {
    es5?: boolean;
    lines?: boolean;
    ownProperties?: boolean;
}
export declare class CodeGen {
    readonly _scope: Scope;
    readonly _extScope: ValueScope;
    readonly _values: ScopeValueSets;
    private readonly _nodes;
    private readonly _blockStarts;
    private readonly _constants;
    private readonly opts;
    constructor(extScope: ValueScope, opts?: CodeGenOptions);
    toString(): string;
    name(prefix: string): Name;
    scopeName(prefix: string): ValueScopeName;
    scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name;
    getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined;
    scopeRefs(scopeName: Name): Code;
    scopeCode(): Code;
    private _def;
    const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name;
    let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name;
    var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name;
    assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen;
    add(lhs: Code, rhs: SafeExpr): CodeGen;
    code(c: Block | SafeExpr): CodeGen;
    object(...keyValues: [Name | string, SafeExpr | string][]): _Code;
    if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen;
    elseIf(condition: Code | boolean): CodeGen;
    else(): CodeGen;
    endIf(): CodeGen;
    private _for;
    for(iteration: Code, forBody?: Block): CodeGen;
    forRange(nameOrPrefix: Name | string, from: SafeExpr, to: SafeExpr, forBody: (index: Name) => void, varKind?: Code): CodeGen;
    forOf(nameOrPrefix: Name | string, iterable: Code, forBody: (item: Name) => void, varKind?: Code): CodeGen;
    forIn(nameOrPrefix: Name | string, obj: Code, forBody: (item: Name) => void, varKind?: Code): CodeGen;
    endFor(): CodeGen;
    label(label: Name): CodeGen;
    break(label?: Code): CodeGen;
    return(value: Block | SafeExpr): CodeGen;
    try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen;
    throw(error: Code): CodeGen;
    block(body?: Block, nodeCount?: number): CodeGen;
    endBlock(nodeCount?: number): CodeGen;
    func(name: Name, args?: Code, async?: boolean, funcBody?: Block): CodeGen;
    endFunc(): CodeGen;
    optimize(n?: number): void;
    private _leafNode;
    private _blockNode;
    private _endBlockNode;
    private _elseNode;
    private get _root();
    private get _currNode();
    private set _currNode(value);
}
export declare function not<T extends Code | SafeExpr>(x: T): T;
export declare function and(...args: Code[]): Code;
export declare function or(...args: Code[]): Code;