validate.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. 'use strict';
  2. module.exports = function generate_validate(it, $keyword, $ruleType) {
  3. var out = '';
  4. var $async = it.schema.$async === true,
  5. $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'),
  6. $id = it.self._getId(it.schema);
  7. if (it.isTop) {
  8. if ($async) {
  9. it.async = true;
  10. var $es7 = it.opts.async == 'es7';
  11. it.yieldAwait = $es7 ? 'await' : 'yield';
  12. }
  13. out += ' var validate = ';
  14. if ($async) {
  15. if ($es7) {
  16. out += ' (async function ';
  17. } else {
  18. if (it.opts.async != '*') {
  19. out += 'co.wrap';
  20. }
  21. out += '(function* ';
  22. }
  23. } else {
  24. out += ' (function ';
  25. }
  26. out += ' (data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; ';
  27. if ($id && (it.opts.sourceCode || it.opts.processCode)) {
  28. out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' ';
  29. }
  30. }
  31. if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) {
  32. var $keyword = 'false schema';
  33. var $lvl = it.level;
  34. var $dataLvl = it.dataLevel;
  35. var $schema = it.schema[$keyword];
  36. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  37. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  38. var $breakOnError = !it.opts.allErrors;
  39. var $errorKeyword;
  40. var $data = 'data' + ($dataLvl || '');
  41. var $valid = 'valid' + $lvl;
  42. if (it.schema === false) {
  43. if (it.isTop) {
  44. $breakOnError = true;
  45. } else {
  46. out += ' var ' + ($valid) + ' = false; ';
  47. }
  48. var $$outStack = $$outStack || [];
  49. $$outStack.push(out);
  50. out = ''; /* istanbul ignore else */
  51. if (it.createErrors !== false) {
  52. out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
  53. if (it.opts.messages !== false) {
  54. out += ' , message: \'boolean schema is false\' ';
  55. }
  56. if (it.opts.verbose) {
  57. out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  58. }
  59. out += ' } ';
  60. } else {
  61. out += ' {} ';
  62. }
  63. var __err = out;
  64. out = $$outStack.pop();
  65. if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
  66. if (it.async) {
  67. out += ' throw new ValidationError([' + (__err) + ']); ';
  68. } else {
  69. out += ' validate.errors = [' + (__err) + ']; return false; ';
  70. }
  71. } else {
  72. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  73. }
  74. } else {
  75. if (it.isTop) {
  76. if ($async) {
  77. out += ' return data; ';
  78. } else {
  79. out += ' validate.errors = null; return true; ';
  80. }
  81. } else {
  82. out += ' var ' + ($valid) + ' = true; ';
  83. }
  84. }
  85. if (it.isTop) {
  86. out += ' }); return validate; ';
  87. }
  88. return out;
  89. }
  90. if (it.isTop) {
  91. var $top = it.isTop,
  92. $lvl = it.level = 0,
  93. $dataLvl = it.dataLevel = 0,
  94. $data = 'data';
  95. it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
  96. it.baseId = it.baseId || it.rootId;
  97. delete it.isTop;
  98. it.dataPathArr = [undefined];
  99. out += ' var vErrors = null; ';
  100. out += ' var errors = 0; ';
  101. out += ' if (rootData === undefined) rootData = data; ';
  102. } else {
  103. var $lvl = it.level,
  104. $dataLvl = it.dataLevel,
  105. $data = 'data' + ($dataLvl || '');
  106. if ($id) it.baseId = it.resolve.url(it.baseId, $id);
  107. if ($async && !it.async) throw new Error('async schema in sync schema');
  108. out += ' var errs_' + ($lvl) + ' = errors;';
  109. }
  110. var $valid = 'valid' + $lvl,
  111. $breakOnError = !it.opts.allErrors,
  112. $closingBraces1 = '',
  113. $closingBraces2 = '';
  114. var $errorKeyword;
  115. var $typeSchema = it.schema.type,
  116. $typeIsArray = Array.isArray($typeSchema);
  117. if ($typeSchema && it.opts.coerceTypes) {
  118. var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
  119. if ($coerceToTypes) {
  120. var $schemaPath = it.schemaPath + '.type',
  121. $errSchemaPath = it.errSchemaPath + '/type',
  122. $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
  123. out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { ';
  124. var $dataType = 'dataType' + $lvl,
  125. $coerced = 'coerced' + $lvl;
  126. out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; ';
  127. if (it.opts.coerceTypes == 'array') {
  128. out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; ';
  129. }
  130. out += ' var ' + ($coerced) + ' = undefined; ';
  131. var $bracesCoercion = '';
  132. var arr1 = $coerceToTypes;
  133. if (arr1) {
  134. var $type, $i = -1,
  135. l1 = arr1.length - 1;
  136. while ($i < l1) {
  137. $type = arr1[$i += 1];
  138. if ($i) {
  139. out += ' if (' + ($coerced) + ' === undefined) { ';
  140. $bracesCoercion += '}';
  141. }
  142. if (it.opts.coerceTypes == 'array' && $type != 'array') {
  143. out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; } ';
  144. }
  145. if ($type == 'string') {
  146. out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; ';
  147. } else if ($type == 'number' || $type == 'integer') {
  148. out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' ';
  149. if ($type == 'integer') {
  150. out += ' && !(' + ($data) + ' % 1)';
  151. }
  152. out += ')) ' + ($coerced) + ' = +' + ($data) + '; ';
  153. } else if ($type == 'boolean') {
  154. out += ' if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; ';
  155. } else if ($type == 'null') {
  156. out += ' if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; ';
  157. } else if (it.opts.coerceTypes == 'array' && $type == 'array') {
  158. out += ' if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; ';
  159. }
  160. }
  161. }
  162. out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) { ';
  163. var $$outStack = $$outStack || [];
  164. $$outStack.push(out);
  165. out = ''; /* istanbul ignore else */
  166. if (it.createErrors !== false) {
  167. out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
  168. if ($typeIsArray) {
  169. out += '' + ($typeSchema.join(","));
  170. } else {
  171. out += '' + ($typeSchema);
  172. }
  173. out += '\' } ';
  174. if (it.opts.messages !== false) {
  175. out += ' , message: \'should be ';
  176. if ($typeIsArray) {
  177. out += '' + ($typeSchema.join(","));
  178. } else {
  179. out += '' + ($typeSchema);
  180. }
  181. out += '\' ';
  182. }
  183. if (it.opts.verbose) {
  184. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  185. }
  186. out += ' } ';
  187. } else {
  188. out += ' {} ';
  189. }
  190. var __err = out;
  191. out = $$outStack.pop();
  192. if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
  193. if (it.async) {
  194. out += ' throw new ValidationError([' + (__err) + ']); ';
  195. } else {
  196. out += ' validate.errors = [' + (__err) + ']; return false; ';
  197. }
  198. } else {
  199. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  200. }
  201. out += ' } else { ';
  202. var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
  203. $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
  204. out += ' ' + ($data) + ' = ' + ($coerced) + '; ';
  205. if (!$dataLvl) {
  206. out += 'if (' + ($parentData) + ' !== undefined)';
  207. }
  208. out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } } ';
  209. }
  210. }
  211. if (it.schema.$ref && $refKeywords) {
  212. if (it.opts.extendRefs == 'fail') {
  213. throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
  214. } else if (it.opts.extendRefs !== true) {
  215. $refKeywords = false;
  216. console.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
  217. }
  218. }
  219. if (it.schema.$ref && !$refKeywords) {
  220. out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' ';
  221. if ($breakOnError) {
  222. out += ' } if (errors === ';
  223. if ($top) {
  224. out += '0';
  225. } else {
  226. out += 'errs_' + ($lvl);
  227. }
  228. out += ') { ';
  229. $closingBraces2 += '}';
  230. }
  231. } else {
  232. if (it.opts.v5 && it.schema.patternGroups) {
  233. console.warn('keyword "patternGroups" is deprecated and disabled. Use option patternGroups: true to enable.');
  234. }
  235. var arr2 = it.RULES;
  236. if (arr2) {
  237. var $rulesGroup, i2 = -1,
  238. l2 = arr2.length - 1;
  239. while (i2 < l2) {
  240. $rulesGroup = arr2[i2 += 1];
  241. if ($shouldUseGroup($rulesGroup)) {
  242. if ($rulesGroup.type) {
  243. out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { ';
  244. }
  245. if (it.opts.useDefaults && !it.compositeRule) {
  246. if ($rulesGroup.type == 'object' && it.schema.properties) {
  247. var $schema = it.schema.properties,
  248. $schemaKeys = Object.keys($schema);
  249. var arr3 = $schemaKeys;
  250. if (arr3) {
  251. var $propertyKey, i3 = -1,
  252. l3 = arr3.length - 1;
  253. while (i3 < l3) {
  254. $propertyKey = arr3[i3 += 1];
  255. var $sch = $schema[$propertyKey];
  256. if ($sch.default !== undefined) {
  257. var $passData = $data + it.util.getProperty($propertyKey);
  258. out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = ';
  259. if (it.opts.useDefaults == 'shared') {
  260. out += ' ' + (it.useDefault($sch.default)) + ' ';
  261. } else {
  262. out += ' ' + (JSON.stringify($sch.default)) + ' ';
  263. }
  264. out += '; ';
  265. }
  266. }
  267. }
  268. } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {
  269. var arr4 = it.schema.items;
  270. if (arr4) {
  271. var $sch, $i = -1,
  272. l4 = arr4.length - 1;
  273. while ($i < l4) {
  274. $sch = arr4[$i += 1];
  275. if ($sch.default !== undefined) {
  276. var $passData = $data + '[' + $i + ']';
  277. out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = ';
  278. if (it.opts.useDefaults == 'shared') {
  279. out += ' ' + (it.useDefault($sch.default)) + ' ';
  280. } else {
  281. out += ' ' + (JSON.stringify($sch.default)) + ' ';
  282. }
  283. out += '; ';
  284. }
  285. }
  286. }
  287. }
  288. }
  289. var arr5 = $rulesGroup.rules;
  290. if (arr5) {
  291. var $rule, i5 = -1,
  292. l5 = arr5.length - 1;
  293. while (i5 < l5) {
  294. $rule = arr5[i5 += 1];
  295. if ($shouldUseRule($rule)) {
  296. var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
  297. if ($code) {
  298. out += ' ' + ($code) + ' ';
  299. if ($breakOnError) {
  300. $closingBraces1 += '}';
  301. }
  302. }
  303. }
  304. }
  305. }
  306. if ($breakOnError) {
  307. out += ' ' + ($closingBraces1) + ' ';
  308. $closingBraces1 = '';
  309. }
  310. if ($rulesGroup.type) {
  311. out += ' } ';
  312. if ($typeSchema && $typeSchema === $rulesGroup.type) {
  313. var $typeChecked = true;
  314. out += ' else { ';
  315. var $schemaPath = it.schemaPath + '.type',
  316. $errSchemaPath = it.errSchemaPath + '/type';
  317. var $$outStack = $$outStack || [];
  318. $$outStack.push(out);
  319. out = ''; /* istanbul ignore else */
  320. if (it.createErrors !== false) {
  321. out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
  322. if ($typeIsArray) {
  323. out += '' + ($typeSchema.join(","));
  324. } else {
  325. out += '' + ($typeSchema);
  326. }
  327. out += '\' } ';
  328. if (it.opts.messages !== false) {
  329. out += ' , message: \'should be ';
  330. if ($typeIsArray) {
  331. out += '' + ($typeSchema.join(","));
  332. } else {
  333. out += '' + ($typeSchema);
  334. }
  335. out += '\' ';
  336. }
  337. if (it.opts.verbose) {
  338. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  339. }
  340. out += ' } ';
  341. } else {
  342. out += ' {} ';
  343. }
  344. var __err = out;
  345. out = $$outStack.pop();
  346. if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
  347. if (it.async) {
  348. out += ' throw new ValidationError([' + (__err) + ']); ';
  349. } else {
  350. out += ' validate.errors = [' + (__err) + ']; return false; ';
  351. }
  352. } else {
  353. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  354. }
  355. out += ' } ';
  356. }
  357. }
  358. if ($breakOnError) {
  359. out += ' if (errors === ';
  360. if ($top) {
  361. out += '0';
  362. } else {
  363. out += 'errs_' + ($lvl);
  364. }
  365. out += ') { ';
  366. $closingBraces2 += '}';
  367. }
  368. }
  369. }
  370. }
  371. }
  372. if ($typeSchema && !$typeChecked && !(it.opts.coerceTypes && $coerceToTypes)) {
  373. var $schemaPath = it.schemaPath + '.type',
  374. $errSchemaPath = it.errSchemaPath + '/type',
  375. $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
  376. out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { ';
  377. var $$outStack = $$outStack || [];
  378. $$outStack.push(out);
  379. out = ''; /* istanbul ignore else */
  380. if (it.createErrors !== false) {
  381. out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
  382. if ($typeIsArray) {
  383. out += '' + ($typeSchema.join(","));
  384. } else {
  385. out += '' + ($typeSchema);
  386. }
  387. out += '\' } ';
  388. if (it.opts.messages !== false) {
  389. out += ' , message: \'should be ';
  390. if ($typeIsArray) {
  391. out += '' + ($typeSchema.join(","));
  392. } else {
  393. out += '' + ($typeSchema);
  394. }
  395. out += '\' ';
  396. }
  397. if (it.opts.verbose) {
  398. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  399. }
  400. out += ' } ';
  401. } else {
  402. out += ' {} ';
  403. }
  404. var __err = out;
  405. out = $$outStack.pop();
  406. if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
  407. if (it.async) {
  408. out += ' throw new ValidationError([' + (__err) + ']); ';
  409. } else {
  410. out += ' validate.errors = [' + (__err) + ']; return false; ';
  411. }
  412. } else {
  413. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  414. }
  415. out += ' }';
  416. }
  417. if ($breakOnError) {
  418. out += ' ' + ($closingBraces2) + ' ';
  419. }
  420. if ($top) {
  421. if ($async) {
  422. out += ' if (errors === 0) return data; ';
  423. out += ' else throw new ValidationError(vErrors); ';
  424. } else {
  425. out += ' validate.errors = vErrors; ';
  426. out += ' return errors === 0; ';
  427. }
  428. out += ' }); return validate;';
  429. } else {
  430. out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
  431. }
  432. out = it.util.cleanUpCode(out);
  433. if ($top) {
  434. out = it.util.finalCleanUpCode(out, $async);
  435. }
  436. function $shouldUseGroup($rulesGroup) {
  437. var rules = $rulesGroup.rules;
  438. for (var i = 0; i < rules.length; i++)
  439. if ($shouldUseRule(rules[i])) return true;
  440. }
  441. function $shouldUseRule($rule) {
  442. return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImlementsSomeKeyword($rule));
  443. }
  444. function $ruleImlementsSomeKeyword($rule) {
  445. var impl = $rule.implements;
  446. for (var i = 0; i < impl.length; i++)
  447. if (it.schema[impl[i]] !== undefined) return true;
  448. }
  449. return out;
  450. }