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