index.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. var genobj = require('generate-object-property')
  2. var genfun = require('generate-function')
  3. var jsonpointer = require('jsonpointer')
  4. var xtend = require('xtend')
  5. var formats = require('./formats')
  6. var get = function(obj, additionalSchemas, ptr) {
  7. var visit = function(sub) {
  8. if (sub && sub.id === ptr) return sub
  9. if (typeof sub !== 'object' || !sub) return null
  10. return Object.keys(sub).reduce(function(res, k) {
  11. return res || visit(sub[k])
  12. }, null)
  13. }
  14. var res = visit(obj)
  15. if (res) return res
  16. ptr = ptr.replace(/^#/, '')
  17. ptr = ptr.replace(/\/$/, '')
  18. try {
  19. return jsonpointer.get(obj, decodeURI(ptr))
  20. } catch (err) {
  21. var end = ptr.indexOf('#')
  22. var other
  23. // external reference
  24. if (end !== 0) {
  25. // fragment doesn't exist.
  26. if (end === -1) {
  27. other = additionalSchemas[ptr]
  28. } else {
  29. var ext = ptr.slice(0, end)
  30. other = additionalSchemas[ext]
  31. var fragment = ptr.slice(end).replace(/^#/, '')
  32. try {
  33. return jsonpointer.get(other, fragment)
  34. } catch (err) {}
  35. }
  36. } else {
  37. other = additionalSchemas[ptr]
  38. }
  39. return other || null
  40. }
  41. }
  42. var formatName = function(field) {
  43. field = JSON.stringify(field)
  44. var pattern = /\[([^\[\]"]+)\]/
  45. while (pattern.test(field)) field = field.replace(pattern, '."+$1+"')
  46. return field
  47. }
  48. var types = {}
  49. types.any = function() {
  50. return 'true'
  51. }
  52. types.null = function(name) {
  53. return name+' === null'
  54. }
  55. types.boolean = function(name) {
  56. return 'typeof '+name+' === "boolean"'
  57. }
  58. types.array = function(name) {
  59. return 'Array.isArray('+name+')'
  60. }
  61. types.object = function(name) {
  62. return 'typeof '+name+' === "object" && '+name+' && !Array.isArray('+name+')'
  63. }
  64. types.number = function(name) {
  65. return 'typeof '+name+' === "number"'
  66. }
  67. types.integer = function(name) {
  68. return 'typeof '+name+' === "number" && (Math.floor('+name+') === '+name+' || '+name+' > 9007199254740992 || '+name+' < -9007199254740992)'
  69. }
  70. types.string = function(name) {
  71. return 'typeof '+name+' === "string"'
  72. }
  73. var unique = function(array) {
  74. var list = []
  75. for (var i = 0; i < array.length; i++) {
  76. list.push(typeof array[i] === 'object' ? JSON.stringify(array[i]) : array[i])
  77. }
  78. for (var i = 1; i < list.length; i++) {
  79. if (list.indexOf(list[i]) !== i) return false
  80. }
  81. return true
  82. }
  83. var isMultipleOf = function(name, multipleOf) {
  84. var res;
  85. var factor = ((multipleOf | 0) !== multipleOf) ? Math.pow(10, multipleOf.toString().split('.').pop().length) : 1
  86. if (factor > 1) {
  87. var factorName = ((name | 0) !== name) ? Math.pow(10, name.toString().split('.').pop().length) : 1
  88. if (factorName > factor) res = true
  89. else res = Math.round(factor * name) % (factor * multipleOf)
  90. }
  91. else res = name % multipleOf;
  92. return !res;
  93. }
  94. var toType = function(node) {
  95. return node.type
  96. }
  97. var compile = function(schema, cache, root, reporter, opts) {
  98. var fmts = opts ? xtend(formats, opts.formats) : formats
  99. var scope = {unique:unique, formats:fmts, isMultipleOf:isMultipleOf}
  100. var verbose = opts ? !!opts.verbose : false;
  101. var greedy = opts && opts.greedy !== undefined ?
  102. opts.greedy : false;
  103. var syms = {}
  104. var gensym = function(name) {
  105. return name+(syms[name] = (syms[name] || 0)+1)
  106. }
  107. var reversePatterns = {}
  108. var patterns = function(p) {
  109. if (reversePatterns[p]) return reversePatterns[p]
  110. var n = gensym('pattern')
  111. scope[n] = new RegExp(p)
  112. reversePatterns[p] = n
  113. return n
  114. }
  115. var vars = ['i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z']
  116. var genloop = function() {
  117. var v = vars.shift()
  118. vars.push(v+v[0])
  119. return v
  120. }
  121. var visit = function(name, node, reporter, filter) {
  122. var properties = node.properties
  123. var type = node.type
  124. var tuple = false
  125. if (Array.isArray(node.items)) { // tuple type
  126. properties = {}
  127. node.items.forEach(function(item, i) {
  128. properties[i] = item
  129. })
  130. type = 'array'
  131. tuple = true
  132. }
  133. var indent = 0
  134. var error = function(msg, prop, value) {
  135. validate('errors++')
  136. if (reporter === true) {
  137. validate('if (validate.errors === null) validate.errors = []')
  138. if (verbose) {
  139. validate('validate.errors.push({field:%s,message:%s,value:%s,type:%s})', formatName(prop || name), JSON.stringify(msg), value || name, JSON.stringify(type))
  140. } else {
  141. validate('validate.errors.push({field:%s,message:%s})', formatName(prop || name), JSON.stringify(msg))
  142. }
  143. }
  144. }
  145. if (node.required === true) {
  146. indent++
  147. validate('if (%s === undefined) {', name)
  148. error('is required')
  149. validate('} else {')
  150. } else {
  151. indent++
  152. validate('if (%s !== undefined) {', name)
  153. }
  154. var valid = [].concat(type)
  155. .map(function(t) {
  156. return types[t || 'any'](name)
  157. })
  158. .join(' || ') || 'true'
  159. if (valid !== 'true') {
  160. indent++
  161. validate('if (!(%s)) {', valid)
  162. error('is the wrong type')
  163. validate('} else {')
  164. }
  165. if (tuple) {
  166. if (node.additionalItems === false) {
  167. validate('if (%s.length > %d) {', name, node.items.length)
  168. error('has additional items')
  169. validate('}')
  170. } else if (node.additionalItems) {
  171. var i = genloop()
  172. validate('for (var %s = %d; %s < %s.length; %s++) {', i, node.items.length, i, name, i)
  173. visit(name+'['+i+']', node.additionalItems, reporter, filter)
  174. validate('}')
  175. }
  176. }
  177. if (node.format && fmts[node.format]) {
  178. if (type !== 'string' && formats[node.format]) validate('if (%s) {', types.string(name))
  179. var n = gensym('format')
  180. scope[n] = fmts[node.format]
  181. if (typeof scope[n] === 'function') validate('if (!%s(%s)) {', n, name)
  182. else validate('if (!%s.test(%s)) {', n, name)
  183. error('must be '+node.format+' format')
  184. validate('}')
  185. if (type !== 'string' && formats[node.format]) validate('}')
  186. }
  187. if (Array.isArray(node.required)) {
  188. var isUndefined = function(req) {
  189. return genobj(name, req) + ' === undefined'
  190. }
  191. var checkRequired = function (req) {
  192. var prop = genobj(name, req);
  193. validate('if (%s === undefined) {', prop)
  194. error('is required', prop)
  195. validate('missing++')
  196. validate('}')
  197. }
  198. validate('if ((%s)) {', type !== 'object' ? types.object(name) : 'true')
  199. validate('var missing = 0')
  200. node.required.map(checkRequired)
  201. validate('}');
  202. if (!greedy) {
  203. validate('if (missing === 0) {')
  204. indent++
  205. }
  206. }
  207. if (node.uniqueItems) {
  208. if (type !== 'array') validate('if (%s) {', types.array(name))
  209. validate('if (!(unique(%s))) {', name)
  210. error('must be unique')
  211. validate('}')
  212. if (type !== 'array') validate('}')
  213. }
  214. if (node.enum) {
  215. var complex = node.enum.some(function(e) {
  216. return typeof e === 'object'
  217. })
  218. var compare = complex ?
  219. function(e) {
  220. return 'JSON.stringify('+name+')'+' !== JSON.stringify('+JSON.stringify(e)+')'
  221. } :
  222. function(e) {
  223. return name+' !== '+JSON.stringify(e)
  224. }
  225. validate('if (%s) {', node.enum.map(compare).join(' && ') || 'false')
  226. error('must be an enum value')
  227. validate('}')
  228. }
  229. if (node.dependencies) {
  230. if (type !== 'object') validate('if (%s) {', types.object(name))
  231. Object.keys(node.dependencies).forEach(function(key) {
  232. var deps = node.dependencies[key]
  233. if (typeof deps === 'string') deps = [deps]
  234. var exists = function(k) {
  235. return genobj(name, k) + ' !== undefined'
  236. }
  237. if (Array.isArray(deps)) {
  238. validate('if (%s !== undefined && !(%s)) {', genobj(name, key), deps.map(exists).join(' && ') || 'true')
  239. error('dependencies not set')
  240. validate('}')
  241. }
  242. if (typeof deps === 'object') {
  243. validate('if (%s !== undefined) {', genobj(name, key))
  244. visit(name, deps, reporter, filter)
  245. validate('}')
  246. }
  247. })
  248. if (type !== 'object') validate('}')
  249. }
  250. if (node.additionalProperties || node.additionalProperties === false) {
  251. if (type !== 'object') validate('if (%s) {', types.object(name))
  252. var i = genloop()
  253. var keys = gensym('keys')
  254. var toCompare = function(p) {
  255. return keys+'['+i+'] !== '+JSON.stringify(p)
  256. }
  257. var toTest = function(p) {
  258. return '!'+patterns(p)+'.test('+keys+'['+i+'])'
  259. }
  260. var additionalProp = Object.keys(properties || {}).map(toCompare)
  261. .concat(Object.keys(node.patternProperties || {}).map(toTest))
  262. .join(' && ') || 'true'
  263. validate('var %s = Object.keys(%s)', keys, name)
  264. ('for (var %s = 0; %s < %s.length; %s++) {', i, i, keys, i)
  265. ('if (%s) {', additionalProp)
  266. if (node.additionalProperties === false) {
  267. if (filter) validate('delete %s', name+'['+keys+'['+i+']]')
  268. error('has additional properties', null, JSON.stringify(name+'.') + ' + ' + keys + '['+i+']')
  269. } else {
  270. visit(name+'['+keys+'['+i+']]', node.additionalProperties, reporter, filter)
  271. }
  272. validate
  273. ('}')
  274. ('}')
  275. if (type !== 'object') validate('}')
  276. }
  277. if (node.$ref) {
  278. var sub = get(root, opts && opts.schemas || {}, node.$ref)
  279. if (sub) {
  280. var fn = cache[node.$ref]
  281. if (!fn) {
  282. cache[node.$ref] = function proxy(data) {
  283. return fn(data)
  284. }
  285. fn = compile(sub, cache, root, false, opts)
  286. }
  287. var n = gensym('ref')
  288. scope[n] = fn
  289. validate('if (!(%s(%s))) {', n, name)
  290. error('referenced schema does not match')
  291. validate('}')
  292. }
  293. }
  294. if (node.not) {
  295. var prev = gensym('prev')
  296. validate('var %s = errors', prev)
  297. visit(name, node.not, false, filter)
  298. validate('if (%s === errors) {', prev)
  299. error('negative schema matches')
  300. validate('} else {')
  301. ('errors = %s', prev)
  302. ('}')
  303. }
  304. if (node.items && !tuple) {
  305. if (type !== 'array') validate('if (%s) {', types.array(name))
  306. var i = genloop()
  307. validate('for (var %s = 0; %s < %s.length; %s++) {', i, i, name, i)
  308. visit(name+'['+i+']', node.items, reporter, filter)
  309. validate('}')
  310. if (type !== 'array') validate('}')
  311. }
  312. if (node.patternProperties) {
  313. if (type !== 'object') validate('if (%s) {', types.object(name))
  314. var keys = gensym('keys')
  315. var i = genloop()
  316. validate
  317. ('var %s = Object.keys(%s)', keys, name)
  318. ('for (var %s = 0; %s < %s.length; %s++) {', i, i, keys, i)
  319. Object.keys(node.patternProperties).forEach(function(key) {
  320. var p = patterns(key)
  321. validate('if (%s.test(%s)) {', p, keys+'['+i+']')
  322. visit(name+'['+keys+'['+i+']]', node.patternProperties[key], reporter, filter)
  323. validate('}')
  324. })
  325. validate('}')
  326. if (type !== 'object') validate('}')
  327. }
  328. if (node.pattern) {
  329. var p = patterns(node.pattern)
  330. if (type !== 'string') validate('if (%s) {', types.string(name))
  331. validate('if (!(%s.test(%s))) {', p, name)
  332. error('pattern mismatch')
  333. validate('}')
  334. if (type !== 'string') validate('}')
  335. }
  336. if (node.allOf) {
  337. node.allOf.forEach(function(sch) {
  338. visit(name, sch, reporter, filter)
  339. })
  340. }
  341. if (node.anyOf && node.anyOf.length) {
  342. var prev = gensym('prev')
  343. node.anyOf.forEach(function(sch, i) {
  344. if (i === 0) {
  345. validate('var %s = errors', prev)
  346. } else {
  347. validate('if (errors !== %s) {', prev)
  348. ('errors = %s', prev)
  349. }
  350. visit(name, sch, false, false)
  351. })
  352. node.anyOf.forEach(function(sch, i) {
  353. if (i) validate('}')
  354. })
  355. validate('if (%s !== errors) {', prev)
  356. error('no schemas match')
  357. validate('}')
  358. }
  359. if (node.oneOf && node.oneOf.length) {
  360. var prev = gensym('prev')
  361. var passes = gensym('passes')
  362. validate
  363. ('var %s = errors', prev)
  364. ('var %s = 0', passes)
  365. node.oneOf.forEach(function(sch, i) {
  366. visit(name, sch, false, false)
  367. validate('if (%s === errors) {', prev)
  368. ('%s++', passes)
  369. ('} else {')
  370. ('errors = %s', prev)
  371. ('}')
  372. })
  373. validate('if (%s !== 1) {', passes)
  374. error('no (or more than one) schemas match')
  375. validate('}')
  376. }
  377. if (node.multipleOf !== undefined) {
  378. if (type !== 'number' && type !== 'integer') validate('if (%s) {', types.number(name))
  379. validate('if (!isMultipleOf(%s, %d)) {', name, node.multipleOf)
  380. error('has a remainder')
  381. validate('}')
  382. if (type !== 'number' && type !== 'integer') validate('}')
  383. }
  384. if (node.maxProperties !== undefined) {
  385. if (type !== 'object') validate('if (%s) {', types.object(name))
  386. validate('if (Object.keys(%s).length > %d) {', name, node.maxProperties)
  387. error('has more properties than allowed')
  388. validate('}')
  389. if (type !== 'object') validate('}')
  390. }
  391. if (node.minProperties !== undefined) {
  392. if (type !== 'object') validate('if (%s) {', types.object(name))
  393. validate('if (Object.keys(%s).length < %d) {', name, node.minProperties)
  394. error('has less properties than allowed')
  395. validate('}')
  396. if (type !== 'object') validate('}')
  397. }
  398. if (node.maxItems !== undefined) {
  399. if (type !== 'array') validate('if (%s) {', types.array(name))
  400. validate('if (%s.length > %d) {', name, node.maxItems)
  401. error('has more items than allowed')
  402. validate('}')
  403. if (type !== 'array') validate('}')
  404. }
  405. if (node.minItems !== undefined) {
  406. if (type !== 'array') validate('if (%s) {', types.array(name))
  407. validate('if (%s.length < %d) {', name, node.minItems)
  408. error('has less items than allowed')
  409. validate('}')
  410. if (type !== 'array') validate('}')
  411. }
  412. if (node.maxLength !== undefined) {
  413. if (type !== 'string') validate('if (%s) {', types.string(name))
  414. validate('if (%s.length > %d) {', name, node.maxLength)
  415. error('has longer length than allowed')
  416. validate('}')
  417. if (type !== 'string') validate('}')
  418. }
  419. if (node.minLength !== undefined) {
  420. if (type !== 'string') validate('if (%s) {', types.string(name))
  421. validate('if (%s.length < %d) {', name, node.minLength)
  422. error('has less length than allowed')
  423. validate('}')
  424. if (type !== 'string') validate('}')
  425. }
  426. if (node.minimum !== undefined) {
  427. if (type !== 'number' && type !== 'integer') validate('if (%s) {', types.number(name))
  428. validate('if (%s %s %d) {', name, node.exclusiveMinimum ? '<=' : '<', node.minimum)
  429. error('is less than minimum')
  430. validate('}')
  431. if (type !== 'number' && type !== 'integer') validate('}')
  432. }
  433. if (node.maximum !== undefined) {
  434. if (type !== 'number' && type !== 'integer') validate('if (%s) {', types.number(name))
  435. validate('if (%s %s %d) {', name, node.exclusiveMaximum ? '>=' : '>', node.maximum)
  436. error('is more than maximum')
  437. validate('}')
  438. if (type !== 'number' && type !== 'integer') validate('}')
  439. }
  440. if (properties) {
  441. Object.keys(properties).forEach(function(p) {
  442. if (Array.isArray(type) && type.indexOf('null') !== -1) validate('if (%s !== null) {', name)
  443. visit(genobj(name, p), properties[p], reporter, filter)
  444. if (Array.isArray(type) && type.indexOf('null') !== -1) validate('}')
  445. })
  446. }
  447. while (indent--) validate('}')
  448. }
  449. var validate = genfun
  450. ('function validate(data) {')
  451. // Since undefined is not a valid JSON value, we coerce to null and other checks will catch this
  452. ('if (data === undefined) data = null')
  453. ('validate.errors = null')
  454. ('var errors = 0')
  455. visit('data', schema, reporter, opts && opts.filter)
  456. validate
  457. ('return errors === 0')
  458. ('}')
  459. validate = validate.toFunction(scope)
  460. validate.errors = null
  461. if (Object.defineProperty) {
  462. Object.defineProperty(validate, 'error', {
  463. get: function() {
  464. if (!validate.errors) return ''
  465. return validate.errors.map(function(err) {
  466. return err.field + ' ' + err.message;
  467. }).join('\n')
  468. }
  469. })
  470. }
  471. validate.toJSON = function() {
  472. return schema
  473. }
  474. return validate
  475. }
  476. module.exports = function(schema, opts) {
  477. if (typeof schema === 'string') schema = JSON.parse(schema)
  478. return compile(schema, {}, schema, true, opts)
  479. }
  480. module.exports.filter = function(schema, opts) {
  481. var validate = module.exports(schema, xtend(opts, {filter: true}))
  482. return function(sch) {
  483. validate(sch)
  484. return sch
  485. }
  486. }