ajv.js 15 KB

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