ajv.js 15 KB

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