Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

ajv.js 15KB

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