ajv.js 16 KB

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