index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. 'use strict';
  2. var resolve = require('./resolve')
  3. , util = require('./util')
  4. , stableStringify = require('json-stable-stringify')
  5. , async = require('../async');
  6. var beautify;
  7. function loadBeautify(){
  8. if (beautify === undefined) {
  9. var name = 'js-beautify';
  10. try { beautify = require(name).js_beautify; }
  11. catch(e) { beautify = false; }
  12. }
  13. }
  14. var validateGenerator = require('../dotjs/validate');
  15. /**
  16. * Functions below are used inside compiled validations function
  17. */
  18. var co = require('co');
  19. var ucs2length = util.ucs2length;
  20. var equal = require('./equal');
  21. // this error is thrown by async schemas to return validation errors via exception
  22. var ValidationError = require('./validation_error');
  23. module.exports = compile;
  24. /**
  25. * Compiles schema to validation function
  26. * @this Ajv
  27. * @param {Object} schema schema object
  28. * @param {Object} root object with information about the root schema for this schema
  29. * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
  30. * @param {String} baseId base ID for IDs in the schema
  31. * @return {Function} validation function
  32. */
  33. function compile(schema, root, localRefs, baseId) {
  34. /* jshint validthis: true, evil: true */
  35. /* eslint no-shadow: 0 */
  36. var self = this
  37. , opts = this._opts
  38. , refVal = [ undefined ]
  39. , refs = {}
  40. , patterns = []
  41. , patternsHash = {}
  42. , defaults = []
  43. , defaultsHash = {}
  44. , customRules = []
  45. , keepSourceCode = opts.sourceCode !== false;
  46. root = root || { schema: schema, refVal: refVal, refs: refs };
  47. var c = checkCompiling.call(this, schema, root, baseId);
  48. var compilation = this._compilations[c.index];
  49. if (c.compiling) return (compilation.callValidate = callValidate);
  50. var formats = this._formats;
  51. var RULES = this.RULES;
  52. try {
  53. var v = localCompile(schema, root, localRefs, baseId);
  54. compilation.validate = v;
  55. var cv = compilation.callValidate;
  56. if (cv) {
  57. cv.schema = v.schema;
  58. cv.errors = null;
  59. cv.refs = v.refs;
  60. cv.refVal = v.refVal;
  61. cv.root = v.root;
  62. cv.$async = v.$async;
  63. if (keepSourceCode) cv.sourceCode = v.sourceCode;
  64. }
  65. return v;
  66. } finally {
  67. endCompiling.call(this, schema, root, baseId);
  68. }
  69. function callValidate() {
  70. var validate = compilation.validate;
  71. var result = validate.apply(null, arguments);
  72. callValidate.errors = validate.errors;
  73. return result;
  74. }
  75. function localCompile(_schema, _root, localRefs, baseId) {
  76. var isRoot = !_root || (_root && _root.schema == _schema);
  77. if (_root.schema != root.schema)
  78. return compile.call(self, _schema, _root, localRefs, baseId);
  79. var $async = _schema.$async === true;
  80. if ($async && !opts.transpile) async.setup(opts);
  81. var sourceCode = validateGenerator({
  82. isTop: true,
  83. schema: _schema,
  84. isRoot: isRoot,
  85. baseId: baseId,
  86. root: _root,
  87. schemaPath: '',
  88. errSchemaPath: '#',
  89. errorPath: '""',
  90. RULES: RULES,
  91. validate: validateGenerator,
  92. util: util,
  93. resolve: resolve,
  94. resolveRef: resolveRef,
  95. usePattern: usePattern,
  96. useDefault: useDefault,
  97. useCustomRule: useCustomRule,
  98. opts: opts,
  99. formats: formats,
  100. self: self
  101. });
  102. sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
  103. + vars(defaults, defaultCode) + vars(customRules, customRuleCode)
  104. + sourceCode;
  105. if (opts.beautify) {
  106. loadBeautify();
  107. /* istanbul ignore else */
  108. if (beautify) sourceCode = beautify(sourceCode, opts.beautify);
  109. else console.error('"npm install js-beautify" to use beautify option');
  110. }
  111. // console.log('\n\n\n *** \n', sourceCode);
  112. var validate, validateCode
  113. , transpile = opts._transpileFunc;
  114. try {
  115. validateCode = $async && transpile
  116. ? transpile(sourceCode)
  117. : sourceCode;
  118. var makeValidate = new Function(
  119. 'self',
  120. 'RULES',
  121. 'formats',
  122. 'root',
  123. 'refVal',
  124. 'defaults',
  125. 'customRules',
  126. 'co',
  127. 'equal',
  128. 'ucs2length',
  129. 'ValidationError',
  130. validateCode
  131. );
  132. validate = makeValidate(
  133. self,
  134. RULES,
  135. formats,
  136. root,
  137. refVal,
  138. defaults,
  139. customRules,
  140. co,
  141. equal,
  142. ucs2length,
  143. ValidationError
  144. );
  145. refVal[0] = validate;
  146. } catch(e) {
  147. console.error('Error compiling schema, function code:', validateCode);
  148. throw e;
  149. }
  150. validate.schema = _schema;
  151. validate.errors = null;
  152. validate.refs = refs;
  153. validate.refVal = refVal;
  154. validate.root = isRoot ? validate : _root;
  155. if ($async) validate.$async = true;
  156. if (keepSourceCode) validate.sourceCode = sourceCode;
  157. if (opts.sourceCode === true) {
  158. validate.source = {
  159. patterns: patterns,
  160. defaults: defaults
  161. };
  162. }
  163. return validate;
  164. }
  165. function resolveRef(baseId, ref, isRoot) {
  166. ref = resolve.url(baseId, ref);
  167. var refIndex = refs[ref];
  168. var _refVal, refCode;
  169. if (refIndex !== undefined) {
  170. _refVal = refVal[refIndex];
  171. refCode = 'refVal[' + refIndex + ']';
  172. return resolvedRef(_refVal, refCode);
  173. }
  174. if (!isRoot && root.refs) {
  175. var rootRefId = root.refs[ref];
  176. if (rootRefId !== undefined) {
  177. _refVal = root.refVal[rootRefId];
  178. refCode = addLocalRef(ref, _refVal);
  179. return resolvedRef(_refVal, refCode);
  180. }
  181. }
  182. refCode = addLocalRef(ref);
  183. var v = resolve.call(self, localCompile, root, ref);
  184. if (!v) {
  185. var localSchema = localRefs && localRefs[ref];
  186. if (localSchema) {
  187. v = resolve.inlineRef(localSchema, opts.inlineRefs)
  188. ? localSchema
  189. : compile.call(self, localSchema, root, localRefs, baseId);
  190. }
  191. }
  192. if (v) {
  193. replaceLocalRef(ref, v);
  194. return resolvedRef(v, refCode);
  195. }
  196. }
  197. function addLocalRef(ref, v) {
  198. var refId = refVal.length;
  199. refVal[refId] = v;
  200. refs[ref] = refId;
  201. return 'refVal' + refId;
  202. }
  203. function replaceLocalRef(ref, v) {
  204. var refId = refs[ref];
  205. refVal[refId] = v;
  206. }
  207. function resolvedRef(refVal, code) {
  208. return typeof refVal == 'object'
  209. ? { code: code, schema: refVal, inline: true }
  210. : { code: code, $async: refVal && refVal.$async };
  211. }
  212. function usePattern(regexStr) {
  213. var index = patternsHash[regexStr];
  214. if (index === undefined) {
  215. index = patternsHash[regexStr] = patterns.length;
  216. patterns[index] = regexStr;
  217. }
  218. return 'pattern' + index;
  219. }
  220. function useDefault(value) {
  221. switch (typeof value) {
  222. case 'boolean':
  223. case 'number':
  224. return '' + value;
  225. case 'string':
  226. return util.toQuotedString(value);
  227. case 'object':
  228. if (value === null) return 'null';
  229. var valueStr = stableStringify(value);
  230. var index = defaultsHash[valueStr];
  231. if (index === undefined) {
  232. index = defaultsHash[valueStr] = defaults.length;
  233. defaults[index] = value;
  234. }
  235. return 'default' + index;
  236. }
  237. }
  238. function useCustomRule(rule, schema, parentSchema, it) {
  239. var validateSchema = rule.definition.validateSchema;
  240. if (validateSchema && self._opts.validateSchema !== false) {
  241. var valid = validateSchema(schema);
  242. if (!valid) {
  243. var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
  244. if (self._opts.validateSchema == 'log') console.error(message);
  245. else throw new Error(message);
  246. }
  247. }
  248. var compile = rule.definition.compile
  249. , inline = rule.definition.inline
  250. , macro = rule.definition.macro;
  251. var validate;
  252. if (compile) {
  253. validate = compile.call(self, schema, parentSchema, it);
  254. } else if (macro) {
  255. validate = macro.call(self, schema, parentSchema, it);
  256. if (opts.validateSchema !== false) self.validateSchema(validate, true);
  257. } else if (inline) {
  258. validate = inline.call(self, it, rule.keyword, schema, parentSchema);
  259. } else {
  260. validate = rule.definition.validate;
  261. }
  262. var index = customRules.length;
  263. customRules[index] = validate;
  264. return {
  265. code: 'customRule' + index,
  266. validate: validate
  267. };
  268. }
  269. }
  270. /**
  271. * Checks if the schema is currently compiled
  272. * @this Ajv
  273. * @param {Object} schema schema to compile
  274. * @param {Object} root root object
  275. * @param {String} baseId base schema ID
  276. * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
  277. */
  278. function checkCompiling(schema, root, baseId) {
  279. /* jshint validthis: true */
  280. var index = compIndex.call(this, schema, root, baseId);
  281. if (index >= 0) return { index: index, compiling: true };
  282. index = this._compilations.length;
  283. this._compilations[index] = {
  284. schema: schema,
  285. root: root,
  286. baseId: baseId
  287. };
  288. return { index: index, compiling: false };
  289. }
  290. /**
  291. * Removes the schema from the currently compiled list
  292. * @this Ajv
  293. * @param {Object} schema schema to compile
  294. * @param {Object} root root object
  295. * @param {String} baseId base schema ID
  296. */
  297. function endCompiling(schema, root, baseId) {
  298. /* jshint validthis: true */
  299. var i = compIndex.call(this, schema, root, baseId);
  300. if (i >= 0) this._compilations.splice(i, 1);
  301. }
  302. /**
  303. * Index of schema compilation in the currently compiled list
  304. * @this Ajv
  305. * @param {Object} schema schema to compile
  306. * @param {Object} root root object
  307. * @param {String} baseId base schema ID
  308. * @return {Integer} compilation index
  309. */
  310. function compIndex(schema, root, baseId) {
  311. /* jshint validthis: true */
  312. for (var i=0; i<this._compilations.length; i++) {
  313. var c = this._compilations[i];
  314. if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
  315. }
  316. return -1;
  317. }
  318. function patternCode(i, patterns) {
  319. return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
  320. }
  321. function defaultCode(i) {
  322. return 'var default' + i + ' = defaults[' + i + '];';
  323. }
  324. function refValCode(i, refVal) {
  325. return refVal[i] ? 'var refVal' + i + ' = refVal[' + i + '];' : '';
  326. }
  327. function customRuleCode(i) {
  328. return 'var customRule' + i + ' = customRules[' + i + '];';
  329. }
  330. function vars(arr, statement) {
  331. if (!arr.length) return '';
  332. var code = '';
  333. for (var i=0; i<arr.length; i++)
  334. code += statement(i, arr);
  335. return code;
  336. }