ajv.js 14 KB

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