2 Object.defineProperty(exports, "__esModule", { value: true });
3 exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
4 var validate_1 = require("./compile/validate");
5 Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
6 var codegen_1 = require("./compile/codegen");
7 Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
8 Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
9 Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
10 Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
11 Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
12 Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
13 const validation_error_1 = require("./runtime/validation_error");
14 const ref_error_1 = require("./compile/ref_error");
15 const rules_1 = require("./compile/rules");
16 const compile_1 = require("./compile");
17 const codegen_2 = require("./compile/codegen");
18 const resolve_1 = require("./compile/resolve");
19 const dataType_1 = require("./compile/validate/dataType");
20 const util_1 = require("./compile/util");
21 const $dataRefSchema = require("./refs/data.json");
22 const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
23 const EXT_SCOPE_NAMES = new Set([
38 const removedOptions = {
40 format: "`validateFormats: false` can be used instead.",
41 nullable: '"nullable" keyword is supported by default.',
42 jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
43 extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
44 missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
45 processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
46 sourceCode: "Use option `code: {source: true}`",
47 schemaId: "JSON Schema draft-04 is not supported in Ajv v7/8.",
48 strictDefaults: "It is default now, see option `strict`.",
49 strictKeywords: "It is default now, see option `strict`.",
50 uniqueItems: '"uniqueItems" keyword is always validated.',
51 unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
52 cache: "Map is used as cache, schema object as key.",
53 serialize: "Map is used as cache, schema object as key.",
54 ajvErrors: "It is default now, see option `strict`.",
56 const deprecatedOptions = {
57 ignoreKeywordsWithRef: "",
59 unicode: '"minLength"/"maxLength" account for unicode characters by default.',
61 const MAX_EXPRESSION = 200;
62 // eslint-disable-next-line complexity
63 function requiredOptions(o) {
64 var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
66 const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
67 const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
69 strictSchema: (_c = (_b = o.strictSchema) !== null && _b !== void 0 ? _b : s) !== null && _c !== void 0 ? _c : true,
70 strictNumbers: (_e = (_d = o.strictNumbers) !== null && _d !== void 0 ? _d : s) !== null && _e !== void 0 ? _e : true,
71 strictTypes: (_g = (_f = o.strictTypes) !== null && _f !== void 0 ? _f : s) !== null && _g !== void 0 ? _g : "log",
72 strictTuples: (_j = (_h = o.strictTuples) !== null && _h !== void 0 ? _h : s) !== null && _j !== void 0 ? _j : "log",
73 strictRequired: (_l = (_k = o.strictRequired) !== null && _k !== void 0 ? _k : s) !== null && _l !== void 0 ? _l : false,
74 code: o.code ? { ...o.code, optimize } : { optimize },
75 loopRequired: (_m = o.loopRequired) !== null && _m !== void 0 ? _m : MAX_EXPRESSION,
76 loopEnum: (_o = o.loopEnum) !== null && _o !== void 0 ? _o : MAX_EXPRESSION,
77 meta: (_p = o.meta) !== null && _p !== void 0 ? _p : true,
78 messages: (_q = o.messages) !== null && _q !== void 0 ? _q : true,
79 inlineRefs: (_r = o.inlineRefs) !== null && _r !== void 0 ? _r : true,
80 addUsedSchema: (_s = o.addUsedSchema) !== null && _s !== void 0 ? _s : true,
81 validateSchema: (_t = o.validateSchema) !== null && _t !== void 0 ? _t : true,
82 validateFormats: (_u = o.validateFormats) !== null && _u !== void 0 ? _u : true,
86 constructor(opts = {}) {
90 this._compilations = new Set();
92 this._cache = new Map();
93 opts = this.opts = { ...opts, ...requiredOptions(opts) };
94 const { es5, lines } = this.opts.code;
95 this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
96 this.logger = getLogger(opts.logger);
97 const formatOpt = opts.validateFormats;
98 opts.validateFormats = false;
99 this.RULES = rules_1.getRules();
100 checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
101 checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
102 this._metaOpts = getMetaSchemaOptions.call(this);
104 addInitialFormats.call(this);
105 this._addVocabularies();
106 this._addDefaultMetaSchema();
108 addInitialKeywords.call(this, opts.keywords);
109 if (typeof opts.meta == "object")
110 this.addMetaSchema(opts.meta);
111 addInitialSchemas.call(this);
112 opts.validateFormats = formatOpt;
115 this.addKeyword("$async");
117 _addDefaultMetaSchema() {
118 const { $data, meta } = this.opts;
120 this.addMetaSchema($dataRefSchema, $dataRefSchema.$id, false);
123 const { meta } = this.opts;
124 return (this.opts.defaultMeta = typeof meta == "object" ? meta.$id || meta : undefined);
126 validate(schemaKeyRef, // key, ref or schema object
127 data // to be validated
130 if (typeof schemaKeyRef == "string") {
131 v = this.getSchema(schemaKeyRef);
133 throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
136 v = this.compile(schemaKeyRef);
138 const valid = v(data);
139 if (!("$async" in v))
140 this.errors = v.errors;
143 compile(schema, _meta) {
144 const sch = this._addSchema(schema, _meta);
145 return (sch.validate || this._compileSchemaEnv(sch));
147 compileAsync(schema, meta) {
148 if (typeof this.opts.loadSchema != "function") {
149 throw new Error("options.loadSchema should be a function");
151 const { loadSchema } = this.opts;
152 return runCompileAsync.call(this, schema, meta);
153 async function runCompileAsync(_schema, _meta) {
154 await loadMetaSchema.call(this, _schema.$schema);
155 const sch = this._addSchema(_schema, _meta);
156 return sch.validate || _compileAsync.call(this, sch);
158 async function loadMetaSchema($ref) {
159 if ($ref && !this.getSchema($ref)) {
160 await runCompileAsync.call(this, { $ref }, true);
163 async function _compileAsync(sch) {
165 return this._compileSchemaEnv(sch);
168 if (!(e instanceof ref_error_1.default))
170 checkLoaded.call(this, e);
171 await loadMissingSchema.call(this, e.missingSchema);
172 return _compileAsync.call(this, sch);
175 function checkLoaded({ missingSchema: ref, missingRef }) {
176 if (this.refs[ref]) {
177 throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
180 async function loadMissingSchema(ref) {
181 const _schema = await _loadSchema.call(this, ref);
183 await loadMetaSchema.call(this, _schema.$schema);
185 this.addSchema(_schema, ref, meta);
187 async function _loadSchema(ref) {
188 const p = this._loading[ref];
192 return await (this._loading[ref] = loadSchema(ref));
195 delete this._loading[ref];
199 // Adds schema to the instance
200 addSchema(schema, // If array is passed, `key` will be ignored
201 key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
202 _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
203 _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
205 if (Array.isArray(schema)) {
206 for (const sch of schema)
207 this.addSchema(sch, undefined, _meta, _validateSchema);
211 if (typeof schema === "object") {
213 if (id !== undefined && typeof id != "string")
214 throw new Error("schema $id must be string");
216 key = resolve_1.normalizeId(key || id);
217 this._checkUnique(key);
218 this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
221 // Add schema that will be used to validate other schemas
222 // options in META_IGNORE_OPTIONS are alway set to false
223 addMetaSchema(schema, key, // schema key
224 _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
226 this.addSchema(schema, key, true, _validateSchema);
229 // Validate schema against its meta-schema
230 validateSchema(schema, throwOrLogError) {
231 if (typeof schema == "boolean")
234 $schema = schema.$schema;
235 if ($schema !== undefined && typeof $schema != "string") {
236 throw new Error("$schema must be a string");
238 $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
240 this.logger.warn("meta-schema not available");
244 const valid = this.validate($schema, schema);
245 if (!valid && throwOrLogError) {
246 const message = "schema is invalid: " + this.errorsText();
247 if (this.opts.validateSchema === "log")
248 this.logger.error(message);
250 throw new Error(message);
254 // Get compiled schema by `key` or `ref`.
255 // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
258 while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
260 if (sch === undefined) {
261 const root = new compile_1.SchemaEnv({ schema: {} });
262 sch = compile_1.resolveSchema.call(this, root, keyRef);
265 this.refs[keyRef] = sch;
267 return (sch.validate || this._compileSchemaEnv(sch));
269 // Remove cached schema(s).
270 // If no parameter is passed all schemas but meta-schemas are removed.
271 // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
272 // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
273 removeSchema(schemaKeyRef) {
274 if (schemaKeyRef instanceof RegExp) {
275 this._removeAllSchemas(this.schemas, schemaKeyRef);
276 this._removeAllSchemas(this.refs, schemaKeyRef);
279 switch (typeof schemaKeyRef) {
281 this._removeAllSchemas(this.schemas);
282 this._removeAllSchemas(this.refs);
286 const sch = getSchEnv.call(this, schemaKeyRef);
287 if (typeof sch == "object")
288 this._cache.delete(sch.schema);
289 delete this.schemas[schemaKeyRef];
290 delete this.refs[schemaKeyRef];
294 const cacheKey = schemaKeyRef;
295 this._cache.delete(cacheKey);
296 let id = schemaKeyRef.$id;
298 id = resolve_1.normalizeId(id);
299 delete this.schemas[id];
300 delete this.refs[id];
305 throw new Error("ajv.removeSchema: invalid parameter");
308 // add "vocabulary" - a collection of keywords
309 addVocabulary(definitions) {
310 for (const def of definitions)
311 this.addKeyword(def);
314 addKeyword(kwdOrDef, def // deprecated
317 if (typeof kwdOrDef == "string") {
319 if (typeof def == "object") {
320 this.logger.warn("these parameters are deprecated, see docs for addKeyword");
321 def.keyword = keyword;
324 else if (typeof kwdOrDef == "object" && def === undefined) {
326 keyword = def.keyword;
327 if (Array.isArray(keyword) && !keyword.length) {
328 throw new Error("addKeywords: keyword must be string or non-empty array");
332 throw new Error("invalid addKeywords parameters");
334 checkKeyword.call(this, keyword, def);
336 util_1.eachItem(keyword, (kwd) => addRule.call(this, kwd));
339 keywordMetaschema.call(this, def);
342 type: dataType_1.getJSONTypes(def.type),
343 schemaType: dataType_1.getJSONTypes(def.schemaType),
345 util_1.eachItem(keyword, definition.type.length === 0
346 ? (k) => addRule.call(this, k, definition)
347 : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
350 getKeyword(keyword) {
351 const rule = this.RULES.all[keyword];
352 return typeof rule == "object" ? rule.definition : !!rule;
355 removeKeyword(keyword) {
356 // TODO return type should be Ajv
357 const { RULES } = this;
358 delete RULES.keywords[keyword];
359 delete RULES.all[keyword];
360 for (const group of RULES.rules) {
361 const i = group.rules.findIndex((rule) => rule.keyword === keyword);
363 group.rules.splice(i, 1);
368 addFormat(name, format) {
369 if (typeof format == "string")
370 format = new RegExp(format);
371 this.formats[name] = format;
374 errorsText(errors = this.errors, // optional array of validation errors
375 { separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar`
377 if (!errors || errors.length === 0)
380 .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
381 .reduce((text, msg) => text + separator + msg);
383 $dataMetaSchema(metaSchema, keywordsJsonPointers) {
384 const rules = this.RULES.all;
385 metaSchema = JSON.parse(JSON.stringify(metaSchema));
386 for (const jsonPointer of keywordsJsonPointers) {
387 const segments = jsonPointer.split("/").slice(1); // first segment is an empty string
388 let keywords = metaSchema;
389 for (const seg of segments)
390 keywords = keywords[seg];
391 for (const key in rules) {
392 const rule = rules[key];
393 if (typeof rule != "object")
395 const { $data } = rule.definition;
396 const schema = keywords[key];
398 keywords[key] = schemaOrData(schema);
403 _removeAllSchemas(schemas, regex) {
404 for (const keyRef in schemas) {
405 const sch = schemas[keyRef];
406 if (!regex || regex.test(keyRef)) {
407 if (typeof sch == "string") {
408 delete schemas[keyRef];
410 else if (sch && !sch.meta) {
411 this._cache.delete(sch.schema);
412 delete schemas[keyRef];
417 _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
419 if (typeof schema == "object") {
424 throw new Error("schema must be object");
425 else if (typeof schema != "boolean")
426 throw new Error("schema must be object or boolean");
428 let sch = this._cache.get(schema);
429 if (sch !== undefined)
431 const localRefs = resolve_1.getSchemaRefs.call(this, schema);
432 baseId = resolve_1.normalizeId(id || baseId);
433 sch = new compile_1.SchemaEnv({ schema, meta, baseId, localRefs });
434 this._cache.set(sch.schema, sch);
435 if (addSchema && !baseId.startsWith("#")) {
436 // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
438 this._checkUnique(baseId);
439 this.refs[baseId] = sch;
442 this.validateSchema(schema, true);
446 if (this.schemas[id] || this.refs[id]) {
447 throw new Error(`schema with key or id "${id}" already exists`);
450 _compileSchemaEnv(sch) {
452 this._compileMetaSchema(sch);
454 compile_1.compileSchema.call(this, sch);
455 /* istanbul ignore if */
457 throw new Error("ajv implementation error");
460 _compileMetaSchema(sch) {
461 const currentOpts = this.opts;
462 this.opts = this._metaOpts;
464 compile_1.compileSchema.call(this, sch);
467 this.opts = currentOpts;
471 exports.default = Ajv;
472 Ajv.ValidationError = validation_error_1.default;
473 Ajv.MissingRefError = ref_error_1.default;
474 function checkOptions(checkOpts, options, msg, log = "error") {
475 for (const key in checkOpts) {
478 this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
481 function getSchEnv(keyRef) {
482 keyRef = resolve_1.normalizeId(keyRef); // TODO tests fail without this line
483 return this.schemas[keyRef] || this.refs[keyRef];
485 function addInitialSchemas() {
486 const optsSchemas = this.opts.schemas;
489 if (Array.isArray(optsSchemas))
490 this.addSchema(optsSchemas);
492 for (const key in optsSchemas)
493 this.addSchema(optsSchemas[key], key);
495 function addInitialFormats() {
496 for (const name in this.opts.formats) {
497 const format = this.opts.formats[name];
499 this.addFormat(name, format);
502 function addInitialKeywords(defs) {
503 if (Array.isArray(defs)) {
504 this.addVocabulary(defs);
507 this.logger.warn("keywords option as map is deprecated, pass array");
508 for (const keyword in defs) {
509 const def = defs[keyword];
511 def.keyword = keyword;
512 this.addKeyword(def);
515 function getMetaSchemaOptions() {
516 const metaOpts = { ...this.opts };
517 for (const opt of META_IGNORE_OPTIONS)
518 delete metaOpts[opt];
521 const noLogs = { log() { }, warn() { }, error() { } };
522 function getLogger(logger) {
523 if (logger === false)
525 if (logger === undefined)
527 if (logger.log && logger.warn && logger.error)
529 throw new Error("logger must implement log, warn and error methods");
531 const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
532 function checkKeyword(keyword, def) {
533 const { RULES } = this;
534 util_1.eachItem(keyword, (kwd) => {
535 if (RULES.keywords[kwd])
536 throw new Error(`Keyword ${kwd} is already defined`);
537 if (!KEYWORD_NAME.test(kwd))
538 throw new Error(`Keyword ${kwd} has invalid name`);
542 if (def.$data && !("code" in def || "validate" in def)) {
543 throw new Error('$data keyword must have "code" or "validate" function');
546 function addRule(keyword, definition, dataType) {
548 const post = definition === null || definition === void 0 ? void 0 : definition.post;
549 if (dataType && post)
550 throw new Error('keyword with "post" flag cannot have "type"');
551 const { RULES } = this;
552 let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
554 ruleGroup = { type: dataType, rules: [] };
555 RULES.rules.push(ruleGroup);
557 RULES.keywords[keyword] = true;
564 type: dataType_1.getJSONTypes(definition.type),
565 schemaType: dataType_1.getJSONTypes(definition.schemaType),
568 if (definition.before)
569 addBeforeRule.call(this, ruleGroup, rule, definition.before);
571 ruleGroup.rules.push(rule);
572 RULES.all[keyword] = rule;
573 (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
575 function addBeforeRule(ruleGroup, rule, before) {
576 const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
578 ruleGroup.rules.splice(i, 0, rule);
581 ruleGroup.rules.push(rule);
582 this.logger.warn(`rule ${before} is not defined`);
585 function keywordMetaschema(def) {
586 let { metaSchema } = def;
587 if (metaSchema === undefined)
589 if (def.$data && this.opts.$data)
590 metaSchema = schemaOrData(metaSchema);
591 def.validateSchema = this.compile(metaSchema, true);
594 $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
596 function schemaOrData(schema) {
597 return { anyOf: [schema, $dataRef] };
599 //# sourceMappingURL=core.js.map