| 1 | 'use strict'; |
| 2 | |
| 3 | var compileSchema = require('./compile') |
| 4 | , resolve = require('./compile/resolve') |
| 5 | , Cache = require('./cache') |
| 6 | , SchemaObject = require('./compile/schema_obj') |
| 7 | , stableStringify = require('fast-json-stable-stringify') |
| 8 | , formats = require('./compile/formats') |
| 9 | , rules = require('./compile/rules') |
| 10 | , $dataMetaSchema = require('./$data') |
| 11 | , patternGroups = require('./patternGroups') |
| 12 | , util = require('./compile/util') |
| 13 | , co = require('co'); |
| 14 | |
| 15 | module.exports = Ajv; |
| 16 | |
| 17 | Ajv.prototype.validate = validate; |
| 18 | Ajv.prototype.compile = compile; |
| 19 | Ajv.prototype.addSchema = addSchema; |
| 20 | Ajv.prototype.addMetaSchema = addMetaSchema; |
| 21 | Ajv.prototype.validateSchema = validateSchema; |
| 22 | Ajv.prototype.getSchema = getSchema; |
| 23 | Ajv.prototype.removeSchema = removeSchema; |
| 24 | Ajv.prototype.addFormat = addFormat; |
| 25 | Ajv.prototype.errorsText = errorsText; |
| 26 | |
| 27 | Ajv.prototype._addSchema = _addSchema; |
| 28 | Ajv.prototype._compile = _compile; |
| 29 | |
| 30 | Ajv.prototype.compileAsync = require('./compile/async'); |
| 31 | var customKeyword = require('./keyword'); |
| 32 | Ajv.prototype.addKeyword = customKeyword.add; |
| 33 | Ajv.prototype.getKeyword = customKeyword.get; |
| 34 | Ajv.prototype.removeKeyword = customKeyword.remove; |
| 35 | |
| 36 | var errorClasses = require('./compile/error_classes'); |
| 37 | Ajv.ValidationError = errorClasses.Validation; |
| 38 | Ajv.MissingRefError = errorClasses.MissingRef; |
| 39 | Ajv.$dataMetaSchema = $dataMetaSchema; |
| 40 | |
| 41 | var META_SCHEMA_ID = 'http://json-schema.org/draft-06/schema'; |
| 42 | |
| 43 | var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes' ]; |
| 44 | var META_SUPPORT_DATA = ['/properties']; |
| 45 | |
| 46 | /** |
| 47 | * Creates validator instance. |
| 48 | * Usage: `Ajv(opts)` |
| 49 | * @param {Object} opts optional options |
| 50 | * @return {Object} ajv instance |
| 51 | */ |
| 52 | function Ajv(opts) { |
| 53 | if (!(this instanceof Ajv)) return new Ajv(opts); |
| 54 | opts = this._opts = util.copy(opts) || {}; |
| 55 | setLogger(this); |
| 56 | this._schemas = {}; |
| 57 | this._refs = {}; |
| 58 | this._fragments = {}; |
| 59 | this._formats = formats(opts.format); |
| 60 | var schemaUriFormat = this._schemaUriFormat = this._formats['uri-reference']; |
| 61 | this._schemaUriFormatFunc = function (str) { return schemaUriFormat.test(str); }; |
| 62 | |
| 63 | this._cache = opts.cache || new Cache; |
| 64 | this._loadingSchemas = {}; |
| 65 | this._compilations = []; |
| 66 | this.RULES = rules(); |
| 67 | this._getId = chooseGetId(opts); |
| 68 | |
| 69 | opts.loopRequired = opts.loopRequired || Infinity; |
| 70 | if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; |
| 71 | if (opts.serialize === undefined) opts.serialize = stableStringify; |
| 72 | this._metaOpts = getMetaSchemaOptions(this); |
| 73 | |
| 74 | if (opts.formats) addInitialFormats(this); |
| 75 | addDraft6MetaSchema(this); |
| 76 | if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); |
| 77 | addInitialSchemas(this); |
| 78 | if (opts.patternGroups) patternGroups(this); |
| 79 | } |
| 80 | |
| 81 | |
| 82 | |
| 83 | /** |
| 84 | * Validate data using schema |
| 85 | * 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. |
| 86 | * @this Ajv |
| 87 | * @param {String|Object} schemaKeyRef key, ref or schema object |
| 88 | * @param {Any} data to be validated |
| 89 | * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). |
| 90 | */ |
| 91 | function validate(schemaKeyRef, data) { |
| 92 | var v; |
| 93 | if (typeof schemaKeyRef == 'string') { |
| 94 | v = this.getSchema(schemaKeyRef); |
| 95 | if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); |
| 96 | } else { |
| 97 | var schemaObj = this._addSchema(schemaKeyRef); |
| 98 | v = schemaObj.validate || this._compile(schemaObj); |
| 99 | } |
| 100 | |
| 101 | var valid = v(data); |
| 102 | if (v.$async === true) |
| 103 | return this._opts.async == '*' ? co(valid) : valid; |
| 104 | this.errors = v.errors; |
| 105 | return valid; |
| 106 | } |
| 107 | |
| 108 | |
| 109 | /** |
| 110 | * Create validating function for passed schema. |
| 111 | * @this Ajv |
| 112 | * @param {Object} schema schema object |
| 113 | * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. |
| 114 | * @return {Function} validating function |
| 115 | */ |
| 116 | function compile(schema, _meta) { |
| 117 | var schemaObj = this._addSchema(schema, undefined, _meta); |
| 118 | return schemaObj.validate || this._compile(schemaObj); |
| 119 | } |
| 120 | |
| 121 | |
| 122 | /** |
| 123 | * Adds schema to the instance. |
| 124 | * @this Ajv |
| 125 | * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. |
| 126 | * @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`. |
| 127 | * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. |
| 128 | * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. |
| 129 | * @return {Ajv} this for method chaining |
| 130 | */ |
| 131 | function addSchema(schema, key, _skipValidation, _meta) { |
| 132 | if (Array.isArray(schema)){ |
| 133 | for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta); |
| 134 | return this; |
| 135 | } |
| 136 | var id = this._getId(schema); |
| 137 | if (id !== undefined && typeof id != 'string') |
| 138 | throw new Error('schema id must be string'); |
| 139 | key = resolve.normalizeId(key || id); |
| 140 | checkUnique(this, key); |
| 141 | this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true); |
| 142 | return this; |
| 143 | } |
| 144 | |
| 145 | |
| 146 | /** |
| 147 | * Add schema that will be used to validate other schemas |
| 148 | * options in META_IGNORE_OPTIONS are alway set to false |
| 149 | * @this Ajv |
| 150 | * @param {Object} schema schema object |
| 151 | * @param {String} key optional schema key |
| 152 | * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema |
| 153 | * @return {Ajv} this for method chaining |
| 154 | */ |
| 155 | function addMetaSchema(schema, key, skipValidation) { |
| 156 | this.addSchema(schema, key, skipValidation, true); |
| 157 | return this; |
| 158 | } |
| 159 | |
| 160 | |
| 161 | /** |
| 162 | * Validate schema |
| 163 | * @this Ajv |
| 164 | * @param {Object} schema schema to validate |
| 165 | * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid |
| 166 | * @return {Boolean} true if schema is valid |
| 167 | */ |
| 168 | function validateSchema(schema, throwOrLogError) { |
| 169 | var $schema = schema.$schema; |
| 170 | if ($schema !== undefined && typeof $schema != 'string') |
| 171 | throw new Error('$schema must be a string'); |
| 172 | $schema = $schema || this._opts.defaultMeta || defaultMeta(this); |
| 173 | if (!$schema) { |
| 174 | this.logger.warn('meta-schema not available'); |
| 175 | this.errors = null; |
| 176 | return true; |
| 177 | } |
| 178 | var currentUriFormat = this._formats.uri; |
| 179 | this._formats.uri = typeof currentUriFormat == 'function' |
| 180 | ? this._schemaUriFormatFunc |
| 181 | : this._schemaUriFormat; |
| 182 | var valid; |
| 183 | try { valid = this.validate($schema, schema); } |
| 184 | finally { this._formats.uri = currentUriFormat; } |
| 185 | if (!valid && throwOrLogError) { |
| 186 | var message = 'schema is invalid: ' + this.errorsText(); |
| 187 | if (this._opts.validateSchema == 'log') this.logger.error(message); |
| 188 | else throw new Error(message); |
| 189 | } |
| 190 | return valid; |
| 191 | } |
| 192 | |
| 193 | |
| 194 | function defaultMeta(self) { |
| 195 | var meta = self._opts.meta; |
| 196 | self._opts.defaultMeta = typeof meta == 'object' |
| 197 | ? self._getId(meta) || meta |
| 198 | : self.getSchema(META_SCHEMA_ID) |
| 199 | ? META_SCHEMA_ID |
| 200 | : undefined; |
| 201 | return self._opts.defaultMeta; |
| 202 | } |
| 203 | |
| 204 | |
| 205 | /** |
| 206 | * Get compiled schema from the instance by `key` or `ref`. |
| 207 | * @this Ajv |
| 208 | * @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id). |
| 209 | * @return {Function} schema validating function (with property `schema`). |
| 210 | */ |
| 211 | function getSchema(keyRef) { |
| 212 | var schemaObj = _getSchemaObj(this, keyRef); |
| 213 | switch (typeof schemaObj) { |
| 214 | case 'object': return schemaObj.validate || this._compile(schemaObj); |
| 215 | case 'string': return this.getSchema(schemaObj); |
| 216 | case 'undefined': return _getSchemaFragment(this, keyRef); |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | |
| 221 | function _getSchemaFragment(self, ref) { |
| 222 | var res = resolve.schema.call(self, { schema: {} }, ref); |
| 223 | if (res) { |
| 224 | var schema = res.schema |
| 225 | , root = res.root |
| 226 | , baseId = res.baseId; |
| 227 | var v = compileSchema.call(self, schema, root, undefined, baseId); |
| 228 | self._fragments[ref] = new SchemaObject({ |
| 229 | ref: ref, |
| 230 | fragment: true, |
| 231 | schema: schema, |
| 232 | root: root, |
| 233 | baseId: baseId, |
| 234 | validate: v |
| 235 | }); |
| 236 | return v; |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | |
| 241 | function _getSchemaObj(self, keyRef) { |
| 242 | keyRef = resolve.normalizeId(keyRef); |
| 243 | return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef]; |
| 244 | } |
| 245 | |
| 246 | |
| 247 | /** |
| 248 | * Remove cached schema(s). |
| 249 | * If no parameter is passed all schemas but meta-schemas are removed. |
| 250 | * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. |
| 251 | * Even if schema is referenced by other schemas it still can be removed as other schemas have local references. |
| 252 | * @this Ajv |
| 253 | * @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object |
| 254 | * @return {Ajv} this for method chaining |
| 255 | */ |
| 256 | function removeSchema(schemaKeyRef) { |
| 257 | if (schemaKeyRef instanceof RegExp) { |
| 258 | _removeAllSchemas(this, this._schemas, schemaKeyRef); |
| 259 | _removeAllSchemas(this, this._refs, schemaKeyRef); |
| 260 | return this; |
| 261 | } |
| 262 | switch (typeof schemaKeyRef) { |
| 263 | case 'undefined': |
| 264 | _removeAllSchemas(this, this._schemas); |
| 265 | _removeAllSchemas(this, this._refs); |
| 266 | this._cache.clear(); |
| 267 | return this; |
| 268 | case 'string': |
| 269 | var schemaObj = _getSchemaObj(this, schemaKeyRef); |
| 270 | if (schemaObj) this._cache.del(schemaObj.cacheKey); |
| 271 | delete this._schemas[schemaKeyRef]; |
| 272 | delete this._refs[schemaKeyRef]; |
| 273 | return this; |
| 274 | case 'object': |
| 275 | var serialize = this._opts.serialize; |
| 276 | var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef; |
| 277 | this._cache.del(cacheKey); |
| 278 | var id = this._getId(schemaKeyRef); |
| 279 | if (id) { |
| 280 | id = resolve.normalizeId(id); |
| 281 | delete this._schemas[id]; |
| 282 | delete this._refs[id]; |
| 283 | } |
| 284 | } |
| 285 | return this; |
| 286 | } |
| 287 | |
| 288 | |
| 289 | function _removeAllSchemas(self, schemas, regex) { |
| 290 | for (var keyRef in schemas) { |
| 291 | var schemaObj = schemas[keyRef]; |
| 292 | if (!schemaObj.meta && (!regex || regex.test(keyRef))) { |
| 293 | self._cache.del(schemaObj.cacheKey); |
| 294 | delete schemas[keyRef]; |
| 295 | } |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | |
| 300 | /* @this Ajv */ |
| 301 | function _addSchema(schema, skipValidation, meta, shouldAddSchema) { |
| 302 | if (typeof schema != 'object' && typeof schema != 'boolean') |
| 303 | throw new Error('schema should be object or boolean'); |
| 304 | var serialize = this._opts.serialize; |
| 305 | var cacheKey = serialize ? serialize(schema) : schema; |
| 306 | var cached = this._cache.get(cacheKey); |
| 307 | if (cached) return cached; |
| 308 | |
| 309 | shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false; |
| 310 | |
| 311 | var id = resolve.normalizeId(this._getId(schema)); |
| 312 | if (id && shouldAddSchema) checkUnique(this, id); |
| 313 | |
| 314 | var willValidate = this._opts.validateSchema !== false && !skipValidation; |
| 315 | var recursiveMeta; |
| 316 | if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema))) |
| 317 | this.validateSchema(schema, true); |
| 318 | |
| 319 | var localRefs = resolve.ids.call(this, schema); |
| 320 | |
| 321 | var schemaObj = new SchemaObject({ |
| 322 | id: id, |
| 323 | schema: schema, |
| 324 | localRefs: localRefs, |
| 325 | cacheKey: cacheKey, |
| 326 | meta: meta |
| 327 | }); |
| 328 | |
| 329 | if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj; |
| 330 | this._cache.put(cacheKey, schemaObj); |
| 331 | |
| 332 | if (willValidate && recursiveMeta) this.validateSchema(schema, true); |
| 333 | |
| 334 | return schemaObj; |
| 335 | } |
| 336 | |
| 337 | |
| 338 | /* @this Ajv */ |
| 339 | function _compile(schemaObj, root) { |
| 340 | if (schemaObj.compiling) { |
| 341 | schemaObj.validate = callValidate; |
| 342 | callValidate.schema = schemaObj.schema; |
| 343 | callValidate.errors = null; |
| 344 | callValidate.root = root ? root : callValidate; |
| 345 | if (schemaObj.schema.$async === true) |
| 346 | callValidate.$async = true; |
| 347 | return callValidate; |
| 348 | } |
| 349 | schemaObj.compiling = true; |
| 350 | |
| 351 | var currentOpts; |
| 352 | if (schemaObj.meta) { |
| 353 | currentOpts = this._opts; |
| 354 | this._opts = this._metaOpts; |
| 355 | } |
| 356 | |
| 357 | var v; |
| 358 | try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); } |
| 359 | finally { |
| 360 | schemaObj.compiling = false; |
| 361 | if (schemaObj.meta) this._opts = currentOpts; |
| 362 | } |
| 363 | |
| 364 | schemaObj.validate = v; |
| 365 | schemaObj.refs = v.refs; |
| 366 | schemaObj.refVal = v.refVal; |
| 367 | schemaObj.root = v.root; |
| 368 | return v; |
| 369 | |
| 370 | |
| 371 | function callValidate() { |
| 372 | var _validate = schemaObj.validate; |
| 373 | var result = _validate.apply(null, arguments); |
| 374 | callValidate.errors = _validate.errors; |
| 375 | return result; |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | |
| 380 | function chooseGetId(opts) { |
| 381 | switch (opts.schemaId) { |
| 382 | case '$id': return _get$Id; |
| 383 | case 'id': return _getId; |
| 384 | default: return _get$IdOrId; |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | /* @this Ajv */ |
| 389 | function _getId(schema) { |
| 390 | if (schema.$id) this.logger.warn('schema $id ignored', schema.$id); |
| 391 | return schema.id; |
| 392 | } |
| 393 | |
| 394 | /* @this Ajv */ |
| 395 | function _get$Id(schema) { |
| 396 | if (schema.id) this.logger.warn('schema id ignored', schema.id); |
| 397 | return schema.$id; |
| 398 | } |
| 399 | |
| 400 | |
| 401 | function _get$IdOrId(schema) { |
| 402 | if (schema.$id && schema.id && schema.$id != schema.id) |
| 403 | throw new Error('schema $id is different from id'); |
| 404 | return schema.$id || schema.id; |
| 405 | } |
| 406 | |
| 407 | |
| 408 | /** |
| 409 | * Convert array of error message objects to string |
| 410 | * @this Ajv |
| 411 | * @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used. |
| 412 | * @param {Object} options optional options with properties `separator` and `dataVar`. |
| 413 | * @return {String} human readable string with all errors descriptions |
| 414 | */ |
| 415 | function errorsText(errors, options) { |
| 416 | errors = errors || this.errors; |
| 417 | if (!errors) return 'No errors'; |
| 418 | options = options || {}; |
| 419 | var separator = options.separator === undefined ? ', ' : options.separator; |
| 420 | var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; |
| 421 | |
| 422 | var text = ''; |
| 423 | for (var i=0; i<errors.length; i++) { |
| 424 | var e = errors[i]; |
| 425 | if (e) text += dataVar + e.dataPath + ' ' + e.message + separator; |
| 426 | } |
| 427 | return text.slice(0, -separator.length); |
| 428 | } |
| 429 | |
| 430 | |
| 431 | /** |
| 432 | * Add custom format |
| 433 | * @this Ajv |
| 434 | * @param {String} name format name |
| 435 | * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid) |
| 436 | * @return {Ajv} this for method chaining |
| 437 | */ |
| 438 | function addFormat(name, format) { |
| 439 | if (typeof format == 'string') format = new RegExp(format); |
| 440 | this._formats[name] = format; |
| 441 | return this; |
| 442 | } |
| 443 | |
| 444 | |
| 445 | function addDraft6MetaSchema(self) { |
| 446 | var $dataSchema; |
| 447 | if (self._opts.$data) { |
| 448 | $dataSchema = require('./refs/$data.json'); |
| 449 | self.addMetaSchema($dataSchema, $dataSchema.$id, true); |
| 450 | } |
| 451 | if (self._opts.meta === false) return; |
| 452 | var metaSchema = require('./refs/json-schema-draft-06.json'); |
| 453 | if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA); |
| 454 | self.addMetaSchema(metaSchema, META_SCHEMA_ID, true); |
| 455 | self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID; |
| 456 | } |
| 457 | |
| 458 | |
| 459 | function addInitialSchemas(self) { |
| 460 | var optsSchemas = self._opts.schemas; |
| 461 | if (!optsSchemas) return; |
| 462 | if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas); |
| 463 | else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key); |
| 464 | } |
| 465 | |
| 466 | |
| 467 | function addInitialFormats(self) { |
| 468 | for (var name in self._opts.formats) { |
| 469 | var format = self._opts.formats[name]; |
| 470 | self.addFormat(name, format); |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | |
| 475 | function checkUnique(self, id) { |
| 476 | if (self._schemas[id] || self._refs[id]) |
| 477 | throw new Error('schema with key or id "' + id + '" already exists'); |
| 478 | } |
| 479 | |
| 480 | |
| 481 | function getMetaSchemaOptions(self) { |
| 482 | var metaOpts = util.copy(self._opts); |
| 483 | for (var i=0; i<META_IGNORE_OPTIONS.length; i++) |
| 484 | delete metaOpts[META_IGNORE_OPTIONS[i]]; |
| 485 | return metaOpts; |
| 486 | } |
| 487 | |
| 488 | |
| 489 | function setLogger(self) { |
| 490 | var logger = self._opts.logger; |
| 491 | if (logger === false) { |
| 492 | self.logger = {log: noop, warn: noop, error: noop}; |
| 493 | } else { |
| 494 | if (logger === undefined) logger = console; |
| 495 | if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error)) |
| 496 | throw new Error('logger must implement log, warn and error methods'); |
| 497 | self.logger = logger; |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | |
| 502 | function noop() {} |