Path: blob/master/node_modules/ajv/lib/ajv.js
2515 views
'use strict';12var compileSchema = require('./compile')3, resolve = require('./compile/resolve')4, Cache = require('./cache')5, SchemaObject = require('./compile/schema_obj')6, stableStringify = require('fast-json-stable-stringify')7, formats = require('./compile/formats')8, rules = require('./compile/rules')9, $dataMetaSchema = require('./data')10, util = require('./compile/util');1112module.exports = Ajv;1314Ajv.prototype.validate = validate;15Ajv.prototype.compile = compile;16Ajv.prototype.addSchema = addSchema;17Ajv.prototype.addMetaSchema = addMetaSchema;18Ajv.prototype.validateSchema = validateSchema;19Ajv.prototype.getSchema = getSchema;20Ajv.prototype.removeSchema = removeSchema;21Ajv.prototype.addFormat = addFormat;22Ajv.prototype.errorsText = errorsText;2324Ajv.prototype._addSchema = _addSchema;25Ajv.prototype._compile = _compile;2627Ajv.prototype.compileAsync = require('./compile/async');28var customKeyword = require('./keyword');29Ajv.prototype.addKeyword = customKeyword.add;30Ajv.prototype.getKeyword = customKeyword.get;31Ajv.prototype.removeKeyword = customKeyword.remove;32Ajv.prototype.validateKeyword = customKeyword.validate;3334var errorClasses = require('./compile/error_classes');35Ajv.ValidationError = errorClasses.Validation;36Ajv.MissingRefError = errorClasses.MissingRef;37Ajv.$dataMetaSchema = $dataMetaSchema;3839var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';4041var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];42var META_SUPPORT_DATA = ['/properties'];4344/**45* Creates validator instance.46* Usage: `Ajv(opts)`47* @param {Object} opts optional options48* @return {Object} ajv instance49*/50function Ajv(opts) {51if (!(this instanceof Ajv)) return new Ajv(opts);52opts = this._opts = util.copy(opts) || {};53setLogger(this);54this._schemas = {};55this._refs = {};56this._fragments = {};57this._formats = formats(opts.format);5859this._cache = opts.cache || new Cache;60this._loadingSchemas = {};61this._compilations = [];62this.RULES = rules();63this._getId = chooseGetId(opts);6465opts.loopRequired = opts.loopRequired || Infinity;66if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;67if (opts.serialize === undefined) opts.serialize = stableStringify;68this._metaOpts = getMetaSchemaOptions(this);6970if (opts.formats) addInitialFormats(this);71if (opts.keywords) addInitialKeywords(this);72addDefaultMetaSchema(this);73if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);74if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});75addInitialSchemas(this);76}77787980/**81* Validate data using schema82* Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.83* @this Ajv84* @param {String|Object} schemaKeyRef key, ref or schema object85* @param {Any} data to be validated86* @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).87*/88function validate(schemaKeyRef, data) {89var v;90if (typeof schemaKeyRef == 'string') {91v = this.getSchema(schemaKeyRef);92if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');93} else {94var schemaObj = this._addSchema(schemaKeyRef);95v = schemaObj.validate || this._compile(schemaObj);96}9798var valid = v(data);99if (v.$async !== true) this.errors = v.errors;100return valid;101}102103104/**105* Create validating function for passed schema.106* @this Ajv107* @param {Object} schema schema object108* @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.109* @return {Function} validating function110*/111function compile(schema, _meta) {112var schemaObj = this._addSchema(schema, undefined, _meta);113return schemaObj.validate || this._compile(schemaObj);114}115116117/**118* Adds schema to the instance.119* @this Ajv120* @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.121* @param {String} 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`.122* @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.123* @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.124* @return {Ajv} this for method chaining125*/126function addSchema(schema, key, _skipValidation, _meta) {127if (Array.isArray(schema)){128for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);129return this;130}131var id = this._getId(schema);132if (id !== undefined && typeof id != 'string')133throw new Error('schema id must be string');134key = resolve.normalizeId(key || id);135checkUnique(this, key);136this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);137return this;138}139140141/**142* Add schema that will be used to validate other schemas143* options in META_IGNORE_OPTIONS are alway set to false144* @this Ajv145* @param {Object} schema schema object146* @param {String} key optional schema key147* @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema148* @return {Ajv} this for method chaining149*/150function addMetaSchema(schema, key, skipValidation) {151this.addSchema(schema, key, skipValidation, true);152return this;153}154155156/**157* Validate schema158* @this Ajv159* @param {Object} schema schema to validate160* @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid161* @return {Boolean} true if schema is valid162*/163function validateSchema(schema, throwOrLogError) {164var $schema = schema.$schema;165if ($schema !== undefined && typeof $schema != 'string')166throw new Error('$schema must be a string');167$schema = $schema || this._opts.defaultMeta || defaultMeta(this);168if (!$schema) {169this.logger.warn('meta-schema not available');170this.errors = null;171return true;172}173var valid = this.validate($schema, schema);174if (!valid && throwOrLogError) {175var message = 'schema is invalid: ' + this.errorsText();176if (this._opts.validateSchema == 'log') this.logger.error(message);177else throw new Error(message);178}179return valid;180}181182183function defaultMeta(self) {184var meta = self._opts.meta;185self._opts.defaultMeta = typeof meta == 'object'186? self._getId(meta) || meta187: self.getSchema(META_SCHEMA_ID)188? META_SCHEMA_ID189: undefined;190return self._opts.defaultMeta;191}192193194/**195* Get compiled schema from the instance by `key` or `ref`.196* @this Ajv197* @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).198* @return {Function} schema validating function (with property `schema`).199*/200function getSchema(keyRef) {201var schemaObj = _getSchemaObj(this, keyRef);202switch (typeof schemaObj) {203case 'object': return schemaObj.validate || this._compile(schemaObj);204case 'string': return this.getSchema(schemaObj);205case 'undefined': return _getSchemaFragment(this, keyRef);206}207}208209210function _getSchemaFragment(self, ref) {211var res = resolve.schema.call(self, { schema: {} }, ref);212if (res) {213var schema = res.schema214, root = res.root215, baseId = res.baseId;216var v = compileSchema.call(self, schema, root, undefined, baseId);217self._fragments[ref] = new SchemaObject({218ref: ref,219fragment: true,220schema: schema,221root: root,222baseId: baseId,223validate: v224});225return v;226}227}228229230function _getSchemaObj(self, keyRef) {231keyRef = resolve.normalizeId(keyRef);232return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];233}234235236/**237* Remove cached schema(s).238* If no parameter is passed all schemas but meta-schemas are removed.239* If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.240* Even if schema is referenced by other schemas it still can be removed as other schemas have local references.241* @this Ajv242* @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object243* @return {Ajv} this for method chaining244*/245function removeSchema(schemaKeyRef) {246if (schemaKeyRef instanceof RegExp) {247_removeAllSchemas(this, this._schemas, schemaKeyRef);248_removeAllSchemas(this, this._refs, schemaKeyRef);249return this;250}251switch (typeof schemaKeyRef) {252case 'undefined':253_removeAllSchemas(this, this._schemas);254_removeAllSchemas(this, this._refs);255this._cache.clear();256return this;257case 'string':258var schemaObj = _getSchemaObj(this, schemaKeyRef);259if (schemaObj) this._cache.del(schemaObj.cacheKey);260delete this._schemas[schemaKeyRef];261delete this._refs[schemaKeyRef];262return this;263case 'object':264var serialize = this._opts.serialize;265var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;266this._cache.del(cacheKey);267var id = this._getId(schemaKeyRef);268if (id) {269id = resolve.normalizeId(id);270delete this._schemas[id];271delete this._refs[id];272}273}274return this;275}276277278function _removeAllSchemas(self, schemas, regex) {279for (var keyRef in schemas) {280var schemaObj = schemas[keyRef];281if (!schemaObj.meta && (!regex || regex.test(keyRef))) {282self._cache.del(schemaObj.cacheKey);283delete schemas[keyRef];284}285}286}287288289/* @this Ajv */290function _addSchema(schema, skipValidation, meta, shouldAddSchema) {291if (typeof schema != 'object' && typeof schema != 'boolean')292throw new Error('schema should be object or boolean');293var serialize = this._opts.serialize;294var cacheKey = serialize ? serialize(schema) : schema;295var cached = this._cache.get(cacheKey);296if (cached) return cached;297298shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;299300var id = resolve.normalizeId(this._getId(schema));301if (id && shouldAddSchema) checkUnique(this, id);302303var willValidate = this._opts.validateSchema !== false && !skipValidation;304var recursiveMeta;305if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))306this.validateSchema(schema, true);307308var localRefs = resolve.ids.call(this, schema);309310var schemaObj = new SchemaObject({311id: id,312schema: schema,313localRefs: localRefs,314cacheKey: cacheKey,315meta: meta316});317318if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;319this._cache.put(cacheKey, schemaObj);320321if (willValidate && recursiveMeta) this.validateSchema(schema, true);322323return schemaObj;324}325326327/* @this Ajv */328function _compile(schemaObj, root) {329if (schemaObj.compiling) {330schemaObj.validate = callValidate;331callValidate.schema = schemaObj.schema;332callValidate.errors = null;333callValidate.root = root ? root : callValidate;334if (schemaObj.schema.$async === true)335callValidate.$async = true;336return callValidate;337}338schemaObj.compiling = true;339340var currentOpts;341if (schemaObj.meta) {342currentOpts = this._opts;343this._opts = this._metaOpts;344}345346var v;347try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }348catch(e) {349delete schemaObj.validate;350throw e;351}352finally {353schemaObj.compiling = false;354if (schemaObj.meta) this._opts = currentOpts;355}356357schemaObj.validate = v;358schemaObj.refs = v.refs;359schemaObj.refVal = v.refVal;360schemaObj.root = v.root;361return v;362363364/* @this {*} - custom context, see passContext option */365function callValidate() {366/* jshint validthis: true */367var _validate = schemaObj.validate;368var result = _validate.apply(this, arguments);369callValidate.errors = _validate.errors;370return result;371}372}373374375function chooseGetId(opts) {376switch (opts.schemaId) {377case 'auto': return _get$IdOrId;378case 'id': return _getId;379default: return _get$Id;380}381}382383/* @this Ajv */384function _getId(schema) {385if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);386return schema.id;387}388389/* @this Ajv */390function _get$Id(schema) {391if (schema.id) this.logger.warn('schema id ignored', schema.id);392return schema.$id;393}394395396function _get$IdOrId(schema) {397if (schema.$id && schema.id && schema.$id != schema.id)398throw new Error('schema $id is different from id');399return schema.$id || schema.id;400}401402403/**404* Convert array of error message objects to string405* @this Ajv406* @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.407* @param {Object} options optional options with properties `separator` and `dataVar`.408* @return {String} human readable string with all errors descriptions409*/410function errorsText(errors, options) {411errors = errors || this.errors;412if (!errors) return 'No errors';413options = options || {};414var separator = options.separator === undefined ? ', ' : options.separator;415var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;416417var text = '';418for (var i=0; i<errors.length; i++) {419var e = errors[i];420if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;421}422return text.slice(0, -separator.length);423}424425426/**427* Add custom format428* @this Ajv429* @param {String} name format name430* @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)431* @return {Ajv} this for method chaining432*/433function addFormat(name, format) {434if (typeof format == 'string') format = new RegExp(format);435this._formats[name] = format;436return this;437}438439440function addDefaultMetaSchema(self) {441var $dataSchema;442if (self._opts.$data) {443$dataSchema = require('./refs/data.json');444self.addMetaSchema($dataSchema, $dataSchema.$id, true);445}446if (self._opts.meta === false) return;447var metaSchema = require('./refs/json-schema-draft-07.json');448if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);449self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);450self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;451}452453454function addInitialSchemas(self) {455var optsSchemas = self._opts.schemas;456if (!optsSchemas) return;457if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);458else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);459}460461462function addInitialFormats(self) {463for (var name in self._opts.formats) {464var format = self._opts.formats[name];465self.addFormat(name, format);466}467}468469470function addInitialKeywords(self) {471for (var name in self._opts.keywords) {472var keyword = self._opts.keywords[name];473self.addKeyword(name, keyword);474}475}476477478function checkUnique(self, id) {479if (self._schemas[id] || self._refs[id])480throw new Error('schema with key or id "' + id + '" already exists');481}482483484function getMetaSchemaOptions(self) {485var metaOpts = util.copy(self._opts);486for (var i=0; i<META_IGNORE_OPTIONS.length; i++)487delete metaOpts[META_IGNORE_OPTIONS[i]];488return metaOpts;489}490491492function setLogger(self) {493var logger = self._opts.logger;494if (logger === false) {495self.logger = {log: noop, warn: noop, error: noop};496} else {497if (logger === undefined) logger = console;498if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error))499throw new Error('logger must implement log, warn and error methods');500self.logger = logger;501}502}503504505function noop() {}506507508