Initial commit
[yaffs-website] / node_modules / ajv / dist / ajv.bundle.js
1 (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Ajv = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2 'use strict';
3
4 module.exports = {
5   setup: setupAsync,
6   compile: compileAsync
7 };
8
9
10 var util = require('./compile/util');
11
12 var ASYNC = {
13   '*': checkGenerators,
14   'co*': checkGenerators,
15   'es7': checkAsyncFunction
16 };
17
18 var TRANSPILE = {
19   'nodent': getNodent,
20   'regenerator': getRegenerator
21 };
22
23 var MODES = [
24   { async: 'co*' },
25   { async: 'es7', transpile: 'nodent' },
26   { async: 'co*', transpile: 'regenerator' }
27 ];
28
29
30 var regenerator, nodent;
31
32
33 function setupAsync(opts, required) {
34   if (required !== false) required = true;
35   var async = opts.async
36     , transpile = opts.transpile
37     , check;
38
39   switch (typeof transpile) {
40     case 'string':
41       var get = TRANSPILE[transpile];
42       if (!get) throw new Error('bad transpiler: ' + transpile);
43       return (opts._transpileFunc = get(opts, required));
44     case 'undefined':
45     case 'boolean':
46       if (typeof async == 'string') {
47         check = ASYNC[async];
48         if (!check) throw new Error('bad async mode: ' + async);
49         return (opts.transpile = check(opts, required));
50       }
51
52       for (var i=0; i<MODES.length; i++) {
53         var _opts = MODES[i];
54         if (setupAsync(_opts, false)) {
55           util.copy(_opts, opts);
56           return opts.transpile;
57         }
58       }
59       /* istanbul ignore next */
60       throw new Error('generators, nodent and regenerator are not available');
61     case 'function':
62       return (opts._transpileFunc = opts.transpile);
63     default:
64       throw new Error('bad transpiler: ' + transpile);
65   }
66 }
67
68
69 function checkGenerators(opts, required) {
70   /* jshint evil: true */
71   try {
72     (new Function('(function*(){})()'))();
73     return true;
74   } catch(e) {
75     /* istanbul ignore next */
76     if (required) throw new Error('generators not supported');
77   }
78 }
79
80
81 function checkAsyncFunction(opts, required) {
82   /* jshint evil: true */
83   try {
84     (new Function('(async function(){})()'))();
85     /* istanbul ignore next */
86     return true;
87   } catch(e) {
88     if (required) throw new Error('es7 async functions not supported');
89   }
90 }
91
92
93 function getRegenerator(opts, required) {
94   try {
95     if (!regenerator) {
96       var name = 'regenerator';
97       regenerator = require(name);
98       regenerator.runtime();
99     }
100     if (!opts.async || opts.async === true)
101       opts.async = 'es7';
102     return regeneratorTranspile;
103   } catch(e) {
104     /* istanbul ignore next */
105     if (required) throw new Error('regenerator not available');
106   }
107 }
108
109
110 function regeneratorTranspile(code) {
111   return regenerator.compile(code).code;
112 }
113
114
115 function getNodent(opts, required) {
116   /* jshint evil: true */
117   try {
118     if (!nodent) {
119       var name = 'nodent';
120       nodent = require(name)({ log: false, dontInstallRequireHook: true });
121     }
122     if (opts.async != 'es7') {
123       if (opts.async && opts.async !== true) console.warn('nodent transpiles only es7 async functions');
124       opts.async = 'es7';
125     }
126     return nodentTranspile;
127   } catch(e) {
128     /* istanbul ignore next */
129     if (required) throw new Error('nodent not available');
130   }
131 }
132
133
134 function nodentTranspile(code) {
135   return nodent.compile(code, '', { promises: true, sourcemap: false }).code;
136 }
137
138
139 /**
140  * Creates validating function for passed schema with asynchronous loading of missing schemas.
141  * `loadSchema` option should be a function that accepts schema uri and node-style callback.
142  * @this  Ajv
143  * @param {Object}   schema schema object
144  * @param {Function} callback node-style callback, it is always called with 2 parameters: error (or null) and validating function.
145  */
146 function compileAsync(schema, callback) {
147   /* eslint no-shadow: 0 */
148   /* jshint validthis: true */
149   var schemaObj;
150   var self = this;
151   try {
152     schemaObj = this._addSchema(schema);
153   } catch(e) {
154     setTimeout(function() { callback(e); });
155     return;
156   }
157   if (schemaObj.validate) {
158     setTimeout(function() { callback(null, schemaObj.validate); });
159   } else {
160     if (typeof this._opts.loadSchema != 'function')
161       throw new Error('options.loadSchema should be a function');
162     _compileAsync(schema, callback, true);
163   }
164
165
166   function _compileAsync(schema, callback, firstCall) {
167     var validate;
168     try { validate = self.compile(schema); }
169     catch(e) {
170       if (e.missingSchema) loadMissingSchema(e);
171       else deferCallback(e);
172       return;
173     }
174     deferCallback(null, validate);
175
176     function loadMissingSchema(e) {
177       var ref = e.missingSchema;
178       if (self._refs[ref] || self._schemas[ref])
179         return callback(new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'));
180       var _callbacks = self._loadingSchemas[ref];
181       if (_callbacks) {
182         if (typeof _callbacks == 'function')
183           self._loadingSchemas[ref] = [_callbacks, schemaLoaded];
184         else
185           _callbacks[_callbacks.length] = schemaLoaded;
186       } else {
187         self._loadingSchemas[ref] = schemaLoaded;
188         self._opts.loadSchema(ref, function (err, sch) {
189           var _callbacks = self._loadingSchemas[ref];
190           delete self._loadingSchemas[ref];
191           if (typeof _callbacks == 'function') {
192             _callbacks(err, sch);
193           } else {
194             for (var i=0; i<_callbacks.length; i++)
195               _callbacks[i](err, sch);
196           }
197         });
198       }
199
200       function schemaLoaded(err, sch) {
201         if (err) return callback(err);
202         if (!(self._refs[ref] || self._schemas[ref])) {
203           try {
204             self.addSchema(sch, ref);
205           } catch(e) {
206             callback(e);
207             return;
208           }
209         }
210         _compileAsync(schema, callback);
211       }
212     }
213
214     function deferCallback(err, validate) {
215       if (firstCall) setTimeout(function() { callback(err, validate); });
216       else return callback(err, validate);
217     }
218   }
219 }
220
221 },{"./compile/util":11}],2:[function(require,module,exports){
222 'use strict';
223
224
225 var Cache = module.exports = function Cache() {
226   this._cache = {};
227 };
228
229
230 Cache.prototype.put = function Cache_put(key, value) {
231   this._cache[key] = value;
232 };
233
234
235 Cache.prototype.get = function Cache_get(key) {
236   return this._cache[key];
237 };
238
239
240 Cache.prototype.del = function Cache_del(key) {
241   delete this._cache[key];
242 };
243
244
245 Cache.prototype.clear = function Cache_clear() {
246   this._cache = {};
247 };
248
249 },{}],3:[function(require,module,exports){
250 'use strict';
251
252 //all requires must be explicit because browserify won't work with dynamic requires
253 module.exports = {
254   '$ref': require('../dotjs/ref'),
255   allOf: require('../dotjs/allOf'),
256   anyOf: require('../dotjs/anyOf'),
257   dependencies: require('../dotjs/dependencies'),
258   'enum': require('../dotjs/enum'),
259   format: require('../dotjs/format'),
260   items: require('../dotjs/items'),
261   maximum: require('../dotjs/_limit'),
262   minimum: require('../dotjs/_limit'),
263   maxItems: require('../dotjs/_limitItems'),
264   minItems: require('../dotjs/_limitItems'),
265   maxLength: require('../dotjs/_limitLength'),
266   minLength: require('../dotjs/_limitLength'),
267   maxProperties: require('../dotjs/_limitProperties'),
268   minProperties: require('../dotjs/_limitProperties'),
269   multipleOf: require('../dotjs/multipleOf'),
270   not: require('../dotjs/not'),
271   oneOf: require('../dotjs/oneOf'),
272   pattern: require('../dotjs/pattern'),
273   properties: require('../dotjs/properties'),
274   required: require('../dotjs/required'),
275   uniqueItems: require('../dotjs/uniqueItems'),
276   validate: require('../dotjs/validate')
277 };
278
279 },{"../dotjs/_limit":14,"../dotjs/_limitItems":15,"../dotjs/_limitLength":16,"../dotjs/_limitProperties":17,"../dotjs/allOf":18,"../dotjs/anyOf":19,"../dotjs/dependencies":22,"../dotjs/enum":23,"../dotjs/format":24,"../dotjs/items":25,"../dotjs/multipleOf":26,"../dotjs/not":27,"../dotjs/oneOf":28,"../dotjs/pattern":29,"../dotjs/properties":31,"../dotjs/ref":32,"../dotjs/required":33,"../dotjs/uniqueItems":35,"../dotjs/validate":36}],4:[function(require,module,exports){
280 'use strict';
281
282 /*eslint complexity: 0*/
283
284 module.exports = function equal(a, b) {
285   if (a === b) return true;
286
287   var arrA = Array.isArray(a)
288     , arrB = Array.isArray(b)
289     , i;
290
291   if (arrA && arrB) {
292     if (a.length != b.length) return false;
293     for (i = 0; i < a.length; i++)
294       if (!equal(a[i], b[i])) return false;
295     return true;
296   }
297
298   if (arrA != arrB) return false;
299
300   if (a && b && typeof a === 'object' && typeof b === 'object') {
301     var keys = Object.keys(a);
302     if (keys.length !== Object.keys(b).length) return false;
303
304     var dateA = a instanceof Date
305       , dateB = b instanceof Date;
306     if (dateA && dateB) return a.getTime() == b.getTime();
307     if (dateA != dateB) return false;
308
309     var regexpA = a instanceof RegExp
310       , regexpB = b instanceof RegExp;
311     if (regexpA && regexpB) return a.toString() == b.toString();
312     if (regexpA != regexpB) return false;
313
314     for (i = 0; i < keys.length; i++)
315       if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
316
317     for (i = 0; i < keys.length; i++)
318       if(!equal(a[keys[i]], b[keys[i]])) return false;
319
320     return true;
321   }
322
323   return false;
324 };
325
326 },{}],5:[function(require,module,exports){
327 'use strict';
328
329 var util = require('./util');
330
331 var DATE = /^\d\d\d\d-(\d\d)-(\d\d)$/;
332 var DAYS = [0,31,29,31,30,31,30,31,31,30,31,30,31];
333 var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i;
334 var HOSTNAME = /^[0-9a-z](?:(?:[-0-9a-z]{0,61})?[0-9a-z])?(\.[0-9a-z](?:(?:[-0-9a-z]{0,61})?[0-9a-z])?)*$/i;
335 var URI = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?$/i;
336 var UUID = /^(?:urn\:uuid\:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
337 var JSON_POINTER = /^(?:\/(?:[^~\/]|~0|~1)*)*$|^\#(?:\/(?:[a-z0-9_\-\.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
338 var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:\#|(?:\/(?:[^~\/]|~0|~1)*)*)$/;
339
340
341 module.exports = formats;
342
343 function formats(mode) {
344   mode = mode == 'full' ? 'full' : 'fast';
345   var formatDefs = util.copy(formats[mode]);
346   for (var fName in formats.compare) {
347     formatDefs[fName] = {
348       validate: formatDefs[fName],
349       compare: formats.compare[fName]
350     };
351   }
352   return formatDefs;
353 }
354
355
356 formats.fast = {
357   // date: http://tools.ietf.org/html/rfc3339#section-5.6
358   date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
359   // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
360   time: /^[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i,
361   'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s][0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i,
362   // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
363   uri: /^(?:[a-z][a-z0-9+-.]*)?(?:\:|\/)\/?[^\s]*$/i,
364   // email (sources from jsen validator):
365   // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
366   // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
367   email: /^[a-z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
368   hostname: HOSTNAME,
369   // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
370   ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
371   // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
372   ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
373   regex: regex,
374   // uuid: http://tools.ietf.org/html/rfc4122
375   uuid: UUID,
376   // JSON-pointer: https://tools.ietf.org/html/rfc6901
377   // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
378   'json-pointer': JSON_POINTER,
379   // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
380   'relative-json-pointer': RELATIVE_JSON_POINTER
381 };
382
383
384 formats.full = {
385   date: date,
386   time: time,
387   'date-time': date_time,
388   uri: uri,
389   email: /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&''*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
390   hostname: hostname,
391   ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
392   ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
393   regex: regex,
394   uuid: UUID,
395   'json-pointer': JSON_POINTER,
396   'relative-json-pointer': RELATIVE_JSON_POINTER
397 };
398
399
400 formats.compare = {
401   date: compareDate,
402   time: compareTime,
403   'date-time': compareDateTime
404 };
405
406
407 function date(str) {
408   // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
409   var matches = str.match(DATE);
410   if (!matches) return false;
411
412   var month = +matches[1];
413   var day = +matches[2];
414   return month >= 1 && month <= 12 && day >= 1 && day <= DAYS[month];
415 }
416
417
418 function time(str, full) {
419   var matches = str.match(TIME);
420   if (!matches) return false;
421
422   var hour = matches[1];
423   var minute = matches[2];
424   var second = matches[3];
425   var timeZone = matches[5];
426   return hour <= 23 && minute <= 59 && second <= 59 && (!full || timeZone);
427 }
428
429
430 var DATE_TIME_SEPARATOR = /t|\s/i;
431 function date_time(str) {
432   // http://tools.ietf.org/html/rfc3339#section-5.6
433   var dateTime = str.split(DATE_TIME_SEPARATOR);
434   return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
435 }
436
437
438 function hostname(str) {
439   // https://tools.ietf.org/html/rfc1034#section-3.5
440   // https://tools.ietf.org/html/rfc1123#section-2
441   return str.length <= 255 && HOSTNAME.test(str);
442 }
443
444
445 var NOT_URI_FRAGMENT = /\/|\:/;
446 function uri(str) {
447   // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
448   return NOT_URI_FRAGMENT.test(str) && URI.test(str);
449 }
450
451
452 function regex(str) {
453   try {
454     new RegExp(str);
455     return true;
456   } catch(e) {
457     return false;
458   }
459 }
460
461
462 function compareDate(d1, d2) {
463   if (!(d1 && d2)) return;
464   if (d1 > d2) return 1;
465   if (d1 < d2) return -1;
466   if (d1 === d2) return 0;
467 }
468
469
470 function compareTime(t1, t2) {
471   if (!(t1 && t2)) return;
472   t1 = t1.match(TIME);
473   t2 = t2.match(TIME);
474   if (!(t1 && t2)) return;
475   t1 = t1[1] + t1[2] + t1[3] + (t1[4]||'');
476   t2 = t2[1] + t2[2] + t2[3] + (t2[4]||'');
477   if (t1 > t2) return 1;
478   if (t1 < t2) return -1;
479   if (t1 === t2) return 0;
480 }
481
482
483 function compareDateTime(dt1, dt2) {
484   if (!(dt1 && dt2)) return;
485   dt1 = dt1.split(DATE_TIME_SEPARATOR);
486   dt2 = dt2.split(DATE_TIME_SEPARATOR);
487   var res = compareDate(dt1[0], dt2[0]);
488   if (res === undefined) return;
489   return res || compareTime(dt1[1], dt2[1]);
490 }
491
492 },{"./util":11}],6:[function(require,module,exports){
493 'use strict';
494
495 var resolve = require('./resolve')
496   , util = require('./util')
497   , stableStringify = require('json-stable-stringify')
498   , async = require('../async');
499
500 var beautify;
501
502 function loadBeautify(){
503   if (beautify === undefined) {
504     var name = 'js-beautify';
505     try { beautify = require(name).js_beautify; }
506     catch(e) { beautify = false; }
507   }
508 }
509
510 var validateGenerator = require('../dotjs/validate');
511
512 /**
513  * Functions below are used inside compiled validations function
514  */
515
516 var co = require('co');
517 var ucs2length = util.ucs2length;
518 var equal = require('./equal');
519
520 // this error is thrown by async schemas to return validation errors via exception
521 var ValidationError = require('./validation_error');
522
523 module.exports = compile;
524
525
526 /**
527  * Compiles schema to validation function
528  * @this   Ajv
529  * @param  {Object} schema schema object
530  * @param  {Object} root object with information about the root schema for this schema
531  * @param  {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
532  * @param  {String} baseId base ID for IDs in the schema
533  * @return {Function} validation function
534  */
535 function compile(schema, root, localRefs, baseId) {
536   /* jshint validthis: true, evil: true */
537   /* eslint no-shadow: 0 */
538   var self = this
539     , opts = this._opts
540     , refVal = [ undefined ]
541     , refs = {}
542     , patterns = []
543     , patternsHash = {}
544     , defaults = []
545     , defaultsHash = {}
546     , customRules = []
547     , keepSourceCode = opts.sourceCode !== false;
548
549   root = root || { schema: schema, refVal: refVal, refs: refs };
550
551   var c = checkCompiling.call(this, schema, root, baseId);
552   var compilation = this._compilations[c.index];
553   if (c.compiling) return (compilation.callValidate = callValidate);
554
555   var formats = this._formats;
556   var RULES = this.RULES;
557
558   try {
559     var v = localCompile(schema, root, localRefs, baseId);
560     compilation.validate = v;
561     var cv = compilation.callValidate;
562     if (cv) {
563       cv.schema = v.schema;
564       cv.errors = null;
565       cv.refs = v.refs;
566       cv.refVal = v.refVal;
567       cv.root = v.root;
568       cv.$async = v.$async;
569       if (keepSourceCode) cv.sourceCode = v.sourceCode;
570     }
571     return v;
572   } finally {
573     endCompiling.call(this, schema, root, baseId);
574   }
575
576   function callValidate() {
577     var validate = compilation.validate;
578     var result = validate.apply(null, arguments);
579     callValidate.errors = validate.errors;
580     return result;
581   }
582
583   function localCompile(_schema, _root, localRefs, baseId) {
584     var isRoot = !_root || (_root && _root.schema == _schema);
585     if (_root.schema != root.schema)
586       return compile.call(self, _schema, _root, localRefs, baseId);
587
588     var $async = _schema.$async === true;
589     if ($async && !opts.transpile) async.setup(opts);
590
591     var sourceCode = validateGenerator({
592       isTop: true,
593       schema: _schema,
594       isRoot: isRoot,
595       baseId: baseId,
596       root: _root,
597       schemaPath: '',
598       errSchemaPath: '#',
599       errorPath: '""',
600       RULES: RULES,
601       validate: validateGenerator,
602       util: util,
603       resolve: resolve,
604       resolveRef: resolveRef,
605       usePattern: usePattern,
606       useDefault: useDefault,
607       useCustomRule: useCustomRule,
608       opts: opts,
609       formats: formats,
610       self: self
611     });
612
613     sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
614                    + vars(defaults, defaultCode) + vars(customRules, customRuleCode)
615                    + sourceCode;
616
617     if (opts.beautify) {
618       loadBeautify();
619       /* istanbul ignore else */
620       if (beautify) sourceCode = beautify(sourceCode, opts.beautify);
621       else console.error('"npm install js-beautify" to use beautify option');
622     }
623     // console.log('\n\n\n *** \n', sourceCode);
624     var validate, validateCode
625       , transpile = opts._transpileFunc;
626     try {
627       validateCode = $async && transpile
628                       ? transpile(sourceCode)
629                       : sourceCode;
630
631       var makeValidate = new Function(
632         'self',
633         'RULES',
634         'formats',
635         'root',
636         'refVal',
637         'defaults',
638         'customRules',
639         'co',
640         'equal',
641         'ucs2length',
642         'ValidationError',
643         validateCode
644       );
645
646       validate = makeValidate(
647         self,
648         RULES,
649         formats,
650         root,
651         refVal,
652         defaults,
653         customRules,
654         co,
655         equal,
656         ucs2length,
657         ValidationError
658       );
659
660       refVal[0] = validate;
661     } catch(e) {
662       console.error('Error compiling schema, function code:', validateCode);
663       throw e;
664     }
665
666     validate.schema = _schema;
667     validate.errors = null;
668     validate.refs = refs;
669     validate.refVal = refVal;
670     validate.root = isRoot ? validate : _root;
671     if ($async) validate.$async = true;
672     if (keepSourceCode) validate.sourceCode = sourceCode;
673     if (opts.sourceCode === true) {
674       validate.source = {
675         patterns: patterns,
676         defaults: defaults
677       };
678     }
679
680     return validate;
681   }
682
683   function resolveRef(baseId, ref, isRoot) {
684     ref = resolve.url(baseId, ref);
685     var refIndex = refs[ref];
686     var _refVal, refCode;
687     if (refIndex !== undefined) {
688       _refVal = refVal[refIndex];
689       refCode = 'refVal[' + refIndex + ']';
690       return resolvedRef(_refVal, refCode);
691     }
692     if (!isRoot && root.refs) {
693       var rootRefId = root.refs[ref];
694       if (rootRefId !== undefined) {
695         _refVal = root.refVal[rootRefId];
696         refCode = addLocalRef(ref, _refVal);
697         return resolvedRef(_refVal, refCode);
698       }
699     }
700
701     refCode = addLocalRef(ref);
702     var v = resolve.call(self, localCompile, root, ref);
703     if (!v) {
704       var localSchema = localRefs && localRefs[ref];
705       if (localSchema) {
706         v = resolve.inlineRef(localSchema, opts.inlineRefs)
707             ? localSchema
708             : compile.call(self, localSchema, root, localRefs, baseId);
709       }
710     }
711
712     if (v) {
713       replaceLocalRef(ref, v);
714       return resolvedRef(v, refCode);
715     }
716   }
717
718   function addLocalRef(ref, v) {
719     var refId = refVal.length;
720     refVal[refId] = v;
721     refs[ref] = refId;
722     return 'refVal' + refId;
723   }
724
725   function replaceLocalRef(ref, v) {
726     var refId = refs[ref];
727     refVal[refId] = v;
728   }
729
730   function resolvedRef(refVal, code) {
731     return typeof refVal == 'object'
732             ? { code: code, schema: refVal, inline: true }
733             : { code: code, $async: refVal && refVal.$async };
734   }
735
736   function usePattern(regexStr) {
737     var index = patternsHash[regexStr];
738     if (index === undefined) {
739       index = patternsHash[regexStr] = patterns.length;
740       patterns[index] = regexStr;
741     }
742     return 'pattern' + index;
743   }
744
745   function useDefault(value) {
746     switch (typeof value) {
747       case 'boolean':
748       case 'number':
749         return '' + value;
750       case 'string':
751         return util.toQuotedString(value);
752       case 'object':
753         if (value === null) return 'null';
754         var valueStr = stableStringify(value);
755         var index = defaultsHash[valueStr];
756         if (index === undefined) {
757           index = defaultsHash[valueStr] = defaults.length;
758           defaults[index] = value;
759         }
760         return 'default' + index;
761     }
762   }
763
764   function useCustomRule(rule, schema, parentSchema, it) {
765     var validateSchema = rule.definition.validateSchema;
766     if (validateSchema && self._opts.validateSchema !== false) {
767       var valid = validateSchema(schema);
768       if (!valid) {
769         var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
770         if (self._opts.validateSchema == 'log') console.error(message);
771         else throw new Error(message);
772       }
773     }
774
775     var compile = rule.definition.compile
776       , inline = rule.definition.inline
777       , macro = rule.definition.macro;
778
779     var validate;
780     if (compile) {
781       validate = compile.call(self, schema, parentSchema, it);
782     } else if (macro) {
783       validate = macro.call(self, schema, parentSchema, it);
784       if (opts.validateSchema !== false) self.validateSchema(validate, true);
785     } else if (inline) {
786       validate = inline.call(self, it, rule.keyword, schema, parentSchema);
787     } else {
788       validate = rule.definition.validate;
789     }
790
791     var index = customRules.length;
792     customRules[index] = validate;
793
794     return {
795       code: 'customRule' + index,
796       validate: validate
797     };
798   }
799 }
800
801
802 /**
803  * Checks if the schema is currently compiled
804  * @this   Ajv
805  * @param  {Object} schema schema to compile
806  * @param  {Object} root root object
807  * @param  {String} baseId base schema ID
808  * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
809  */
810 function checkCompiling(schema, root, baseId) {
811   /* jshint validthis: true */
812   var index = compIndex.call(this, schema, root, baseId);
813   if (index >= 0) return { index: index, compiling: true };
814   index = this._compilations.length;
815   this._compilations[index] = {
816     schema: schema,
817     root: root,
818     baseId: baseId
819   };
820   return { index: index, compiling: false };
821 }
822
823
824 /**
825  * Removes the schema from the currently compiled list
826  * @this   Ajv
827  * @param  {Object} schema schema to compile
828  * @param  {Object} root root object
829  * @param  {String} baseId base schema ID
830  */
831 function endCompiling(schema, root, baseId) {
832   /* jshint validthis: true */
833   var i = compIndex.call(this, schema, root, baseId);
834   if (i >= 0) this._compilations.splice(i, 1);
835 }
836
837
838 /**
839  * Index of schema compilation in the currently compiled list
840  * @this   Ajv
841  * @param  {Object} schema schema to compile
842  * @param  {Object} root root object
843  * @param  {String} baseId base schema ID
844  * @return {Integer} compilation index
845  */
846 function compIndex(schema, root, baseId) {
847   /* jshint validthis: true */
848   for (var i=0; i<this._compilations.length; i++) {
849     var c = this._compilations[i];
850     if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
851   }
852   return -1;
853 }
854
855
856 function patternCode(i, patterns) {
857   return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
858 }
859
860
861 function defaultCode(i) {
862   return 'var default' + i + ' = defaults[' + i + '];';
863 }
864
865
866 function refValCode(i, refVal) {
867   return refVal[i] ? 'var refVal' + i + ' = refVal[' + i + '];' : '';
868 }
869
870
871 function customRuleCode(i) {
872   return 'var customRule' + i + ' = customRules[' + i + '];';
873 }
874
875
876 function vars(arr, statement) {
877   if (!arr.length) return '';
878   var code = '';
879   for (var i=0; i<arr.length; i++)
880     code += statement(i, arr);
881   return code;
882 }
883
884 },{"../async":1,"../dotjs/validate":36,"./equal":4,"./resolve":7,"./util":11,"./validation_error":12,"co":47,"json-stable-stringify":48}],7:[function(require,module,exports){
885 'use strict';
886
887 var url = require('url')
888   , equal = require('./equal')
889   , util = require('./util')
890   , SchemaObject = require('./schema_obj');
891
892 module.exports = resolve;
893
894 resolve.normalizeId = normalizeId;
895 resolve.fullPath = getFullPath;
896 resolve.url = resolveUrl;
897 resolve.ids = resolveIds;
898 resolve.inlineRef = inlineRef;
899 resolve.schema = resolveSchema;
900
901 /**
902  * [resolve and compile the references ($ref)]
903  * @this   Ajv
904  * @param  {Function} compile reference to schema compilation funciton (localCompile)
905  * @param  {Object} root object with information about the root schema for the current schema
906  * @param  {String} ref reference to resolve
907  * @return {Object|Function} schema object (if the schema can be inlined) or validation function
908  */
909 function resolve(compile, root, ref) {
910   /* jshint validthis: true */
911   var refVal = this._refs[ref];
912   if (typeof refVal == 'string') {
913     if (this._refs[refVal]) refVal = this._refs[refVal];
914     else return resolve.call(this, compile, root, refVal);
915   }
916
917   refVal = refVal || this._schemas[ref];
918   if (refVal instanceof SchemaObject) {
919     return inlineRef(refVal.schema, this._opts.inlineRefs)
920             ? refVal.schema
921             : refVal.validate || this._compile(refVal);
922   }
923
924   var res = resolveSchema.call(this, root, ref);
925   var schema, v, baseId;
926   if (res) {
927     schema = res.schema;
928     root = res.root;
929     baseId = res.baseId;
930   }
931
932   if (schema instanceof SchemaObject) {
933     v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
934   } else if (schema) {
935     v = inlineRef(schema, this._opts.inlineRefs)
936         ? schema
937         : compile.call(this, schema, root, undefined, baseId);
938   }
939
940   return v;
941 }
942
943
944 /**
945  * Resolve schema, its root and baseId
946  * @this Ajv
947  * @param  {Object} root root object with properties schema, refVal, refs
948  * @param  {String} ref  reference to resolve
949  * @return {Object} object with properties schema, root, baseId
950  */
951 function resolveSchema(root, ref) {
952   /* jshint validthis: true */
953   var p = url.parse(ref, false, true)
954     , refPath = _getFullPath(p)
955     , baseId = getFullPath(root.schema.id);
956   if (refPath !== baseId) {
957     var id = normalizeId(refPath);
958     var refVal = this._refs[id];
959     if (typeof refVal == 'string') {
960       return resolveRecursive.call(this, root, refVal, p);
961     } else if (refVal instanceof SchemaObject) {
962       if (!refVal.validate) this._compile(refVal);
963       root = refVal;
964     } else {
965       refVal = this._schemas[id];
966       if (refVal instanceof SchemaObject) {
967         if (!refVal.validate) this._compile(refVal);
968         if (id == normalizeId(ref))
969           return { schema: refVal, root: root, baseId: baseId };
970         root = refVal;
971       } else {
972         return;
973       }
974     }
975     if (!root.schema) return;
976     baseId = getFullPath(root.schema.id);
977   }
978   return getJsonPointer.call(this, p, baseId, root.schema, root);
979 }
980
981
982 /* @this Ajv */
983 function resolveRecursive(root, ref, parsedRef) {
984   /* jshint validthis: true */
985   var res = resolveSchema.call(this, root, ref);
986   if (res) {
987     var schema = res.schema;
988     var baseId = res.baseId;
989     root = res.root;
990     if (schema.id) baseId = resolveUrl(baseId, schema.id);
991     return getJsonPointer.call(this, parsedRef, baseId, schema, root);
992   }
993 }
994
995
996 var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']);
997 /* @this Ajv */
998 function getJsonPointer(parsedRef, baseId, schema, root) {
999   /* jshint validthis: true */
1000   parsedRef.hash = parsedRef.hash || '';
1001   if (parsedRef.hash.slice(0,2) != '#/') return;
1002   var parts = parsedRef.hash.split('/');
1003
1004   for (var i = 1; i < parts.length; i++) {
1005     var part = parts[i];
1006     if (part) {
1007       part = util.unescapeFragment(part);
1008       schema = schema[part];
1009       if (!schema) break;
1010       if (schema.id && !PREVENT_SCOPE_CHANGE[part]) baseId = resolveUrl(baseId, schema.id);
1011       if (schema.$ref) {
1012         var $ref = resolveUrl(baseId, schema.$ref);
1013         var res = resolveSchema.call(this, root, $ref);
1014         if (res) {
1015           schema = res.schema;
1016           root = res.root;
1017           baseId = res.baseId;
1018         }
1019       }
1020     }
1021   }
1022   if (schema && schema != root.schema)
1023     return { schema: schema, root: root, baseId: baseId };
1024 }
1025
1026
1027 var SIMPLE_INLINED = util.toHash([
1028   'type', 'format', 'pattern',
1029   'maxLength', 'minLength',
1030   'maxProperties', 'minProperties',
1031   'maxItems', 'minItems',
1032   'maximum', 'minimum',
1033   'uniqueItems', 'multipleOf',
1034   'required', 'enum'
1035 ]);
1036 function inlineRef(schema, limit) {
1037   if (limit === false) return false;
1038   if (limit === undefined || limit === true) return checkNoRef(schema);
1039   else if (limit) return countKeys(schema) <= limit;
1040 }
1041
1042
1043 function checkNoRef(schema) {
1044   var item;
1045   if (Array.isArray(schema)) {
1046     for (var i=0; i<schema.length; i++) {
1047       item = schema[i];
1048       if (typeof item == 'object' && !checkNoRef(item)) return false;
1049     }
1050   } else {
1051     for (var key in schema) {
1052       if (key == '$ref') return false;
1053       item = schema[key];
1054       if (typeof item == 'object' && !checkNoRef(item)) return false;
1055     }
1056   }
1057   return true;
1058 }
1059
1060
1061 function countKeys(schema) {
1062   var count = 0, item;
1063   if (Array.isArray(schema)) {
1064     for (var i=0; i<schema.length; i++) {
1065       item = schema[i];
1066       if (typeof item == 'object') count += countKeys(item);
1067       if (count == Infinity) return Infinity;
1068     }
1069   } else {
1070     for (var key in schema) {
1071       if (key == '$ref') return Infinity;
1072       if (SIMPLE_INLINED[key]) {
1073         count++;
1074       } else {
1075         item = schema[key];
1076         if (typeof item == 'object') count += countKeys(item) + 1;
1077         if (count == Infinity) return Infinity;
1078       }
1079     }
1080   }
1081   return count;
1082 }
1083
1084
1085 function getFullPath(id, normalize) {
1086   if (normalize !== false) id = normalizeId(id);
1087   var p = url.parse(id, false, true);
1088   return _getFullPath(p);
1089 }
1090
1091
1092 function _getFullPath(p) {
1093   var protocolSeparator = p.protocol || p.href.slice(0,2) == '//' ? '//' : '';
1094   return (p.protocol||'') + protocolSeparator + (p.host||'') + (p.path||'')  + '#';
1095 }
1096
1097
1098 var TRAILING_SLASH_HASH = /#\/?$/;
1099 function normalizeId(id) {
1100   return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
1101 }
1102
1103
1104 function resolveUrl(baseId, id) {
1105   id = normalizeId(id);
1106   return url.resolve(baseId, id);
1107 }
1108
1109
1110 /* @this Ajv */
1111 function resolveIds(schema) {
1112   /* eslint no-shadow: 0 */
1113   /* jshint validthis: true */
1114   var id = normalizeId(schema.id);
1115   var localRefs = {};
1116   _resolveIds.call(this, schema, getFullPath(id, false), id);
1117   return localRefs;
1118
1119   /* @this Ajv */
1120   function _resolveIds(schema, fullPath, baseId) {
1121     /* jshint validthis: true */
1122     if (Array.isArray(schema)) {
1123       for (var i=0; i<schema.length; i++)
1124         _resolveIds.call(this, schema[i], fullPath+'/'+i, baseId);
1125     } else if (schema && typeof schema == 'object') {
1126       if (typeof schema.id == 'string') {
1127         var id = baseId = baseId
1128                           ? url.resolve(baseId, schema.id)
1129                           : schema.id;
1130         id = normalizeId(id);
1131
1132         var refVal = this._refs[id];
1133         if (typeof refVal == 'string') refVal = this._refs[refVal];
1134         if (refVal && refVal.schema) {
1135           if (!equal(schema, refVal.schema))
1136             throw new Error('id "' + id + '" resolves to more than one schema');
1137         } else if (id != normalizeId(fullPath)) {
1138           if (id[0] == '#') {
1139             if (localRefs[id] && !equal(schema, localRefs[id]))
1140               throw new Error('id "' + id + '" resolves to more than one schema');
1141             localRefs[id] = schema;
1142           } else {
1143             this._refs[id] = fullPath;
1144           }
1145         }
1146       }
1147       for (var key in schema)
1148         _resolveIds.call(this, schema[key], fullPath+'/'+util.escapeFragment(key), baseId);
1149     }
1150   }
1151 }
1152
1153 },{"./equal":4,"./schema_obj":9,"./util":11,"url":45}],8:[function(require,module,exports){
1154 'use strict';
1155
1156 var ruleModules = require('./_rules')
1157   , toHash = require('./util').toHash;
1158
1159 module.exports = function rules() {
1160   var RULES = [
1161     { type: 'number',
1162       rules: [ 'maximum', 'minimum', 'multipleOf'] },
1163     { type: 'string',
1164       rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] },
1165     { type: 'array',
1166       rules: [ 'maxItems', 'minItems', 'uniqueItems', 'items' ] },
1167     { type: 'object',
1168       rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'properties' ] },
1169     { rules: [ '$ref', 'enum', 'not', 'anyOf', 'oneOf', 'allOf' ] }
1170   ];
1171
1172   var ALL = [ 'type', 'additionalProperties', 'patternProperties' ];
1173   var KEYWORDS = [ 'additionalItems', '$schema', 'id', 'title', 'description', 'default' ];
1174   var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ];
1175   RULES.all = toHash(ALL);
1176
1177   RULES.forEach(function (group) {
1178     group.rules = group.rules.map(function (keyword) {
1179       ALL.push(keyword);
1180       var rule = RULES.all[keyword] = {
1181         keyword: keyword,
1182         code: ruleModules[keyword]
1183       };
1184       return rule;
1185     });
1186   });
1187
1188   RULES.keywords = toHash(ALL.concat(KEYWORDS));
1189   RULES.types = toHash(TYPES);
1190   RULES.custom = {};
1191
1192   return RULES;
1193 };
1194
1195 },{"./_rules":3,"./util":11}],9:[function(require,module,exports){
1196 'use strict';
1197
1198 var util = require('./util');
1199
1200 module.exports = SchemaObject;
1201
1202 function SchemaObject(obj) {
1203   util.copy(obj, this);
1204 }
1205
1206 },{"./util":11}],10:[function(require,module,exports){
1207 'use strict';
1208
1209 // https://mathiasbynens.be/notes/javascript-encoding
1210 // https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
1211 module.exports = function ucs2length(str) {
1212   var length = 0
1213     , len = str.length
1214     , pos = 0
1215     , value;
1216   while (pos < len) {
1217     length++;
1218     value = str.charCodeAt(pos++);
1219     if (value >= 0xD800 && value <= 0xDBFF && pos < len) {
1220       // high surrogate, and there is a next character
1221       value = str.charCodeAt(pos);
1222       if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate
1223     }
1224   }
1225   return length;
1226 };
1227
1228 },{}],11:[function(require,module,exports){
1229 'use strict';
1230
1231
1232 module.exports = {
1233   copy: copy,
1234   checkDataType: checkDataType,
1235   checkDataTypes: checkDataTypes,
1236   coerceToTypes: coerceToTypes,
1237   toHash: toHash,
1238   getProperty: getProperty,
1239   escapeQuotes: escapeQuotes,
1240   ucs2length: require('./ucs2length'),
1241   varOccurences: varOccurences,
1242   varReplace: varReplace,
1243   cleanUpCode: cleanUpCode,
1244   cleanUpVarErrors: cleanUpVarErrors,
1245   schemaHasRules: schemaHasRules,
1246   schemaHasRulesExcept: schemaHasRulesExcept,
1247   stableStringify: require('json-stable-stringify'),
1248   toQuotedString: toQuotedString,
1249   getPathExpr: getPathExpr,
1250   getPath: getPath,
1251   getData: getData,
1252   unescapeFragment: unescapeFragment,
1253   escapeFragment: escapeFragment,
1254   escapeJsonPointer: escapeJsonPointer
1255 };
1256
1257
1258 function copy(o, to) {
1259   to = to || {};
1260   for (var key in o) to[key] = o[key];
1261   return to;
1262 }
1263
1264
1265 function checkDataType(dataType, data, negate) {
1266   var EQUAL = negate ? ' !== ' : ' === '
1267     , AND = negate ? ' || ' : ' && '
1268     , OK = negate ? '!' : ''
1269     , NOT = negate ? '' : '!';
1270   switch (dataType) {
1271     case 'null': return data + EQUAL + 'null';
1272     case 'array': return OK + 'Array.isArray(' + data + ')';
1273     case 'object': return '(' + OK + data + AND +
1274                           'typeof ' + data + EQUAL + '"object"' + AND +
1275                           NOT + 'Array.isArray(' + data + '))';
1276     case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
1277                            NOT + '(' + data + ' % 1)' +
1278                            AND + data + EQUAL + data + ')';
1279     default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
1280   }
1281 }
1282
1283
1284 function checkDataTypes(dataTypes, data) {
1285   switch (dataTypes.length) {
1286     case 1: return checkDataType(dataTypes[0], data, true);
1287     default:
1288       var code = '';
1289       var types = toHash(dataTypes);
1290       if (types.array && types.object) {
1291         code = types.null ? '(': '(!' + data + ' || ';
1292         code += 'typeof ' + data + ' !== "object")';
1293         delete types.null;
1294         delete types.array;
1295         delete types.object;
1296       }
1297       if (types.number) delete types.integer;
1298       for (var t in types)
1299         code += (code ? ' && ' : '' ) + checkDataType(t, data, true);
1300
1301       return code;
1302   }
1303 }
1304
1305
1306 var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
1307 function coerceToTypes(optionCoerceTypes, dataTypes) {
1308   if (Array.isArray(dataTypes)) {
1309     var types = [];
1310     for (var i=0; i<dataTypes.length; i++) {
1311       var t = dataTypes[i];
1312       if (COERCE_TO_TYPES[t]) types[types.length] = t;
1313       else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
1314     }
1315     if (types.length) return types;
1316   } else if (COERCE_TO_TYPES[dataTypes]) {
1317     return [dataTypes];
1318   } else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
1319     return ['array'];
1320   }
1321 }
1322
1323
1324 function toHash(arr) {
1325   var hash = {};
1326   for (var i=0; i<arr.length; i++) hash[arr[i]] = true;
1327   return hash;
1328 }
1329
1330
1331 var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
1332 var SINGLE_QUOTE = /'|\\/g;
1333 function getProperty(key) {
1334   return typeof key == 'number'
1335           ? '[' + key + ']'
1336           : IDENTIFIER.test(key)
1337             ? '.' + key
1338             : "['" + escapeQuotes(key) + "']";
1339 }
1340
1341
1342 function escapeQuotes(str) {
1343   return str.replace(SINGLE_QUOTE, '\\$&')
1344             .replace(/\n/g, '\\n')
1345             .replace(/\r/g, '\\r')
1346             .replace(/\f/g, '\\f')
1347             .replace(/\t/g, '\\t');
1348 }
1349
1350
1351 function varOccurences(str, dataVar) {
1352   dataVar += '[^0-9]';
1353   var matches = str.match(new RegExp(dataVar, 'g'));
1354   return matches ? matches.length : 0;
1355 }
1356
1357
1358 function varReplace(str, dataVar, expr) {
1359   dataVar += '([^0-9])';
1360   expr = expr.replace(/\$/g, '$$$$');
1361   return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
1362 }
1363
1364
1365 var EMPTY_ELSE = /else\s*{\s*}/g
1366   , EMPTY_IF_NO_ELSE = /if\s*\([^)]+\)\s*\{\s*\}(?!\s*else)/g
1367   , EMPTY_IF_WITH_ELSE = /if\s*\(([^)]+)\)\s*\{\s*\}\s*else(?!\s*if)/g;
1368 function cleanUpCode(out) {
1369   return out.replace(EMPTY_ELSE, '')
1370             .replace(EMPTY_IF_NO_ELSE, '')
1371             .replace(EMPTY_IF_WITH_ELSE, 'if (!($1))');
1372 }
1373
1374
1375 var ERRORS_REGEXP = /[^v\.]errors/g
1376   , REMOVE_ERRORS = /var errors = 0;|var vErrors = null;|validate.errors = vErrors;/g
1377   , REMOVE_ERRORS_ASYNC = /var errors = 0;|var vErrors = null;/g
1378   , RETURN_VALID = 'return errors === 0;'
1379   , RETURN_TRUE = 'validate.errors = null; return true;'
1380   , RETURN_ASYNC = /if \(errors === 0\) return true;\s*else throw new ValidationError\(vErrors\);/
1381   , RETURN_TRUE_ASYNC = 'return true;';
1382
1383 function cleanUpVarErrors(out, async) {
1384   var matches = out.match(ERRORS_REGEXP);
1385   if (!matches || matches.length !== 2) return out;
1386   return async
1387           ? out.replace(REMOVE_ERRORS_ASYNC, '')
1388                .replace(RETURN_ASYNC, RETURN_TRUE_ASYNC)
1389           : out.replace(REMOVE_ERRORS, '')
1390                .replace(RETURN_VALID, RETURN_TRUE);
1391 }
1392
1393
1394 function schemaHasRules(schema, rules) {
1395   for (var key in schema) if (rules[key]) return true;
1396 }
1397
1398
1399 function schemaHasRulesExcept(schema, rules, exceptKeyword) {
1400   for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
1401 }
1402
1403
1404 function toQuotedString(str) {
1405   return '\'' + escapeQuotes(str) + '\'';
1406 }
1407
1408
1409 function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
1410   var path = jsonPointers // false by default
1411               ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
1412               : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
1413   return joinPaths(currentPath, path);
1414 }
1415
1416
1417 function getPath(currentPath, prop, jsonPointers) {
1418   var path = jsonPointers // false by default
1419               ? toQuotedString('/' + escapeJsonPointer(prop))
1420               : toQuotedString(getProperty(prop));
1421   return joinPaths(currentPath, path);
1422 }
1423
1424
1425 var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
1426 var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
1427 function getData($data, lvl, paths) {
1428   var up, jsonPointer, data, matches;
1429   if ($data === '') return 'rootData';
1430   if ($data[0] == '/') {
1431     if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
1432     jsonPointer = $data;
1433     data = 'rootData';
1434   } else {
1435     matches = $data.match(RELATIVE_JSON_POINTER);
1436     if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
1437     up = +matches[1];
1438     jsonPointer = matches[2];
1439     if (jsonPointer == '#') {
1440       if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
1441       return paths[lvl - up];
1442     }
1443
1444     if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
1445     data = 'data' + ((lvl - up) || '');
1446     if (!jsonPointer) return data;
1447   }
1448
1449   var expr = data;
1450   var segments = jsonPointer.split('/');
1451   for (var i=0; i<segments.length; i++) {
1452     var segment = segments[i];
1453     if (segment) {
1454       data += getProperty(unescapeJsonPointer(segment));
1455       expr += ' && ' + data;
1456     }
1457   }
1458   return expr;
1459 }
1460
1461
1462 function joinPaths (a, b) {
1463   if (a == '""') return b;
1464   return (a + ' + ' + b).replace(/' \+ '/g, '');
1465 }
1466
1467
1468 function unescapeFragment(str) {
1469   return unescapeJsonPointer(decodeURIComponent(str));
1470 }
1471
1472
1473 function escapeFragment(str) {
1474   return encodeURIComponent(escapeJsonPointer(str));
1475 }
1476
1477
1478 function escapeJsonPointer(str) {
1479   return str.replace(/~/g, '~0').replace(/\//g, '~1');
1480 }
1481
1482
1483 function unescapeJsonPointer(str) {
1484   return str.replace(/~1/g, '/').replace(/~0/g, '~');
1485 }
1486
1487 },{"./ucs2length":10,"json-stable-stringify":48}],12:[function(require,module,exports){
1488 'use strict';
1489
1490 module.exports = ValidationError;
1491
1492
1493 function ValidationError(errors) {
1494   this.message = 'validation failed';
1495   this.errors = errors;
1496   this.ajv = this.validation = true;
1497 }
1498
1499
1500 ValidationError.prototype = Object.create(Error.prototype);
1501 ValidationError.prototype.constructor = ValidationError;
1502
1503 },{}],13:[function(require,module,exports){
1504 'use strict';
1505 module.exports = function generate__formatLimit(it, $keyword) {
1506   var out = ' ';
1507   var $lvl = it.level;
1508   var $dataLvl = it.dataLevel;
1509   var $schema = it.schema[$keyword];
1510   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
1511   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
1512   var $breakOnError = !it.opts.allErrors;
1513   var $errorKeyword;
1514   var $data = 'data' + ($dataLvl || '');
1515   var $valid = 'valid' + $lvl;
1516   out += 'var ' + ($valid) + ' = undefined;';
1517   if (it.opts.format === false) {
1518     out += ' ' + ($valid) + ' = true; ';
1519     return out;
1520   }
1521   var $schemaFormat = it.schema.format,
1522     $isDataFormat = it.opts.v5 && $schemaFormat.$data,
1523     $closingBraces = '';
1524   if ($isDataFormat) {
1525     var $schemaValueFormat = it.util.getData($schemaFormat.$data, $dataLvl, it.dataPathArr),
1526       $format = 'format' + $lvl,
1527       $compare = 'compare' + $lvl;
1528     out += ' var ' + ($format) + ' = formats[' + ($schemaValueFormat) + '] , ' + ($compare) + ' = ' + ($format) + ' && ' + ($format) + '.compare;';
1529   } else {
1530     var $format = it.formats[$schemaFormat];
1531     if (!($format && $format.compare)) {
1532       out += '  ' + ($valid) + ' = true; ';
1533       return out;
1534     }
1535     var $compare = 'formats' + it.util.getProperty($schemaFormat) + '.compare';
1536   }
1537   var $isMax = $keyword == 'formatMaximum',
1538     $exclusiveKeyword = 'formatExclusive' + ($isMax ? 'Maximum' : 'Minimum'),
1539     $schemaExcl = it.schema[$exclusiveKeyword],
1540     $isDataExcl = it.opts.v5 && $schemaExcl && $schemaExcl.$data,
1541     $op = $isMax ? '<' : '>',
1542     $result = 'result' + $lvl;
1543   var $isData = it.opts.v5 && $schema && $schema.$data,
1544     $schemaValue;
1545   if ($isData) {
1546     out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
1547     $schemaValue = 'schema' + $lvl;
1548   } else {
1549     $schemaValue = $schema;
1550   }
1551   if ($isDataExcl) {
1552     var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
1553       $exclusive = 'exclusive' + $lvl,
1554       $opExpr = 'op' + $lvl,
1555       $opStr = '\' + ' + $opExpr + ' + \'';
1556     out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
1557     $schemaValueExcl = 'schemaExcl' + $lvl;
1558     out += ' if (typeof ' + ($schemaValueExcl) + ' != \'boolean\' && ' + ($schemaValueExcl) + ' !== undefined) { ' + ($valid) + ' = false; ';
1559     var $errorKeyword = $exclusiveKeyword;
1560     var $$outStack = $$outStack || [];
1561     $$outStack.push(out);
1562     out = ''; /* istanbul ignore else */
1563     if (it.createErrors !== false) {
1564       out += ' { keyword: \'' + ($errorKeyword || '_formatExclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
1565       if (it.opts.messages !== false) {
1566         out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
1567       }
1568       if (it.opts.verbose) {
1569         out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
1570       }
1571       out += ' } ';
1572     } else {
1573       out += ' {} ';
1574     }
1575     var __err = out;
1576     out = $$outStack.pop();
1577     if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
1578       if (it.async) {
1579         out += ' throw new ValidationError([' + (__err) + ']); ';
1580       } else {
1581         out += ' validate.errors = [' + (__err) + ']; return false; ';
1582       }
1583     } else {
1584       out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
1585     }
1586     out += ' }  ';
1587     if ($breakOnError) {
1588       $closingBraces += '}';
1589       out += ' else { ';
1590     }
1591     if ($isData) {
1592       out += ' if (' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'string\') ' + ($valid) + ' = false; else { ';
1593       $closingBraces += '}';
1594     }
1595     if ($isDataFormat) {
1596       out += ' if (!' + ($compare) + ') ' + ($valid) + ' = true; else { ';
1597       $closingBraces += '}';
1598     }
1599     out += ' var ' + ($result) + ' = ' + ($compare) + '(' + ($data) + ',  ';
1600     if ($isData) {
1601       out += '' + ($schemaValue);
1602     } else {
1603       out += '' + (it.util.toQuotedString($schema));
1604     }
1605     out += ' ); if (' + ($result) + ' === undefined) ' + ($valid) + ' = false; var ' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true; if (' + ($valid) + ' === undefined) { ' + ($valid) + ' = ' + ($exclusive) + ' ? ' + ($result) + ' ' + ($op) + ' 0 : ' + ($result) + ' ' + ($op) + '= 0; } if (!' + ($valid) + ') var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';';
1606   } else {
1607     var $exclusive = $schemaExcl === true,
1608       $opStr = $op;
1609     if (!$exclusive) $opStr += '=';
1610     var $opExpr = '\'' + $opStr + '\'';
1611     if ($isData) {
1612       out += ' if (' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'string\') ' + ($valid) + ' = false; else { ';
1613       $closingBraces += '}';
1614     }
1615     if ($isDataFormat) {
1616       out += ' if (!' + ($compare) + ') ' + ($valid) + ' = true; else { ';
1617       $closingBraces += '}';
1618     }
1619     out += ' var ' + ($result) + ' = ' + ($compare) + '(' + ($data) + ',  ';
1620     if ($isData) {
1621       out += '' + ($schemaValue);
1622     } else {
1623       out += '' + (it.util.toQuotedString($schema));
1624     }
1625     out += ' ); if (' + ($result) + ' === undefined) ' + ($valid) + ' = false; if (' + ($valid) + ' === undefined) ' + ($valid) + ' = ' + ($result) + ' ' + ($op);
1626     if (!$exclusive) {
1627       out += '=';
1628     }
1629     out += ' 0;';
1630   }
1631   out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { ';
1632   var $errorKeyword = $keyword;
1633   var $$outStack = $$outStack || [];
1634   $$outStack.push(out);
1635   out = ''; /* istanbul ignore else */
1636   if (it.createErrors !== false) {
1637     out += ' { keyword: \'' + ($errorKeyword || '_formatLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit:  ';
1638     if ($isData) {
1639       out += '' + ($schemaValue);
1640     } else {
1641       out += '' + (it.util.toQuotedString($schema));
1642     }
1643     out += ' , exclusive: ' + ($exclusive) + ' } ';
1644     if (it.opts.messages !== false) {
1645       out += ' , message: \'should be ' + ($opStr) + ' "';
1646       if ($isData) {
1647         out += '\' + ' + ($schemaValue) + ' + \'';
1648       } else {
1649         out += '' + (it.util.escapeQuotes($schema));
1650       }
1651       out += '"\' ';
1652     }
1653     if (it.opts.verbose) {
1654       out += ' , schema:  ';
1655       if ($isData) {
1656         out += 'validate.schema' + ($schemaPath);
1657       } else {
1658         out += '' + (it.util.toQuotedString($schema));
1659       }
1660       out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
1661     }
1662     out += ' } ';
1663   } else {
1664     out += ' {} ';
1665   }
1666   var __err = out;
1667   out = $$outStack.pop();
1668   if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
1669     if (it.async) {
1670       out += ' throw new ValidationError([' + (__err) + ']); ';
1671     } else {
1672       out += ' validate.errors = [' + (__err) + ']; return false; ';
1673     }
1674   } else {
1675     out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
1676   }
1677   out += '}';
1678   return out;
1679 }
1680
1681 },{}],14:[function(require,module,exports){
1682 'use strict';
1683 module.exports = function generate__limit(it, $keyword) {
1684   var out = ' ';
1685   var $lvl = it.level;
1686   var $dataLvl = it.dataLevel;
1687   var $schema = it.schema[$keyword];
1688   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
1689   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
1690   var $breakOnError = !it.opts.allErrors;
1691   var $errorKeyword;
1692   var $data = 'data' + ($dataLvl || '');
1693   var $isData = it.opts.v5 && $schema && $schema.$data,
1694     $schemaValue;
1695   if ($isData) {
1696     out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
1697     $schemaValue = 'schema' + $lvl;
1698   } else {
1699     $schemaValue = $schema;
1700   }
1701   var $isMax = $keyword == 'maximum',
1702     $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum',
1703     $schemaExcl = it.schema[$exclusiveKeyword],
1704     $isDataExcl = it.opts.v5 && $schemaExcl && $schemaExcl.$data,
1705     $op = $isMax ? '<' : '>',
1706     $notOp = $isMax ? '>' : '<';
1707   if ($isDataExcl) {
1708     var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
1709       $exclusive = 'exclusive' + $lvl,
1710       $opExpr = 'op' + $lvl,
1711       $opStr = '\' + ' + $opExpr + ' + \'';
1712     out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
1713     $schemaValueExcl = 'schemaExcl' + $lvl;
1714     out += ' var exclusive' + ($lvl) + '; if (typeof ' + ($schemaValueExcl) + ' != \'boolean\' && typeof ' + ($schemaValueExcl) + ' != \'undefined\') { ';
1715     var $errorKeyword = $exclusiveKeyword;
1716     var $$outStack = $$outStack || [];
1717     $$outStack.push(out);
1718     out = ''; /* istanbul ignore else */
1719     if (it.createErrors !== false) {
1720       out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
1721       if (it.opts.messages !== false) {
1722         out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
1723       }
1724       if (it.opts.verbose) {
1725         out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
1726       }
1727       out += ' } ';
1728     } else {
1729       out += ' {} ';
1730     }
1731     var __err = out;
1732     out = $$outStack.pop();
1733     if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
1734       if (it.async) {
1735         out += ' throw new ValidationError([' + (__err) + ']); ';
1736       } else {
1737         out += ' validate.errors = [' + (__err) + ']; return false; ';
1738       }
1739     } else {
1740       out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
1741     }
1742     out += ' } else if( ';
1743     if ($isData) {
1744       out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
1745     }
1746     out += ' ((exclusive' + ($lvl) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ') || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = exclusive' + ($lvl) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';';
1747   } else {
1748     var $exclusive = $schemaExcl === true,
1749       $opStr = $op;
1750     if (!$exclusive) $opStr += '=';
1751     var $opExpr = '\'' + $opStr + '\'';
1752     out += ' if ( ';
1753     if ($isData) {
1754       out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
1755     }
1756     out += ' ' + ($data) + ' ' + ($notOp);
1757     if ($exclusive) {
1758       out += '=';
1759     }
1760     out += ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') {';
1761   }
1762   var $errorKeyword = $keyword;
1763   var $$outStack = $$outStack || [];
1764   $$outStack.push(out);
1765   out = ''; /* istanbul ignore else */
1766   if (it.createErrors !== false) {
1767     out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } ';
1768     if (it.opts.messages !== false) {
1769       out += ' , message: \'should be ' + ($opStr) + ' ';
1770       if ($isData) {
1771         out += '\' + ' + ($schemaValue);
1772       } else {
1773         out += '' + ($schema) + '\'';
1774       }
1775     }
1776     if (it.opts.verbose) {
1777       out += ' , schema:  ';
1778       if ($isData) {
1779         out += 'validate.schema' + ($schemaPath);
1780       } else {
1781         out += '' + ($schema);
1782       }
1783       out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
1784     }
1785     out += ' } ';
1786   } else {
1787     out += ' {} ';
1788   }
1789   var __err = out;
1790   out = $$outStack.pop();
1791   if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
1792     if (it.async) {
1793       out += ' throw new ValidationError([' + (__err) + ']); ';
1794     } else {
1795       out += ' validate.errors = [' + (__err) + ']; return false; ';
1796     }
1797   } else {
1798     out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
1799   }
1800   out += ' } ';
1801   if ($breakOnError) {
1802     out += ' else { ';
1803   }
1804   return out;
1805 }
1806
1807 },{}],15:[function(require,module,exports){
1808 'use strict';
1809 module.exports = function generate__limitItems(it, $keyword) {
1810   var out = ' ';
1811   var $lvl = it.level;
1812   var $dataLvl = it.dataLevel;
1813   var $schema = it.schema[$keyword];
1814   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
1815   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
1816   var $breakOnError = !it.opts.allErrors;
1817   var $errorKeyword;
1818   var $data = 'data' + ($dataLvl || '');
1819   var $isData = it.opts.v5 && $schema && $schema.$data,
1820     $schemaValue;
1821   if ($isData) {
1822     out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
1823     $schemaValue = 'schema' + $lvl;
1824   } else {
1825     $schemaValue = $schema;
1826   }
1827   var $op = $keyword == 'maxItems' ? '>' : '<';
1828   out += 'if ( ';
1829   if ($isData) {
1830     out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
1831   }
1832   out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { ';
1833   var $errorKeyword = $keyword;
1834   var $$outStack = $$outStack || [];
1835   $$outStack.push(out);
1836   out = ''; /* istanbul ignore else */
1837   if (it.createErrors !== false) {
1838     out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
1839     if (it.opts.messages !== false) {
1840       out += ' , message: \'should NOT have ';
1841       if ($keyword == 'maxItems') {
1842         out += 'more';
1843       } else {
1844         out += 'less';
1845       }
1846       out += ' than ';
1847       if ($isData) {
1848         out += '\' + ' + ($schemaValue) + ' + \'';
1849       } else {
1850         out += '' + ($schema);
1851       }
1852       out += ' items\' ';
1853     }
1854     if (it.opts.verbose) {
1855       out += ' , schema:  ';
1856       if ($isData) {
1857         out += 'validate.schema' + ($schemaPath);
1858       } else {
1859         out += '' + ($schema);
1860       }
1861       out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
1862     }
1863     out += ' } ';
1864   } else {
1865     out += ' {} ';
1866   }
1867   var __err = out;
1868   out = $$outStack.pop();
1869   if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
1870     if (it.async) {
1871       out += ' throw new ValidationError([' + (__err) + ']); ';
1872     } else {
1873       out += ' validate.errors = [' + (__err) + ']; return false; ';
1874     }
1875   } else {
1876     out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
1877   }
1878   out += '} ';
1879   if ($breakOnError) {
1880     out += ' else { ';
1881   }
1882   return out;
1883 }
1884
1885 },{}],16:[function(require,module,exports){
1886 'use strict';
1887 module.exports = function generate__limitLength(it, $keyword) {
1888   var out = ' ';
1889   var $lvl = it.level;
1890   var $dataLvl = it.dataLevel;
1891   var $schema = it.schema[$keyword];
1892   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
1893   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
1894   var $breakOnError = !it.opts.allErrors;
1895   var $errorKeyword;
1896   var $data = 'data' + ($dataLvl || '');
1897   var $isData = it.opts.v5 && $schema && $schema.$data,
1898     $schemaValue;
1899   if ($isData) {
1900     out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
1901     $schemaValue = 'schema' + $lvl;
1902   } else {
1903     $schemaValue = $schema;
1904   }
1905   var $op = $keyword == 'maxLength' ? '>' : '<';
1906   out += 'if ( ';
1907   if ($isData) {
1908     out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
1909   }
1910   if (it.opts.unicode === false) {
1911     out += ' ' + ($data) + '.length ';
1912   } else {
1913     out += ' ucs2length(' + ($data) + ') ';
1914   }
1915   out += ' ' + ($op) + ' ' + ($schemaValue) + ') { ';
1916   var $errorKeyword = $keyword;
1917   var $$outStack = $$outStack || [];
1918   $$outStack.push(out);
1919   out = ''; /* istanbul ignore else */
1920   if (it.createErrors !== false) {
1921     out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
1922     if (it.opts.messages !== false) {
1923       out += ' , message: \'should NOT be ';
1924       if ($keyword == 'maxLength') {
1925         out += 'longer';
1926       } else {
1927         out += 'shorter';
1928       }
1929       out += ' than ';
1930       if ($isData) {
1931         out += '\' + ' + ($schemaValue) + ' + \'';
1932       } else {
1933         out += '' + ($schema);
1934       }
1935       out += ' characters\' ';
1936     }
1937     if (it.opts.verbose) {
1938       out += ' , schema:  ';
1939       if ($isData) {
1940         out += 'validate.schema' + ($schemaPath);
1941       } else {
1942         out += '' + ($schema);
1943       }
1944       out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
1945     }
1946     out += ' } ';
1947   } else {
1948     out += ' {} ';
1949   }
1950   var __err = out;
1951   out = $$outStack.pop();
1952   if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
1953     if (it.async) {
1954       out += ' throw new ValidationError([' + (__err) + ']); ';
1955     } else {
1956       out += ' validate.errors = [' + (__err) + ']; return false; ';
1957     }
1958   } else {
1959     out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
1960   }
1961   out += '} ';
1962   if ($breakOnError) {
1963     out += ' else { ';
1964   }
1965   return out;
1966 }
1967
1968 },{}],17:[function(require,module,exports){
1969 'use strict';
1970 module.exports = function generate__limitProperties(it, $keyword) {
1971   var out = ' ';
1972   var $lvl = it.level;
1973   var $dataLvl = it.dataLevel;
1974   var $schema = it.schema[$keyword];
1975   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
1976   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
1977   var $breakOnError = !it.opts.allErrors;
1978   var $errorKeyword;
1979   var $data = 'data' + ($dataLvl || '');
1980   var $isData = it.opts.v5 && $schema && $schema.$data,
1981     $schemaValue;
1982   if ($isData) {
1983     out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
1984     $schemaValue = 'schema' + $lvl;
1985   } else {
1986     $schemaValue = $schema;
1987   }
1988   var $op = $keyword == 'maxProperties' ? '>' : '<';
1989   out += 'if ( ';
1990   if ($isData) {
1991     out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
1992   }
1993   out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { ';
1994   var $errorKeyword = $keyword;
1995   var $$outStack = $$outStack || [];
1996   $$outStack.push(out);
1997   out = ''; /* istanbul ignore else */
1998   if (it.createErrors !== false) {
1999     out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
2000     if (it.opts.messages !== false) {
2001       out += ' , message: \'should NOT have ';
2002       if ($keyword == 'maxProperties') {
2003         out += 'more';
2004       } else {
2005         out += 'less';
2006       }
2007       out += ' than ';
2008       if ($isData) {
2009         out += '\' + ' + ($schemaValue) + ' + \'';
2010       } else {
2011         out += '' + ($schema);
2012       }
2013       out += ' properties\' ';
2014     }
2015     if (it.opts.verbose) {
2016       out += ' , schema:  ';
2017       if ($isData) {
2018         out += 'validate.schema' + ($schemaPath);
2019       } else {
2020         out += '' + ($schema);
2021       }
2022       out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
2023     }
2024     out += ' } ';
2025   } else {
2026     out += ' {} ';
2027   }
2028   var __err = out;
2029   out = $$outStack.pop();
2030   if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
2031     if (it.async) {
2032       out += ' throw new ValidationError([' + (__err) + ']); ';
2033     } else {
2034       out += ' validate.errors = [' + (__err) + ']; return false; ';
2035     }
2036   } else {
2037     out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
2038   }
2039   out += '} ';
2040   if ($breakOnError) {
2041     out += ' else { ';
2042   }
2043   return out;
2044 }
2045
2046 },{}],18:[function(require,module,exports){
2047 'use strict';
2048 module.exports = function generate_allOf(it, $keyword) {
2049   var out = ' ';
2050   var $schema = it.schema[$keyword];
2051   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
2052   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
2053   var $breakOnError = !it.opts.allErrors;
2054   var $it = it.util.copy(it);
2055   var $closingBraces = '';
2056   $it.level++;
2057   var $nextValid = 'valid' + $it.level;
2058   var $currentBaseId = $it.baseId,
2059     $allSchemasEmpty = true;
2060   var arr1 = $schema;
2061   if (arr1) {
2062     var $sch, $i = -1,
2063       l1 = arr1.length - 1;
2064     while ($i < l1) {
2065       $sch = arr1[$i += 1];
2066       if (it.util.schemaHasRules($sch, it.RULES.all)) {
2067         $allSchemasEmpty = false;
2068         $it.schema = $sch;
2069         $it.schemaPath = $schemaPath + '[' + $i + ']';
2070         $it.errSchemaPath = $errSchemaPath + '/' + $i;
2071         out += '  ' + (it.validate($it)) + ' ';
2072         $it.baseId = $currentBaseId;
2073         if ($breakOnError) {
2074           out += ' if (' + ($nextValid) + ') { ';
2075           $closingBraces += '}';
2076         }
2077       }
2078     }
2079   }
2080   if ($breakOnError) {
2081     if ($allSchemasEmpty) {
2082       out += ' if (true) { ';
2083     } else {
2084       out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
2085     }
2086   }
2087   out = it.util.cleanUpCode(out);
2088   return out;
2089 }
2090
2091 },{}],19:[function(require,module,exports){
2092 'use strict';
2093 module.exports = function generate_anyOf(it, $keyword) {
2094   var out = ' ';
2095   var $lvl = it.level;
2096   var $dataLvl = it.dataLevel;
2097   var $schema = it.schema[$keyword];
2098   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
2099   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
2100   var $breakOnError = !it.opts.allErrors;
2101   var $errorKeyword;
2102   var $data = 'data' + ($dataLvl || '');
2103   var $valid = 'valid' + $lvl;
2104   var $errs = 'errs__' + $lvl;
2105   var $it = it.util.copy(it);
2106   var $closingBraces = '';
2107   $it.level++;
2108   var $nextValid = 'valid' + $it.level;
2109   var $noEmptySchema = $schema.every(function($sch) {
2110     return it.util.schemaHasRules($sch, it.RULES.all);
2111   });
2112   if ($noEmptySchema) {
2113     var $currentBaseId = $it.baseId;
2114     out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false;  ';
2115     var $wasComposite = it.compositeRule;
2116     it.compositeRule = $it.compositeRule = true;
2117     var arr1 = $schema;
2118     if (arr1) {
2119       var $sch, $i = -1,
2120         l1 = arr1.length - 1;
2121       while ($i < l1) {
2122         $sch = arr1[$i += 1];
2123         $it.schema = $sch;
2124         $it.schemaPath = $schemaPath + '[' + $i + ']';
2125         $it.errSchemaPath = $errSchemaPath + '/' + $i;
2126         out += '  ' + (it.validate($it)) + ' ';
2127         $it.baseId = $currentBaseId;
2128         out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { ';
2129         $closingBraces += '}';
2130       }
2131     }
2132     it.compositeRule = $it.compositeRule = $wasComposite;
2133     out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') {  var err =   '; /* istanbul ignore else */
2134     if (it.createErrors !== false) {
2135       out += ' { keyword: \'' + ($errorKeyword || 'anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
2136       if (it.opts.messages !== false) {
2137         out += ' , message: \'should match some schema in anyOf\' ';
2138       }
2139       if (it.opts.verbose) {
2140         out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
2141       }
2142       out += ' } ';
2143     } else {
2144       out += ' {} ';
2145     }
2146     out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
2147     if (it.opts.allErrors) {
2148       out += ' } ';
2149     }
2150     out = it.util.cleanUpCode(out);
2151   } else {
2152     if ($breakOnError) {
2153       out += ' if (true) { ';
2154     }
2155   }
2156   return out;
2157 }
2158
2159 },{}],20:[function(require,module,exports){
2160 'use strict';
2161 module.exports = function generate_constant(it, $keyword) {
2162   var out = ' ';
2163   var $lvl = it.level;
2164   var $dataLvl = it.dataLevel;
2165   var $schema = it.schema[$keyword];
2166   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
2167   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
2168   var $breakOnError = !it.opts.allErrors;
2169   var $errorKeyword;
2170   var $data = 'data' + ($dataLvl || '');
2171   var $valid = 'valid' + $lvl;
2172   var $isData = it.opts.v5 && $schema && $schema.$data,
2173     $schemaValue;
2174   if ($isData) {
2175     out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
2176     $schemaValue = 'schema' + $lvl;
2177   } else {
2178     $schemaValue = $schema;
2179   }
2180   if (!$isData) {
2181     out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';';
2182   }
2183   out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') {   ';
2184   var $$outStack = $$outStack || [];
2185   $$outStack.push(out);
2186   out = ''; /* istanbul ignore else */
2187   if (it.createErrors !== false) {
2188     out += ' { keyword: \'' + ($errorKeyword || 'constant') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
2189     if (it.opts.messages !== false) {
2190       out += ' , message: \'should be equal to constant\' ';
2191     }
2192     if (it.opts.verbose) {
2193       out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
2194     }
2195     out += ' } ';
2196   } else {
2197     out += ' {} ';
2198   }
2199   var __err = out;
2200   out = $$outStack.pop();
2201   if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
2202     if (it.async) {
2203       out += ' throw new ValidationError([' + (__err) + ']); ';
2204     } else {
2205       out += ' validate.errors = [' + (__err) + ']; return false; ';
2206     }
2207   } else {
2208     out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
2209   }
2210   out += ' }';
2211   return out;
2212 }
2213
2214 },{}],21:[function(require,module,exports){
2215 'use strict';
2216 module.exports = function generate_custom(it, $keyword) {
2217   var out = ' ';
2218   var $lvl = it.level;
2219   var $dataLvl = it.dataLevel;
2220   var $schema = it.schema[$keyword];
2221   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
2222   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
2223   var $breakOnError = !it.opts.allErrors;
2224   var $errorKeyword;
2225   var $data = 'data' + ($dataLvl || '');
2226   var $valid = 'valid' + $lvl;
2227   var $errs = 'errs__' + $lvl;
2228   var $isData = it.opts.v5 && $schema && $schema.$data,
2229     $schemaValue;
2230   if ($isData) {
2231     out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
2232     $schemaValue = 'schema' + $lvl;
2233   } else {
2234     $schemaValue = $schema;
2235   }
2236   var $rule = this,
2237     $definition = 'definition' + $lvl,
2238     $rDef = $rule.definition,
2239     $validate = $rDef.validate,
2240     $compile, $inline, $macro, $ruleValidate, $validateCode;
2241   if ($isData && $rDef.$data) {
2242     $validateCode = 'keywordValidate' + $lvl;
2243     var $validateSchema = $rDef.validateSchema;
2244     out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;';
2245   } else {
2246     $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
2247     $schemaValue = 'validate.schema' + $schemaPath;
2248     $validateCode = $ruleValidate.code;
2249     $compile = $rDef.compile;
2250     $inline = $rDef.inline;
2251     $macro = $rDef.macro;
2252   }
2253   var $ruleErrs = $validateCode + '.errors',
2254     $i = 'i' + $lvl,
2255     $ruleErr = 'ruleErr' + $lvl,
2256     $asyncKeyword = $rDef.async;
2257   if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema');
2258   if (!($inline || $macro)) {
2259     out += '' + ($ruleErrs) + ' = null;';
2260   }
2261   out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
2262   if ($validateSchema) {
2263     out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') {';
2264   }
2265   if ($inline) {
2266     if ($rDef.statements) {
2267       out += ' ' + ($ruleValidate.validate) + ' ';
2268     } else {
2269       out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; ';
2270     }
2271   } else if ($macro) {
2272     var $it = it.util.copy(it);
2273     $it.level++;
2274     var $nextValid = 'valid' + $it.level;
2275     $it.schema = $ruleValidate.validate;
2276     $it.schemaPath = '';
2277     var $wasComposite = it.compositeRule;
2278     it.compositeRule = $it.compositeRule = true;
2279     var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
2280     it.compositeRule = $it.compositeRule = $wasComposite;
2281     out += ' ' + ($code);
2282   } else {
2283     var $$outStack = $$outStack || [];
2284     $$outStack.push(out);
2285     out = '';
2286     out += '  ' + ($validateCode) + '.call( ';
2287     if (it.opts.passContext) {
2288       out += 'this';
2289     } else {
2290       out += 'self';
2291     }
2292     if ($compile || $rDef.schema === false) {
2293       out += ' , ' + ($data) + ' ';
2294     } else {
2295       out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' ';
2296     }
2297     out += ' , (dataPath || \'\')';
2298     if (it.errorPath != '""') {
2299       out += ' + ' + (it.errorPath);
2300     }
2301     var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
2302       $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
2303     out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData )  ';
2304     var def_callRuleValidate = out;
2305     out = $$outStack.pop();
2306     if ($rDef.errors === false) {
2307       out += ' ' + ($valid) + ' = ';
2308       if ($asyncKeyword) {
2309         out += '' + (it.yieldAwait);
2310       }
2311       out += '' + (def_callRuleValidate) + '; ';
2312     } else {
2313       if ($asyncKeyword) {
2314         $ruleErrs = 'customErrors' + $lvl;
2315         out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = ' + (it.yieldAwait) + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } ';
2316       } else {
2317         out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; ';
2318       }
2319     }
2320   }
2321   if ($rDef.modifying) {
2322     out += ' ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];';
2323   }
2324   if ($validateSchema) {
2325     out += ' }';
2326   }
2327   if ($rDef.valid) {
2328     if ($breakOnError) {
2329       out += ' if (true) { ';
2330     }
2331   } else {
2332     out += ' if ( ';
2333     if ($rDef.valid === undefined) {
2334       out += ' !';
2335       if ($macro) {
2336         out += '' + ($nextValid);
2337       } else {
2338         out += '' + ($valid);
2339       }
2340     } else {
2341       out += ' ' + (!$rDef.valid) + ' ';
2342     }
2343     out += ') { ';
2344     $errorKeyword = $rule.keyword;
2345     var $$outStack = $$outStack || [];
2346     $$outStack.push(out);
2347     out = '';
2348     var $$outStack = $$outStack || [];
2349     $$outStack.push(out);
2350     out = ''; /* istanbul ignore else */
2351     if (it.createErrors !== false) {
2352       out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
2353       if (it.opts.messages !== false) {
2354         out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
2355       }
2356       if (it.opts.verbose) {
2357         out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
2358       }
2359       out += ' } ';
2360     } else {
2361       out += ' {} ';
2362     }
2363     var __err = out;
2364     out = $$outStack.pop();
2365     if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
2366       if (it.async) {
2367         out += ' throw new ValidationError([' + (__err) + ']); ';
2368       } else {
2369         out += ' validate.errors = [' + (__err) + ']; return false; ';
2370       }
2371     } else {
2372       out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
2373     }
2374     var def_customError = out;
2375     out = $$outStack.pop();
2376     if ($inline) {
2377       if ($rDef.errors) {
2378         if ($rDef.errors != 'full') {
2379           out += '  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
2380           if (it.opts.verbose) {
2381             out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
2382           }
2383           out += ' } ';
2384         }
2385       } else {
2386         if ($rDef.errors === false) {
2387           out += ' ' + (def_customError) + ' ';
2388         } else {
2389           out += ' if (' + ($errs) + ' == errors) { ' + (def_customError) + ' } else {  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
2390           if (it.opts.verbose) {
2391             out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
2392           }
2393           out += ' } } ';
2394         }
2395       }
2396     } else if ($macro) {
2397       out += '   var err =   '; /* istanbul ignore else */
2398       if (it.createErrors !== false) {
2399         out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
2400         if (it.opts.messages !== false) {
2401           out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
2402         }
2403         if (it.opts.verbose) {
2404           out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
2405         }
2406         out += ' } ';
2407       } else {
2408         out += ' {} ';
2409       }
2410       out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
2411       if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
2412         if (it.async) {
2413           out += ' throw new ValidationError(vErrors); ';
2414         } else {
2415           out += ' validate.errors = vErrors; return false; ';
2416         }
2417       }
2418     } else {
2419       if ($rDef.errors === false) {
2420         out += ' ' + (def_customError) + ' ';
2421       } else {
2422         out += ' if (Array.isArray(' + ($ruleErrs) + ')) { if (vErrors === null) vErrors = ' + ($ruleErrs) + '; else vErrors = vErrors.concat(' + ($ruleErrs) + '); errors = vErrors.length;  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + ';  ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '";  ';
2423         if (it.opts.verbose) {
2424           out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
2425         }
2426         out += ' } } else { ' + (def_customError) + ' } ';
2427       }
2428     }
2429     out += ' } ';
2430     if ($breakOnError) {
2431       out += ' else { ';
2432     }
2433   }
2434   return out;
2435 }
2436
2437 },{}],22:[function(require,module,exports){
2438 'use strict';
2439 module.exports = function generate_dependencies(it, $keyword) {
2440   var out = ' ';
2441   var $lvl = it.level;
2442   var $dataLvl = it.dataLevel;
2443   var $schema = it.schema[$keyword];
2444   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
2445   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
2446   var $breakOnError = !it.opts.allErrors;
2447   var $errorKeyword;
2448   var $data = 'data' + ($dataLvl || '');
2449   var $errs = 'errs__' + $lvl;
2450   var $it = it.util.copy(it);
2451   var $closingBraces = '';
2452   $it.level++;
2453   var $nextValid = 'valid' + $it.level;
2454   var $schemaDeps = {},
2455     $propertyDeps = {};
2456   for ($property in $schema) {
2457     var $sch = $schema[$property];
2458     var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
2459     $deps[$property] = $sch;
2460   }
2461   out += 'var ' + ($errs) + ' = errors;';
2462   var $currentErrorPath = it.errorPath;
2463   out += 'var missing' + ($lvl) + ';';
2464   for (var $property in $propertyDeps) {
2465     $deps = $propertyDeps[$property];
2466     out += ' if (' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
2467     if ($breakOnError) {
2468       out += ' && ( ';
2469       var arr1 = $deps;
2470       if (arr1) {
2471         var _$property, $i = -1,
2472           l1 = arr1.length - 1;
2473         while ($i < l1) {
2474           _$property = arr1[$i += 1];
2475           if ($i) {
2476             out += ' || ';
2477           }
2478           var $prop = it.util.getProperty(_$property);
2479           out += ' ( ' + ($data) + ($prop) + ' === undefined && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? _$property : $prop)) + ') ) ';
2480         }
2481       }
2482       out += ')) {  ';
2483       var $propertyPath = 'missing' + $lvl,
2484         $missingProperty = '\' + ' + $propertyPath + ' + \'';
2485       if (it.opts._errorDataPathProperty) {
2486         it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
2487       }
2488       var $$outStack = $$outStack || [];
2489       $$outStack.push(out);
2490       out = ''; /* istanbul ignore else */
2491       if (it.createErrors !== false) {
2492         out += ' { keyword: \'' + ($errorKeyword || 'dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
2493         if (it.opts.messages !== false) {
2494           out += ' , message: \'should have ';
2495           if ($deps.length == 1) {
2496             out += 'property ' + (it.util.escapeQuotes($deps[0]));
2497           } else {
2498             out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
2499           }
2500           out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
2501         }
2502         if (it.opts.verbose) {
2503           out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
2504         }
2505         out += ' } ';
2506       } else {
2507         out += ' {} ';
2508       }
2509       var __err = out;
2510       out = $$outStack.pop();
2511       if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
2512         if (it.async) {
2513           out += ' throw new ValidationError([' + (__err) + ']); ';
2514         } else {
2515           out += ' validate.errors = [' + (__err) + ']; return false; ';
2516         }
2517       } else {
2518         out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
2519       }
2520     } else {
2521       out += ' ) { ';
2522       var arr2 = $deps;
2523       if (arr2) {
2524         var $reqProperty, i2 = -1,
2525           l2 = arr2.length - 1;
2526         while (i2 < l2) {
2527           $reqProperty = arr2[i2 += 1];
2528           var $prop = it.util.getProperty($reqProperty),
2529             $missingProperty = it.util.escapeQuotes($reqProperty);
2530           if (it.opts._errorDataPathProperty) {
2531             it.errorPath = it.util.getPath($currentErrorPath, $reqProperty, it.opts.jsonPointers);
2532           }
2533           out += ' if (' + ($data) + ($prop) + ' === undefined) {  var err =   '; /* istanbul ignore else */
2534           if (it.createErrors !== false) {
2535             out += ' { keyword: \'' + ($errorKeyword || 'dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
2536             if (it.opts.messages !== false) {
2537               out += ' , message: \'should have ';
2538               if ($deps.length == 1) {
2539                 out += 'property ' + (it.util.escapeQuotes($deps[0]));
2540               } else {
2541                 out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
2542               }
2543               out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
2544             }
2545             if (it.opts.verbose) {
2546               out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
2547             }
2548             out += ' } ';
2549           } else {
2550             out += ' {} ';
2551           }
2552           out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
2553         }
2554       }
2555     }
2556     out += ' }   ';
2557     if ($breakOnError) {
2558       $closingBraces += '}';
2559       out += ' else { ';
2560     }
2561   }
2562   it.errorPath = $currentErrorPath;
2563   var $currentBaseId = $it.baseId;
2564   for (var $property in $schemaDeps) {
2565     var $sch = $schemaDeps[$property];
2566     if (it.util.schemaHasRules($sch, it.RULES.all)) {
2567       out += ' ' + ($nextValid) + ' = true; if (' + ($data) + (it.util.getProperty($property)) + ' !== undefined) { ';
2568       $it.schema = $sch;
2569       $it.schemaPath = $schemaPath + it.util.getProperty($property);
2570       $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
2571       out += '  ' + (it.validate($it)) + ' ';
2572       $it.baseId = $currentBaseId;
2573       out += ' }  ';
2574       if ($breakOnError) {
2575         out += ' if (' + ($nextValid) + ') { ';
2576         $closingBraces += '}';
2577       }
2578     }
2579   }
2580   if ($breakOnError) {
2581     out += '   ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
2582   }
2583   out = it.util.cleanUpCode(out);
2584   return out;
2585 }
2586
2587 },{}],23:[function(require,module,exports){
2588 'use strict';
2589 module.exports = function generate_enum(it, $keyword) {
2590   var out = ' ';
2591   var $lvl = it.level;
2592   var $dataLvl = it.dataLevel;
2593   var $schema = it.schema[$keyword];
2594   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
2595   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
2596   var $breakOnError = !it.opts.allErrors;
2597   var $errorKeyword;
2598   var $data = 'data' + ($dataLvl || '');
2599   var $valid = 'valid' + $lvl;
2600   var $isData = it.opts.v5 && $schema && $schema.$data,
2601     $schemaValue;
2602   if ($isData) {
2603     out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
2604     $schemaValue = 'schema' + $lvl;
2605   } else {
2606     $schemaValue = $schema;
2607   }
2608   var $i = 'i' + $lvl,
2609     $vSchema = 'schema' + $lvl;
2610   if (!$isData) {
2611     out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';';
2612   }
2613   out += 'var ' + ($valid) + ';';
2614   if ($isData) {
2615     out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
2616   }
2617   out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }';
2618   if ($isData) {
2619     out += '  }  ';
2620   }
2621   out += ' if (!' + ($valid) + ') {   ';
2622   var $$outStack = $$outStack || [];
2623   $$outStack.push(out);
2624   out = ''; /* istanbul ignore else */
2625   if (it.createErrors !== false) {
2626     out += ' { keyword: \'' + ($errorKeyword || 'enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } ';
2627     if (it.opts.messages !== false) {
2628       out += ' , message: \'should be equal to one of the allowed values\' ';
2629     }
2630     if (it.opts.verbose) {
2631       out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
2632     }
2633     out += ' } ';
2634   } else {
2635     out += ' {} ';
2636   }
2637   var __err = out;
2638   out = $$outStack.pop();
2639   if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
2640     if (it.async) {
2641       out += ' throw new ValidationError([' + (__err) + ']); ';
2642     } else {
2643       out += ' validate.errors = [' + (__err) + ']; return false; ';
2644     }
2645   } else {
2646     out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
2647   }
2648   out += ' }';
2649   if ($breakOnError) {
2650     out += ' else { ';
2651   }
2652   return out;
2653 }
2654
2655 },{}],24:[function(require,module,exports){
2656 'use strict';
2657 module.exports = function generate_format(it, $keyword) {
2658   var out = ' ';
2659   var $lvl = it.level;
2660   var $dataLvl = it.dataLevel;
2661   var $schema = it.schema[$keyword];
2662   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
2663   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
2664   var $breakOnError = !it.opts.allErrors;
2665   var $errorKeyword;
2666   var $data = 'data' + ($dataLvl || '');
2667   if (it.opts.format === false) {
2668     if ($breakOnError) {
2669       out += ' if (true) { ';
2670     }
2671     return out;
2672   }
2673   var $isData = it.opts.v5 && $schema && $schema.$data,
2674     $schemaValue;
2675   if ($isData) {
2676     out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
2677     $schemaValue = 'schema' + $lvl;
2678   } else {
2679     $schemaValue = $schema;
2680   }
2681   var $unknownFormats = it.opts.unknownFormats,
2682     $allowUnknown = Array.isArray($unknownFormats);
2683   if ($isData) {
2684     var $format = 'format' + $lvl;
2685     out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var isObject' + ($lvl) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; if (isObject' + ($lvl) + ') { ';
2686     if (it.async) {
2687       out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; ';
2688     }
2689     out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if (  ';
2690     if ($isData) {
2691       out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
2692     }
2693     out += ' (';
2694     if ($unknownFormats === true || $allowUnknown) {
2695       out += ' (' + ($schemaValue) + ' && !' + ($format) + ' ';
2696       if ($allowUnknown) {
2697         out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 ';
2698       }
2699       out += ') || ';
2700     }
2701     out += ' (' + ($format) + ' && !(typeof ' + ($format) + ' == \'function\' ? ';
2702     if (it.async) {
2703       out += ' (async' + ($lvl) + ' ? ' + (it.yieldAwait) + ' ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
2704     } else {
2705       out += ' ' + ($format) + '(' + ($data) + ') ';
2706     }
2707     out += ' : ' + ($format) + '.test(' + ($data) + '))))) {';
2708   } else {
2709     var $format = it.formats[$schema];
2710     if (!$format) {
2711       if ($unknownFormats === true || ($allowUnknown && $unknownFormats.indexOf($schema) == -1)) {
2712         throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
2713       } else {
2714         if (!$allowUnknown) {
2715           console.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
2716           if ($unknownFormats !== 'ignore') console.warn('In the next major version it will throw exception. See option unknownFormats for more information');
2717         }
2718         if ($breakOnError) {
2719           out += ' if (true) { ';
2720         }
2721         return out;
2722       }
2723     }
2724     var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;
2725     if ($isObject) {
2726       var $async = $format.async === true;
2727       $format = $format.validate;
2728     }
2729     if ($async) {
2730       if (!it.async) throw new Error('async format in sync schema');
2731       var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
2732       out += ' if (!(' + (it.yieldAwait) + ' ' + ($formatRef) + '(' + ($data) + '))) { ';
2733     } else {
2734       out += ' if (! ';
2735       var $formatRef = 'formats' + it.util.getProperty($schema);
2736       if ($isObject) $formatRef += '.validate';
2737       if (typeof $format == 'function') {
2738         out += ' ' + ($formatRef) + '(' + ($data) + ') ';
2739       } else {
2740         out += ' ' + ($formatRef) + '.test(' + ($data) + ') ';
2741       }
2742       out += ') { ';
2743     }
2744   }
2745   var $$outStack = $$outStack || [];
2746   $$outStack.push(out);
2747   out = ''; /* istanbul ignore else */
2748   if (it.createErrors !== false) {
2749     out += ' { keyword: \'' + ($errorKeyword || 'format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format:  ';
2750     if ($isData) {
2751       out += '' + ($schemaValue);
2752     } else {
2753       out += '' + (it.util.toQuotedString($schema));
2754     }
2755     out += '  } ';
2756     if (it.opts.messages !== false) {
2757       out += ' , message: \'should match format "';
2758       if ($isData) {
2759         out += '\' + ' + ($schemaValue) + ' + \'';
2760       } else {
2761         out += '' + (it.util.escapeQuotes($schema));
2762       }
2763       out += '"\' ';
2764     }
2765     if (it.opts.verbose) {
2766       out += ' , schema:  ';
2767       if ($isData) {
2768         out += 'validate.schema' + ($schemaPath);
2769       } else {
2770         out += '' + (it.util.toQuotedString($schema));
2771       }
2772       out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
2773     }
2774     out += ' } ';
2775   } else {
2776     out += ' {} ';
2777   }
2778   var __err = out;
2779   out = $$outStack.pop();
2780   if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
2781     if (it.async) {
2782       out += ' throw new ValidationError([' + (__err) + ']); ';
2783     } else {
2784       out += ' validate.errors = [' + (__err) + ']; return false; ';
2785     }
2786   } else {
2787     out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
2788   }
2789   out += ' } ';
2790   if ($breakOnError) {
2791     out += ' else { ';
2792   }
2793   return out;
2794 }
2795
2796 },{}],25:[function(require,module,exports){
2797 'use strict';
2798 module.exports = function generate_items(it, $keyword) {
2799   var out = ' ';
2800   var $lvl = it.level;
2801   var $dataLvl = it.dataLevel;
2802   var $schema = it.schema[$keyword];
2803   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
2804   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
2805   var $breakOnError = !it.opts.allErrors;
2806   var $errorKeyword;
2807   var $data = 'data' + ($dataLvl || '');
2808   var $valid = 'valid' + $lvl;
2809   var $errs = 'errs__' + $lvl;
2810   var $it = it.util.copy(it);
2811   var $closingBraces = '';
2812   $it.level++;
2813   var $nextValid = 'valid' + $it.level;
2814   var $idx = 'i' + $lvl,
2815     $dataNxt = $it.dataLevel = it.dataLevel + 1,
2816     $nextData = 'data' + $dataNxt,
2817     $currentBaseId = it.baseId;
2818   out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
2819   if (Array.isArray($schema)) {
2820     var $additionalItems = it.schema.additionalItems;
2821     if ($additionalItems === false) {
2822       out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; ';
2823       var $currErrSchemaPath = $errSchemaPath;
2824       $errSchemaPath = it.errSchemaPath + '/additionalItems';
2825       out += '  if (!' + ($valid) + ') {   ';
2826       var $$outStack = $$outStack || [];
2827       $$outStack.push(out);
2828       out = ''; /* istanbul ignore else */
2829       if (it.createErrors !== false) {
2830         out += ' { keyword: \'' + ($errorKeyword || 'additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } ';
2831         if (it.opts.messages !== false) {
2832           out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' ';
2833         }
2834         if (it.opts.verbose) {
2835           out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
2836         }
2837         out += ' } ';
2838       } else {
2839         out += ' {} ';
2840       }
2841       var __err = out;
2842       out = $$outStack.pop();
2843       if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
2844         if (it.async) {
2845           out += ' throw new ValidationError([' + (__err) + ']); ';
2846         } else {
2847           out += ' validate.errors = [' + (__err) + ']; return false; ';
2848         }
2849       } else {
2850         out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
2851       }
2852       out += ' } ';
2853       $errSchemaPath = $currErrSchemaPath;
2854       if ($breakOnError) {
2855         $closingBraces += '}';
2856         out += ' else { ';
2857       }
2858     }
2859     var arr1 = $schema;
2860     if (arr1) {
2861       var $sch, $i = -1,
2862         l1 = arr1.length - 1;
2863       while ($i < l1) {
2864         $sch = arr1[$i += 1];
2865         if (it.util.schemaHasRules($sch, it.RULES.all)) {
2866           out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { ';
2867           var $passData = $data + '[' + $i + ']';
2868           $it.schema = $sch;
2869           $it.schemaPath = $schemaPath + '[' + $i + ']';
2870           $it.errSchemaPath = $errSchemaPath + '/' + $i;
2871           $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
2872           $it.dataPathArr[$dataNxt] = $i;
2873           var $code = it.validate($it);
2874           $it.baseId = $currentBaseId;
2875           if (it.util.varOccurences($code, $nextData) < 2) {
2876             out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
2877           } else {
2878             out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
2879           }
2880           out += ' }  ';
2881           if ($breakOnError) {
2882             out += ' if (' + ($nextValid) + ') { ';
2883             $closingBraces += '}';
2884           }
2885         }
2886       }
2887     }
2888     if (typeof $additionalItems == 'object' && it.util.schemaHasRules($additionalItems, it.RULES.all)) {
2889       $it.schema = $additionalItems;
2890       $it.schemaPath = it.schemaPath + '.additionalItems';
2891       $it.errSchemaPath = it.errSchemaPath + '/additionalItems';
2892       out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') {  for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
2893       $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
2894       var $passData = $data + '[' + $idx + ']';
2895       $it.dataPathArr[$dataNxt] = $idx;
2896       var $code = it.validate($it);
2897       $it.baseId = $currentBaseId;
2898       if (it.util.varOccurences($code, $nextData) < 2) {
2899         out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
2900       } else {
2901         out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
2902       }
2903       if ($breakOnError) {
2904         out += ' if (!' + ($nextValid) + ') break; ';
2905       }
2906       out += ' } }  ';
2907       if ($breakOnError) {
2908         out += ' if (' + ($nextValid) + ') { ';
2909         $closingBraces += '}';
2910       }
2911     }
2912   } else if (it.util.schemaHasRules($schema, it.RULES.all)) {
2913     $it.schema = $schema;
2914     $it.schemaPath = $schemaPath;
2915     $it.errSchemaPath = $errSchemaPath;
2916     out += '  for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
2917     $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
2918     var $passData = $data + '[' + $idx + ']';
2919     $it.dataPathArr[$dataNxt] = $idx;
2920     var $code = it.validate($it);
2921     $it.baseId = $currentBaseId;
2922     if (it.util.varOccurences($code, $nextData) < 2) {
2923       out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
2924     } else {
2925       out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
2926     }
2927     if ($breakOnError) {
2928       out += ' if (!' + ($nextValid) + ') break; ';
2929     }
2930     out += ' }  ';
2931     if ($breakOnError) {
2932       out += ' if (' + ($nextValid) + ') { ';
2933       $closingBraces += '}';
2934     }
2935   }
2936   if ($breakOnError) {
2937     out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
2938   }
2939   out = it.util.cleanUpCode(out);
2940   return out;
2941 }
2942
2943 },{}],26:[function(require,module,exports){
2944 'use strict';
2945 module.exports = function generate_multipleOf(it, $keyword) {
2946   var out = ' ';
2947   var $lvl = it.level;
2948   var $dataLvl = it.dataLevel;
2949   var $schema = it.schema[$keyword];
2950   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
2951   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
2952   var $breakOnError = !it.opts.allErrors;
2953   var $errorKeyword;
2954   var $data = 'data' + ($dataLvl || '');
2955   var $isData = it.opts.v5 && $schema && $schema.$data,
2956     $schemaValue;
2957   if ($isData) {
2958     out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
2959     $schemaValue = 'schema' + $lvl;
2960   } else {
2961     $schemaValue = $schema;
2962   }
2963   out += 'var division' + ($lvl) + ';if (';
2964   if ($isData) {
2965     out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || ';
2966   }
2967   out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', ';
2968   if (it.opts.multipleOfPrecision) {
2969     out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' ';
2970   } else {
2971     out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') ';
2972   }
2973   out += ' ) ';
2974   if ($isData) {
2975     out += '  )  ';
2976   }
2977   out += ' ) {   ';
2978   var $$outStack = $$outStack || [];
2979   $$outStack.push(out);
2980   out = ''; /* istanbul ignore else */
2981   if (it.createErrors !== false) {
2982     out += ' { keyword: \'' + ($errorKeyword || 'multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } ';
2983     if (it.opts.messages !== false) {
2984       out += ' , message: \'should be multiple of ';
2985       if ($isData) {
2986         out += '\' + ' + ($schemaValue);
2987       } else {
2988         out += '' + ($schema) + '\'';
2989       }
2990     }
2991     if (it.opts.verbose) {
2992       out += ' , schema:  ';
2993       if ($isData) {
2994         out += 'validate.schema' + ($schemaPath);
2995       } else {
2996         out += '' + ($schema);
2997       }
2998       out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
2999     }
3000     out += ' } ';
3001   } else {
3002     out += ' {} ';
3003   }
3004   var __err = out;
3005   out = $$outStack.pop();
3006   if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
3007     if (it.async) {
3008       out += ' throw new ValidationError([' + (__err) + ']); ';
3009     } else {
3010       out += ' validate.errors = [' + (__err) + ']; return false; ';
3011     }
3012   } else {
3013     out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3014   }
3015   out += '} ';
3016   if ($breakOnError) {
3017     out += ' else { ';
3018   }
3019   return out;
3020 }
3021
3022 },{}],27:[function(require,module,exports){
3023 'use strict';
3024 module.exports = function generate_not(it, $keyword) {
3025   var out = ' ';
3026   var $lvl = it.level;
3027   var $dataLvl = it.dataLevel;
3028   var $schema = it.schema[$keyword];
3029   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3030   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3031   var $breakOnError = !it.opts.allErrors;
3032   var $errorKeyword;
3033   var $data = 'data' + ($dataLvl || '');
3034   var $errs = 'errs__' + $lvl;
3035   var $it = it.util.copy(it);
3036   $it.level++;
3037   var $nextValid = 'valid' + $it.level;
3038   if (it.util.schemaHasRules($schema, it.RULES.all)) {
3039     $it.schema = $schema;
3040     $it.schemaPath = $schemaPath;
3041     $it.errSchemaPath = $errSchemaPath;
3042     out += ' var ' + ($errs) + ' = errors;  ';
3043     var $wasComposite = it.compositeRule;
3044     it.compositeRule = $it.compositeRule = true;
3045     $it.createErrors = false;
3046     var $allErrorsOption;
3047     if ($it.opts.allErrors) {
3048       $allErrorsOption = $it.opts.allErrors;
3049       $it.opts.allErrors = false;
3050     }
3051     out += ' ' + (it.validate($it)) + ' ';
3052     $it.createErrors = true;
3053     if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
3054     it.compositeRule = $it.compositeRule = $wasComposite;
3055     out += ' if (' + ($nextValid) + ') {   ';
3056     var $$outStack = $$outStack || [];
3057     $$outStack.push(out);
3058     out = ''; /* istanbul ignore else */
3059     if (it.createErrors !== false) {
3060       out += ' { keyword: \'' + ($errorKeyword || 'not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
3061       if (it.opts.messages !== false) {
3062         out += ' , message: \'should NOT be valid\' ';
3063       }
3064       if (it.opts.verbose) {
3065         out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3066       }
3067       out += ' } ';
3068     } else {
3069       out += ' {} ';
3070     }
3071     var __err = out;
3072     out = $$outStack.pop();
3073     if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
3074       if (it.async) {
3075         out += ' throw new ValidationError([' + (__err) + ']); ';
3076       } else {
3077         out += ' validate.errors = [' + (__err) + ']; return false; ';
3078       }
3079     } else {
3080       out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3081     }
3082     out += ' } else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
3083     if (it.opts.allErrors) {
3084       out += ' } ';
3085     }
3086   } else {
3087     out += '  var err =   '; /* istanbul ignore else */
3088     if (it.createErrors !== false) {
3089       out += ' { keyword: \'' + ($errorKeyword || 'not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
3090       if (it.opts.messages !== false) {
3091         out += ' , message: \'should NOT be valid\' ';
3092       }
3093       if (it.opts.verbose) {
3094         out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3095       }
3096       out += ' } ';
3097     } else {
3098       out += ' {} ';
3099     }
3100     out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3101     if ($breakOnError) {
3102       out += ' if (false) { ';
3103     }
3104   }
3105   return out;
3106 }
3107
3108 },{}],28:[function(require,module,exports){
3109 'use strict';
3110 module.exports = function generate_oneOf(it, $keyword) {
3111   var out = ' ';
3112   var $lvl = it.level;
3113   var $dataLvl = it.dataLevel;
3114   var $schema = it.schema[$keyword];
3115   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3116   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3117   var $breakOnError = !it.opts.allErrors;
3118   var $errorKeyword;
3119   var $data = 'data' + ($dataLvl || '');
3120   var $valid = 'valid' + $lvl;
3121   var $errs = 'errs__' + $lvl;
3122   var $it = it.util.copy(it);
3123   var $closingBraces = '';
3124   $it.level++;
3125   var $nextValid = 'valid' + $it.level;
3126   out += 'var ' + ($errs) + ' = errors;var prevValid' + ($lvl) + ' = false;var ' + ($valid) + ' = false;';
3127   var $currentBaseId = $it.baseId;
3128   var $wasComposite = it.compositeRule;
3129   it.compositeRule = $it.compositeRule = true;
3130   var arr1 = $schema;
3131   if (arr1) {
3132     var $sch, $i = -1,
3133       l1 = arr1.length - 1;
3134     while ($i < l1) {
3135       $sch = arr1[$i += 1];
3136       if (it.util.schemaHasRules($sch, it.RULES.all)) {
3137         $it.schema = $sch;
3138         $it.schemaPath = $schemaPath + '[' + $i + ']';
3139         $it.errSchemaPath = $errSchemaPath + '/' + $i;
3140         out += '  ' + (it.validate($it)) + ' ';
3141         $it.baseId = $currentBaseId;
3142       } else {
3143         out += ' var ' + ($nextValid) + ' = true; ';
3144       }
3145       if ($i) {
3146         out += ' if (' + ($nextValid) + ' && prevValid' + ($lvl) + ') ' + ($valid) + ' = false; else { ';
3147         $closingBraces += '}';
3148       }
3149       out += ' if (' + ($nextValid) + ') ' + ($valid) + ' = prevValid' + ($lvl) + ' = true;';
3150     }
3151   }
3152   it.compositeRule = $it.compositeRule = $wasComposite;
3153   out += '' + ($closingBraces) + 'if (!' + ($valid) + ') {   ';
3154   var $$outStack = $$outStack || [];
3155   $$outStack.push(out);
3156   out = ''; /* istanbul ignore else */
3157   if (it.createErrors !== false) {
3158     out += ' { keyword: \'' + ($errorKeyword || 'oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
3159     if (it.opts.messages !== false) {
3160       out += ' , message: \'should match exactly one schema in oneOf\' ';
3161     }
3162     if (it.opts.verbose) {
3163       out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3164     }
3165     out += ' } ';
3166   } else {
3167     out += ' {} ';
3168   }
3169   var __err = out;
3170   out = $$outStack.pop();
3171   if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
3172     if (it.async) {
3173       out += ' throw new ValidationError([' + (__err) + ']); ';
3174     } else {
3175       out += ' validate.errors = [' + (__err) + ']; return false; ';
3176     }
3177   } else {
3178     out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3179   }
3180   out += '} else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }';
3181   if (it.opts.allErrors) {
3182     out += ' } ';
3183   }
3184   return out;
3185 }
3186
3187 },{}],29:[function(require,module,exports){
3188 'use strict';
3189 module.exports = function generate_pattern(it, $keyword) {
3190   var out = ' ';
3191   var $lvl = it.level;
3192   var $dataLvl = it.dataLevel;
3193   var $schema = it.schema[$keyword];
3194   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3195   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3196   var $breakOnError = !it.opts.allErrors;
3197   var $errorKeyword;
3198   var $data = 'data' + ($dataLvl || '');
3199   var $isData = it.opts.v5 && $schema && $schema.$data,
3200     $schemaValue;
3201   if ($isData) {
3202     out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
3203     $schemaValue = 'schema' + $lvl;
3204   } else {
3205     $schemaValue = $schema;
3206   }
3207   var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema);
3208   out += 'if ( ';
3209   if ($isData) {
3210     out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
3211   }
3212   out += ' !' + ($regexp) + '.test(' + ($data) + ') ) {   ';
3213   var $$outStack = $$outStack || [];
3214   $$outStack.push(out);
3215   out = ''; /* istanbul ignore else */
3216   if (it.createErrors !== false) {
3217     out += ' { keyword: \'' + ($errorKeyword || 'pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern:  ';
3218     if ($isData) {
3219       out += '' + ($schemaValue);
3220     } else {
3221       out += '' + (it.util.toQuotedString($schema));
3222     }
3223     out += '  } ';
3224     if (it.opts.messages !== false) {
3225       out += ' , message: \'should match pattern "';
3226       if ($isData) {
3227         out += '\' + ' + ($schemaValue) + ' + \'';
3228       } else {
3229         out += '' + (it.util.escapeQuotes($schema));
3230       }
3231       out += '"\' ';
3232     }
3233     if (it.opts.verbose) {
3234       out += ' , schema:  ';
3235       if ($isData) {
3236         out += 'validate.schema' + ($schemaPath);
3237       } else {
3238         out += '' + (it.util.toQuotedString($schema));
3239       }
3240       out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3241     }
3242     out += ' } ';
3243   } else {
3244     out += ' {} ';
3245   }
3246   var __err = out;
3247   out = $$outStack.pop();
3248   if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
3249     if (it.async) {
3250       out += ' throw new ValidationError([' + (__err) + ']); ';
3251     } else {
3252       out += ' validate.errors = [' + (__err) + ']; return false; ';
3253     }
3254   } else {
3255     out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3256   }
3257   out += '} ';
3258   if ($breakOnError) {
3259     out += ' else { ';
3260   }
3261   return out;
3262 }
3263
3264 },{}],30:[function(require,module,exports){
3265 'use strict';
3266 module.exports = function generate_patternRequired(it, $keyword) {
3267   var out = ' ';
3268   var $lvl = it.level;
3269   var $dataLvl = it.dataLevel;
3270   var $schema = it.schema[$keyword];
3271   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3272   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3273   var $breakOnError = !it.opts.allErrors;
3274   var $errorKeyword;
3275   var $data = 'data' + ($dataLvl || '');
3276   var $valid = 'valid' + $lvl;
3277   var $key = 'key' + $lvl,
3278     $matched = 'patternMatched' + $lvl,
3279     $closingBraces = '',
3280     $ownProperties = it.opts.ownProperties;
3281   out += 'var ' + ($valid) + ' = true;';
3282   var arr1 = $schema;
3283   if (arr1) {
3284     var $pProperty, i1 = -1,
3285       l1 = arr1.length - 1;
3286     while (i1 < l1) {
3287       $pProperty = arr1[i1 += 1];
3288       out += ' var ' + ($matched) + ' = false; for (var ' + ($key) + ' in ' + ($data) + ') {  ';
3289       if ($ownProperties) {
3290         out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; ';
3291       }
3292       out += ' ' + ($matched) + ' = ' + (it.usePattern($pProperty)) + '.test(' + ($key) + '); if (' + ($matched) + ') break; } ';
3293       var $missingPattern = it.util.escapeQuotes($pProperty);
3294       out += ' if (!' + ($matched) + ') { ' + ($valid) + ' = false;  var err =   '; /* istanbul ignore else */
3295       if (it.createErrors !== false) {
3296         out += ' { keyword: \'' + ($errorKeyword || 'patternRequired') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingPattern: \'' + ($missingPattern) + '\' } ';
3297         if (it.opts.messages !== false) {
3298           out += ' , message: \'should have property matching pattern \\\'' + ($missingPattern) + '\\\'\' ';
3299         }
3300         if (it.opts.verbose) {
3301           out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3302         }
3303         out += ' } ';
3304       } else {
3305         out += ' {} ';
3306       }
3307       out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; }   ';
3308       if ($breakOnError) {
3309         $closingBraces += '}';
3310         out += ' else { ';
3311       }
3312     }
3313   }
3314   out += '' + ($closingBraces);
3315   return out;
3316 }
3317
3318 },{}],31:[function(require,module,exports){
3319 'use strict';
3320 module.exports = function generate_properties(it, $keyword) {
3321   var out = ' ';
3322   var $lvl = it.level;
3323   var $dataLvl = it.dataLevel;
3324   var $schema = it.schema[$keyword];
3325   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3326   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3327   var $breakOnError = !it.opts.allErrors;
3328   var $errorKeyword;
3329   var $data = 'data' + ($dataLvl || '');
3330   var $valid = 'valid' + $lvl;
3331   var $errs = 'errs__' + $lvl;
3332   var $it = it.util.copy(it);
3333   var $closingBraces = '';
3334   $it.level++;
3335   var $nextValid = 'valid' + $it.level;
3336   var $key = 'key' + $lvl,
3337     $dataNxt = $it.dataLevel = it.dataLevel + 1,
3338     $nextData = 'data' + $dataNxt;
3339   var $schemaKeys = Object.keys($schema || {}),
3340     $pProperties = it.schema.patternProperties || {},
3341     $pPropertyKeys = Object.keys($pProperties),
3342     $aProperties = it.schema.additionalProperties,
3343     $someProperties = $schemaKeys.length || $pPropertyKeys.length,
3344     $noAdditional = $aProperties === false,
3345     $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length,
3346     $removeAdditional = it.opts.removeAdditional,
3347     $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional,
3348     $ownProperties = it.opts.ownProperties,
3349     $currentBaseId = it.baseId;
3350   var $required = it.schema.required;
3351   if ($required && !(it.opts.v5 && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required);
3352   if (it.opts.v5) {
3353     var $pgProperties = it.schema.patternGroups || {},
3354       $pgPropertyKeys = Object.keys($pgProperties);
3355   }
3356   out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
3357   if ($checkAdditional) {
3358     out += ' for (var ' + ($key) + ' in ' + ($data) + ') {  ';
3359     if ($ownProperties) {
3360       out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; ';
3361     }
3362     if ($someProperties) {
3363       out += ' var isAdditional' + ($lvl) + ' = !(false ';
3364       if ($schemaKeys.length) {
3365         if ($schemaKeys.length > 5) {
3366           out += ' || validate.schema' + ($schemaPath) + '[' + ($key) + '] ';
3367         } else {
3368           var arr1 = $schemaKeys;
3369           if (arr1) {
3370             var $propertyKey, i1 = -1,
3371               l1 = arr1.length - 1;
3372             while (i1 < l1) {
3373               $propertyKey = arr1[i1 += 1];
3374               out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' ';
3375             }
3376           }
3377         }
3378       }
3379       if ($pPropertyKeys.length) {
3380         var arr2 = $pPropertyKeys;
3381         if (arr2) {
3382           var $pProperty, $i = -1,
3383             l2 = arr2.length - 1;
3384           while ($i < l2) {
3385             $pProperty = arr2[$i += 1];
3386             out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') ';
3387           }
3388         }
3389       }
3390       if (it.opts.v5 && $pgPropertyKeys && $pgPropertyKeys.length) {
3391         var arr3 = $pgPropertyKeys;
3392         if (arr3) {
3393           var $pgProperty, $i = -1,
3394             l3 = arr3.length - 1;
3395           while ($i < l3) {
3396             $pgProperty = arr3[$i += 1];
3397             out += ' || ' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ') ';
3398           }
3399         }
3400       }
3401       out += ' ); if (isAdditional' + ($lvl) + ') { ';
3402     }
3403     if ($removeAdditional == 'all') {
3404       out += ' delete ' + ($data) + '[' + ($key) + ']; ';
3405     } else {
3406       var $currentErrorPath = it.errorPath;
3407       var $additionalProperty = '\' + ' + $key + ' + \'';
3408       if (it.opts._errorDataPathProperty) {
3409         it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
3410       }
3411       if ($noAdditional) {
3412         if ($removeAdditional) {
3413           out += ' delete ' + ($data) + '[' + ($key) + ']; ';
3414         } else {
3415           out += ' ' + ($nextValid) + ' = false; ';
3416           var $currErrSchemaPath = $errSchemaPath;
3417           $errSchemaPath = it.errSchemaPath + '/additionalProperties';
3418           var $$outStack = $$outStack || [];
3419           $$outStack.push(out);
3420           out = ''; /* istanbul ignore else */
3421           if (it.createErrors !== false) {
3422             out += ' { keyword: \'' + ($errorKeyword || 'additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } ';
3423             if (it.opts.messages !== false) {
3424               out += ' , message: \'should NOT have additional properties\' ';
3425             }
3426             if (it.opts.verbose) {
3427               out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3428             }
3429             out += ' } ';
3430           } else {
3431             out += ' {} ';
3432           }
3433           var __err = out;
3434           out = $$outStack.pop();
3435           if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
3436             if (it.async) {
3437               out += ' throw new ValidationError([' + (__err) + ']); ';
3438             } else {
3439               out += ' validate.errors = [' + (__err) + ']; return false; ';
3440             }
3441           } else {
3442             out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3443           }
3444           $errSchemaPath = $currErrSchemaPath;
3445           if ($breakOnError) {
3446             out += ' break; ';
3447           }
3448         }
3449       } else if ($additionalIsSchema) {
3450         if ($removeAdditional == 'failing') {
3451           out += ' var ' + ($errs) + ' = errors;  ';
3452           var $wasComposite = it.compositeRule;
3453           it.compositeRule = $it.compositeRule = true;
3454           $it.schema = $aProperties;
3455           $it.schemaPath = it.schemaPath + '.additionalProperties';
3456           $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
3457           $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
3458           var $passData = $data + '[' + $key + ']';
3459           $it.dataPathArr[$dataNxt] = $key;
3460           var $code = it.validate($it);
3461           $it.baseId = $currentBaseId;
3462           if (it.util.varOccurences($code, $nextData) < 2) {
3463             out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
3464           } else {
3465             out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
3466           }
3467           out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; }  ';
3468           it.compositeRule = $it.compositeRule = $wasComposite;
3469         } else {
3470           $it.schema = $aProperties;
3471           $it.schemaPath = it.schemaPath + '.additionalProperties';
3472           $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
3473           $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
3474           var $passData = $data + '[' + $key + ']';
3475           $it.dataPathArr[$dataNxt] = $key;
3476           var $code = it.validate($it);
3477           $it.baseId = $currentBaseId;
3478           if (it.util.varOccurences($code, $nextData) < 2) {
3479             out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
3480           } else {
3481             out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
3482           }
3483           if ($breakOnError) {
3484             out += ' if (!' + ($nextValid) + ') break; ';
3485           }
3486         }
3487       }
3488       it.errorPath = $currentErrorPath;
3489     }
3490     if ($someProperties) {
3491       out += ' } ';
3492     }
3493     out += ' }  ';
3494     if ($breakOnError) {
3495       out += ' if (' + ($nextValid) + ') { ';
3496       $closingBraces += '}';
3497     }
3498   }
3499   var $useDefaults = it.opts.useDefaults && !it.compositeRule;
3500   if ($schemaKeys.length) {
3501     var arr4 = $schemaKeys;
3502     if (arr4) {
3503       var $propertyKey, i4 = -1,
3504         l4 = arr4.length - 1;
3505       while (i4 < l4) {
3506         $propertyKey = arr4[i4 += 1];
3507         var $sch = $schema[$propertyKey];
3508         if (it.util.schemaHasRules($sch, it.RULES.all)) {
3509           var $prop = it.util.getProperty($propertyKey),
3510             $passData = $data + $prop,
3511             $hasDefault = $useDefaults && $sch.default !== undefined;
3512           $it.schema = $sch;
3513           $it.schemaPath = $schemaPath + $prop;
3514           $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
3515           $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
3516           $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
3517           var $code = it.validate($it);
3518           $it.baseId = $currentBaseId;
3519           if (it.util.varOccurences($code, $nextData) < 2) {
3520             $code = it.util.varReplace($code, $nextData, $passData);
3521             var $useData = $passData;
3522           } else {
3523             var $useData = $nextData;
3524             out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ';
3525           }
3526           if ($hasDefault) {
3527             out += ' ' + ($code) + ' ';
3528           } else {
3529             if ($requiredHash && $requiredHash[$propertyKey]) {
3530               out += ' if (' + ($useData) + ' === undefined) { ' + ($nextValid) + ' = false; ';
3531               var $currentErrorPath = it.errorPath,
3532                 $currErrSchemaPath = $errSchemaPath,
3533                 $missingProperty = it.util.escapeQuotes($propertyKey);
3534               if (it.opts._errorDataPathProperty) {
3535                 it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
3536               }
3537               $errSchemaPath = it.errSchemaPath + '/required';
3538               var $$outStack = $$outStack || [];
3539               $$outStack.push(out);
3540               out = ''; /* istanbul ignore else */
3541               if (it.createErrors !== false) {
3542                 out += ' { keyword: \'' + ($errorKeyword || 'required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
3543                 if (it.opts.messages !== false) {
3544                   out += ' , message: \'';
3545                   if (it.opts._errorDataPathProperty) {
3546                     out += 'is a required property';
3547                   } else {
3548                     out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
3549                   }
3550                   out += '\' ';
3551                 }
3552                 if (it.opts.verbose) {
3553                   out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3554                 }
3555                 out += ' } ';
3556               } else {
3557                 out += ' {} ';
3558               }
3559               var __err = out;
3560               out = $$outStack.pop();
3561               if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
3562                 if (it.async) {
3563                   out += ' throw new ValidationError([' + (__err) + ']); ';
3564                 } else {
3565                   out += ' validate.errors = [' + (__err) + ']; return false; ';
3566                 }
3567               } else {
3568                 out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3569               }
3570               $errSchemaPath = $currErrSchemaPath;
3571               it.errorPath = $currentErrorPath;
3572               out += ' } else { ';
3573             } else {
3574               if ($breakOnError) {
3575                 out += ' if (' + ($useData) + ' === undefined) { ' + ($nextValid) + ' = true; } else { ';
3576               } else {
3577                 out += ' if (' + ($useData) + ' !== undefined) { ';
3578               }
3579             }
3580             out += ' ' + ($code) + ' } ';
3581           }
3582         }
3583         if ($breakOnError) {
3584           out += ' if (' + ($nextValid) + ') { ';
3585           $closingBraces += '}';
3586         }
3587       }
3588     }
3589   }
3590   var arr5 = $pPropertyKeys;
3591   if (arr5) {
3592     var $pProperty, i5 = -1,
3593       l5 = arr5.length - 1;
3594     while (i5 < l5) {
3595       $pProperty = arr5[i5 += 1];
3596       var $sch = $pProperties[$pProperty];
3597       if (it.util.schemaHasRules($sch, it.RULES.all)) {
3598         $it.schema = $sch;
3599         $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
3600         $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty);
3601         out += ' for (var ' + ($key) + ' in ' + ($data) + ') {  ';
3602         if ($ownProperties) {
3603           out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; ';
3604         }
3605         out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { ';
3606         $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
3607         var $passData = $data + '[' + $key + ']';
3608         $it.dataPathArr[$dataNxt] = $key;
3609         var $code = it.validate($it);
3610         $it.baseId = $currentBaseId;
3611         if (it.util.varOccurences($code, $nextData) < 2) {
3612           out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
3613         } else {
3614           out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
3615         }
3616         if ($breakOnError) {
3617           out += ' if (!' + ($nextValid) + ') break; ';
3618         }
3619         out += ' } ';
3620         if ($breakOnError) {
3621           out += ' else ' + ($nextValid) + ' = true; ';
3622         }
3623         out += ' }  ';
3624         if ($breakOnError) {
3625           out += ' if (' + ($nextValid) + ') { ';
3626           $closingBraces += '}';
3627         }
3628       }
3629     }
3630   }
3631   if (it.opts.v5) {
3632     var arr6 = $pgPropertyKeys;
3633     if (arr6) {
3634       var $pgProperty, i6 = -1,
3635         l6 = arr6.length - 1;
3636       while (i6 < l6) {
3637         $pgProperty = arr6[i6 += 1];
3638         var $pgSchema = $pgProperties[$pgProperty],
3639           $sch = $pgSchema.schema;
3640         if (it.util.schemaHasRules($sch, it.RULES.all)) {
3641           $it.schema = $sch;
3642           $it.schemaPath = it.schemaPath + '.patternGroups' + it.util.getProperty($pgProperty) + '.schema';
3643           $it.errSchemaPath = it.errSchemaPath + '/patternGroups/' + it.util.escapeFragment($pgProperty) + '/schema';
3644           out += ' var pgPropCount' + ($lvl) + ' = 0; for (var ' + ($key) + ' in ' + ($data) + ') {  ';
3645           if ($ownProperties) {
3646             out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; ';
3647           }
3648           out += ' if (' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ')) { pgPropCount' + ($lvl) + '++; ';
3649           $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
3650           var $passData = $data + '[' + $key + ']';
3651           $it.dataPathArr[$dataNxt] = $key;
3652           var $code = it.validate($it);
3653           $it.baseId = $currentBaseId;
3654           if (it.util.varOccurences($code, $nextData) < 2) {
3655             out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
3656           } else {
3657             out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
3658           }
3659           if ($breakOnError) {
3660             out += ' if (!' + ($nextValid) + ') break; ';
3661           }
3662           out += ' } ';
3663           if ($breakOnError) {
3664             out += ' else ' + ($nextValid) + ' = true; ';
3665           }
3666           out += ' }  ';
3667           if ($breakOnError) {
3668             out += ' if (' + ($nextValid) + ') { ';
3669             $closingBraces += '}';
3670           }
3671           var $pgMin = $pgSchema.minimum,
3672             $pgMax = $pgSchema.maximum;
3673           if ($pgMin !== undefined || $pgMax !== undefined) {
3674             out += ' var ' + ($valid) + ' = true; ';
3675             var $currErrSchemaPath = $errSchemaPath;
3676             if ($pgMin !== undefined) {
3677               var $limit = $pgMin,
3678                 $reason = 'minimum',
3679                 $moreOrLess = 'less';
3680               out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' >= ' + ($pgMin) + '; ';
3681               $errSchemaPath = it.errSchemaPath + '/patternGroups/minimum';
3682               out += '  if (!' + ($valid) + ') {   ';
3683               var $$outStack = $$outStack || [];
3684               $$outStack.push(out);
3685               out = ''; /* istanbul ignore else */
3686               if (it.createErrors !== false) {
3687                 out += ' { keyword: \'' + ($errorKeyword || 'patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } ';
3688                 if (it.opts.messages !== false) {
3689                   out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' ';
3690                 }
3691                 if (it.opts.verbose) {
3692                   out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3693                 }
3694                 out += ' } ';
3695               } else {
3696                 out += ' {} ';
3697               }
3698               var __err = out;
3699               out = $$outStack.pop();
3700               if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
3701                 if (it.async) {
3702                   out += ' throw new ValidationError([' + (__err) + ']); ';
3703                 } else {
3704                   out += ' validate.errors = [' + (__err) + ']; return false; ';
3705                 }
3706               } else {
3707                 out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3708               }
3709               out += ' } ';
3710               if ($pgMax !== undefined) {
3711                 out += ' else ';
3712               }
3713             }
3714             if ($pgMax !== undefined) {
3715               var $limit = $pgMax,
3716                 $reason = 'maximum',
3717                 $moreOrLess = 'more';
3718               out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' <= ' + ($pgMax) + '; ';
3719               $errSchemaPath = it.errSchemaPath + '/patternGroups/maximum';
3720               out += '  if (!' + ($valid) + ') {   ';
3721               var $$outStack = $$outStack || [];
3722               $$outStack.push(out);
3723               out = ''; /* istanbul ignore else */
3724               if (it.createErrors !== false) {
3725                 out += ' { keyword: \'' + ($errorKeyword || 'patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } ';
3726                 if (it.opts.messages !== false) {
3727                   out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' ';
3728                 }
3729                 if (it.opts.verbose) {
3730                   out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3731                 }
3732                 out += ' } ';
3733               } else {
3734                 out += ' {} ';
3735               }
3736               var __err = out;
3737               out = $$outStack.pop();
3738               if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
3739                 if (it.async) {
3740                   out += ' throw new ValidationError([' + (__err) + ']); ';
3741                 } else {
3742                   out += ' validate.errors = [' + (__err) + ']; return false; ';
3743                 }
3744               } else {
3745                 out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3746               }
3747               out += ' } ';
3748             }
3749             $errSchemaPath = $currErrSchemaPath;
3750             if ($breakOnError) {
3751               out += ' if (' + ($valid) + ') { ';
3752               $closingBraces += '}';
3753             }
3754           }
3755         }
3756       }
3757     }
3758   }
3759   if ($breakOnError) {
3760     out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
3761   }
3762   out = it.util.cleanUpCode(out);
3763   return out;
3764 }
3765
3766 },{}],32:[function(require,module,exports){
3767 'use strict';
3768 module.exports = function generate_ref(it, $keyword) {
3769   var out = ' ';
3770   var $lvl = it.level;
3771   var $dataLvl = it.dataLevel;
3772   var $schema = it.schema[$keyword];
3773   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3774   var $breakOnError = !it.opts.allErrors;
3775   var $errorKeyword;
3776   var $data = 'data' + ($dataLvl || '');
3777   var $valid = 'valid' + $lvl;
3778   var $async, $refCode;
3779   if ($schema == '#' || $schema == '#/') {
3780     if (it.isRoot) {
3781       $async = it.async;
3782       $refCode = 'validate';
3783     } else {
3784       $async = it.root.schema.$async === true;
3785       $refCode = 'root.refVal[0]';
3786     }
3787   } else {
3788     var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot);
3789     if ($refVal === undefined) {
3790       var $message = 'can\'t resolve reference ' + $schema + ' from id ' + it.baseId;
3791       if (it.opts.missingRefs == 'fail') {
3792         console.log($message);
3793         var $$outStack = $$outStack || [];
3794         $$outStack.push(out);
3795         out = ''; /* istanbul ignore else */
3796         if (it.createErrors !== false) {
3797           out += ' { keyword: \'' + ($errorKeyword || '$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } ';
3798           if (it.opts.messages !== false) {
3799             out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' ';
3800           }
3801           if (it.opts.verbose) {
3802             out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3803           }
3804           out += ' } ';
3805         } else {
3806           out += ' {} ';
3807         }
3808         var __err = out;
3809         out = $$outStack.pop();
3810         if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
3811           if (it.async) {
3812             out += ' throw new ValidationError([' + (__err) + ']); ';
3813           } else {
3814             out += ' validate.errors = [' + (__err) + ']; return false; ';
3815           }
3816         } else {
3817           out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3818         }
3819         if ($breakOnError) {
3820           out += ' if (false) { ';
3821         }
3822       } else if (it.opts.missingRefs == 'ignore') {
3823         console.log($message);
3824         if ($breakOnError) {
3825           out += ' if (true) { ';
3826         }
3827       } else {
3828         var $error = new Error($message);
3829         $error.missingRef = it.resolve.url(it.baseId, $schema);
3830         $error.missingSchema = it.resolve.normalizeId(it.resolve.fullPath($error.missingRef));
3831         throw $error;
3832       }
3833     } else if ($refVal.inline) {
3834       var $it = it.util.copy(it);
3835       $it.level++;
3836       var $nextValid = 'valid' + $it.level;
3837       $it.schema = $refVal.schema;
3838       $it.schemaPath = '';
3839       $it.errSchemaPath = $schema;
3840       var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
3841       out += ' ' + ($code) + ' ';
3842       if ($breakOnError) {
3843         out += ' if (' + ($nextValid) + ') { ';
3844       }
3845     } else {
3846       $async = $refVal.$async === true;
3847       $refCode = $refVal.code;
3848     }
3849   }
3850   if ($refCode) {
3851     var $$outStack = $$outStack || [];
3852     $$outStack.push(out);
3853     out = '';
3854     if (it.opts.passContext) {
3855       out += ' ' + ($refCode) + '.call(this, ';
3856     } else {
3857       out += ' ' + ($refCode) + '( ';
3858     }
3859     out += ' ' + ($data) + ', (dataPath || \'\')';
3860     if (it.errorPath != '""') {
3861       out += ' + ' + (it.errorPath);
3862     }
3863     var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
3864       $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
3865     out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData)  ';
3866     var __callValidate = out;
3867     out = $$outStack.pop();
3868     if ($async) {
3869       if (!it.async) throw new Error('async schema referenced by sync schema');
3870       out += ' try { ';
3871       if ($breakOnError) {
3872         out += 'var ' + ($valid) + ' =';
3873       }
3874       out += ' ' + (it.yieldAwait) + ' ' + (__callValidate) + '; } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; } ';
3875       if ($breakOnError) {
3876         out += ' if (' + ($valid) + ') { ';
3877       }
3878     } else {
3879       out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } ';
3880       if ($breakOnError) {
3881         out += ' else { ';
3882       }
3883     }
3884   }
3885   return out;
3886 }
3887
3888 },{}],33:[function(require,module,exports){
3889 'use strict';
3890 module.exports = function generate_required(it, $keyword) {
3891   var out = ' ';
3892   var $lvl = it.level;
3893   var $dataLvl = it.dataLevel;
3894   var $schema = it.schema[$keyword];
3895   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3896   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3897   var $breakOnError = !it.opts.allErrors;
3898   var $errorKeyword;
3899   var $data = 'data' + ($dataLvl || '');
3900   var $valid = 'valid' + $lvl;
3901   var $isData = it.opts.v5 && $schema && $schema.$data,
3902     $schemaValue;
3903   if ($isData) {
3904     out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
3905     $schemaValue = 'schema' + $lvl;
3906   } else {
3907     $schemaValue = $schema;
3908   }
3909   var $vSchema = 'schema' + $lvl;
3910   if (!$isData) {
3911     if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
3912       var $required = [];
3913       var arr1 = $schema;
3914       if (arr1) {
3915         var $property, i1 = -1,
3916           l1 = arr1.length - 1;
3917         while (i1 < l1) {
3918           $property = arr1[i1 += 1];
3919           var $propertySch = it.schema.properties[$property];
3920           if (!($propertySch && it.util.schemaHasRules($propertySch, it.RULES.all))) {
3921             $required[$required.length] = $property;
3922           }
3923         }
3924       }
3925     } else {
3926       var $required = $schema;
3927     }
3928   }
3929   if ($isData || $required.length) {
3930     var $currentErrorPath = it.errorPath,
3931       $loopRequired = $isData || $required.length >= it.opts.loopRequired;
3932     if ($breakOnError) {
3933       out += ' var missing' + ($lvl) + '; ';
3934       if ($loopRequired) {
3935         if (!$isData) {
3936           out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
3937         }
3938         var $i = 'i' + $lvl,
3939           $propertyPath = 'schema' + $lvl + '[' + $i + ']',
3940           $missingProperty = '\' + ' + $propertyPath + ' + \'';
3941         if (it.opts._errorDataPathProperty) {
3942           it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
3943         }
3944         out += ' var ' + ($valid) + ' = true; ';
3945         if ($isData) {
3946           out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
3947         }
3948         out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined; if (!' + ($valid) + ') break; } ';
3949         if ($isData) {
3950           out += '  }  ';
3951         }
3952         out += '  if (!' + ($valid) + ') {   ';
3953         var $$outStack = $$outStack || [];
3954         $$outStack.push(out);
3955         out = ''; /* istanbul ignore else */
3956         if (it.createErrors !== false) {
3957           out += ' { keyword: \'' + ($errorKeyword || 'required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
3958           if (it.opts.messages !== false) {
3959             out += ' , message: \'';
3960             if (it.opts._errorDataPathProperty) {
3961               out += 'is a required property';
3962             } else {
3963               out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
3964             }
3965             out += '\' ';
3966           }
3967           if (it.opts.verbose) {
3968             out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3969           }
3970           out += ' } ';
3971         } else {
3972           out += ' {} ';
3973         }
3974         var __err = out;
3975         out = $$outStack.pop();
3976         if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
3977           if (it.async) {
3978             out += ' throw new ValidationError([' + (__err) + ']); ';
3979           } else {
3980             out += ' validate.errors = [' + (__err) + ']; return false; ';
3981           }
3982         } else {
3983           out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3984         }
3985         out += ' } else { ';
3986       } else {
3987         out += ' if ( ';
3988         var arr2 = $required;
3989         if (arr2) {
3990           var _$property, $i = -1,
3991             l2 = arr2.length - 1;
3992           while ($i < l2) {
3993             _$property = arr2[$i += 1];
3994             if ($i) {
3995               out += ' || ';
3996             }
3997             var $prop = it.util.getProperty(_$property);
3998             out += ' ( ' + ($data) + ($prop) + ' === undefined && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? _$property : $prop)) + ') ) ';
3999           }
4000         }
4001         out += ') {  ';
4002         var $propertyPath = 'missing' + $lvl,
4003           $missingProperty = '\' + ' + $propertyPath + ' + \'';
4004         if (it.opts._errorDataPathProperty) {
4005           it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
4006         }
4007         var $$outStack = $$outStack || [];
4008         $$outStack.push(out);
4009         out = ''; /* istanbul ignore else */
4010         if (it.createErrors !== false) {
4011           out += ' { keyword: \'' + ($errorKeyword || 'required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
4012           if (it.opts.messages !== false) {
4013             out += ' , message: \'';
4014             if (it.opts._errorDataPathProperty) {
4015               out += 'is a required property';
4016             } else {
4017               out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
4018             }
4019             out += '\' ';
4020           }
4021           if (it.opts.verbose) {
4022             out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4023           }
4024           out += ' } ';
4025         } else {
4026           out += ' {} ';
4027         }
4028         var __err = out;
4029         out = $$outStack.pop();
4030         if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
4031           if (it.async) {
4032             out += ' throw new ValidationError([' + (__err) + ']); ';
4033           } else {
4034             out += ' validate.errors = [' + (__err) + ']; return false; ';
4035           }
4036         } else {
4037           out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4038         }
4039         out += ' } else { ';
4040       }
4041     } else {
4042       if ($loopRequired) {
4043         if (!$isData) {
4044           out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
4045         }
4046         var $i = 'i' + $lvl,
4047           $propertyPath = 'schema' + $lvl + '[' + $i + ']',
4048           $missingProperty = '\' + ' + $propertyPath + ' + \'';
4049         if (it.opts._errorDataPathProperty) {
4050           it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
4051         }
4052         if ($isData) {
4053           out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) {  var err =   '; /* istanbul ignore else */
4054           if (it.createErrors !== false) {
4055             out += ' { keyword: \'' + ($errorKeyword || 'required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
4056             if (it.opts.messages !== false) {
4057               out += ' , message: \'';
4058               if (it.opts._errorDataPathProperty) {
4059                 out += 'is a required property';
4060               } else {
4061                 out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
4062               }
4063               out += '\' ';
4064             }
4065             if (it.opts.verbose) {
4066               out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4067             }
4068             out += ' } ';
4069           } else {
4070             out += ' {} ';
4071           }
4072           out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { ';
4073         }
4074         out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined) {  var err =   '; /* istanbul ignore else */
4075         if (it.createErrors !== false) {
4076           out += ' { keyword: \'' + ($errorKeyword || 'required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
4077           if (it.opts.messages !== false) {
4078             out += ' , message: \'';
4079             if (it.opts._errorDataPathProperty) {
4080               out += 'is a required property';
4081             } else {
4082               out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
4083             }
4084             out += '\' ';
4085           }
4086           if (it.opts.verbose) {
4087             out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4088           }
4089           out += ' } ';
4090         } else {
4091           out += ' {} ';
4092         }
4093         out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ';
4094         if ($isData) {
4095           out += '  }  ';
4096         }
4097       } else {
4098         var arr3 = $required;
4099         if (arr3) {
4100           var $reqProperty, i3 = -1,
4101             l3 = arr3.length - 1;
4102           while (i3 < l3) {
4103             $reqProperty = arr3[i3 += 1];
4104             var $prop = it.util.getProperty($reqProperty),
4105               $missingProperty = it.util.escapeQuotes($reqProperty);
4106             if (it.opts._errorDataPathProperty) {
4107               it.errorPath = it.util.getPath($currentErrorPath, $reqProperty, it.opts.jsonPointers);
4108             }
4109             out += ' if (' + ($data) + ($prop) + ' === undefined) {  var err =   '; /* istanbul ignore else */
4110             if (it.createErrors !== false) {
4111               out += ' { keyword: \'' + ($errorKeyword || 'required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
4112               if (it.opts.messages !== false) {
4113                 out += ' , message: \'';
4114                 if (it.opts._errorDataPathProperty) {
4115                   out += 'is a required property';
4116                 } else {
4117                   out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
4118                 }
4119                 out += '\' ';
4120               }
4121               if (it.opts.verbose) {
4122                 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4123               }
4124               out += ' } ';
4125             } else {
4126               out += ' {} ';
4127             }
4128             out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
4129           }
4130         }
4131       }
4132     }
4133     it.errorPath = $currentErrorPath;
4134   } else if ($breakOnError) {
4135     out += ' if (true) {';
4136   }
4137   return out;
4138 }
4139
4140 },{}],34:[function(require,module,exports){
4141 'use strict';
4142 module.exports = function generate_switch(it, $keyword) {
4143   var out = ' ';
4144   var $lvl = it.level;
4145   var $dataLvl = it.dataLevel;
4146   var $schema = it.schema[$keyword];
4147   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4148   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4149   var $breakOnError = !it.opts.allErrors;
4150   var $errorKeyword;
4151   var $data = 'data' + ($dataLvl || '');
4152   var $valid = 'valid' + $lvl;
4153   var $errs = 'errs__' + $lvl;
4154   var $it = it.util.copy(it);
4155   var $closingBraces = '';
4156   $it.level++;
4157   var $nextValid = 'valid' + $it.level;
4158   var $ifPassed = 'ifPassed' + it.level,
4159     $currentBaseId = $it.baseId,
4160     $shouldContinue;
4161   out += 'var ' + ($ifPassed) + ';';
4162   var arr1 = $schema;
4163   if (arr1) {
4164     var $sch, $caseIndex = -1,
4165       l1 = arr1.length - 1;
4166     while ($caseIndex < l1) {
4167       $sch = arr1[$caseIndex += 1];
4168       if ($caseIndex && !$shouldContinue) {
4169         out += ' if (!' + ($ifPassed) + ') { ';
4170         $closingBraces += '}';
4171       }
4172       if ($sch.if && it.util.schemaHasRules($sch.if, it.RULES.all)) {
4173         out += ' var ' + ($errs) + ' = errors;   ';
4174         var $wasComposite = it.compositeRule;
4175         it.compositeRule = $it.compositeRule = true;
4176         $it.createErrors = false;
4177         $it.schema = $sch.if;
4178         $it.schemaPath = $schemaPath + '[' + $caseIndex + '].if';
4179         $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/if';
4180         out += '  ' + (it.validate($it)) + ' ';
4181         $it.baseId = $currentBaseId;
4182         $it.createErrors = true;
4183         it.compositeRule = $it.compositeRule = $wasComposite;
4184         out += ' ' + ($ifPassed) + ' = ' + ($nextValid) + '; if (' + ($ifPassed) + ') {  ';
4185         if (typeof $sch.then == 'boolean') {
4186           if ($sch.then === false) {
4187             var $$outStack = $$outStack || [];
4188             $$outStack.push(out);
4189             out = ''; /* istanbul ignore else */
4190             if (it.createErrors !== false) {
4191               out += ' { keyword: \'' + ($errorKeyword || 'switch') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { caseIndex: ' + ($caseIndex) + ' } ';
4192               if (it.opts.messages !== false) {
4193                 out += ' , message: \'should pass "switch" keyword validation\' ';
4194               }
4195               if (it.opts.verbose) {
4196                 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4197               }
4198               out += ' } ';
4199             } else {
4200               out += ' {} ';
4201             }
4202             var __err = out;
4203             out = $$outStack.pop();
4204             if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
4205               if (it.async) {
4206                 out += ' throw new ValidationError([' + (__err) + ']); ';
4207               } else {
4208                 out += ' validate.errors = [' + (__err) + ']; return false; ';
4209               }
4210             } else {
4211               out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4212             }
4213           }
4214           out += ' var ' + ($nextValid) + ' = ' + ($sch.then) + '; ';
4215         } else {
4216           $it.schema = $sch.then;
4217           $it.schemaPath = $schemaPath + '[' + $caseIndex + '].then';
4218           $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/then';
4219           out += '  ' + (it.validate($it)) + ' ';
4220           $it.baseId = $currentBaseId;
4221         }
4222         out += '  } else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } } ';
4223       } else {
4224         out += ' ' + ($ifPassed) + ' = true;  ';
4225         if (typeof $sch.then == 'boolean') {
4226           if ($sch.then === false) {
4227             var $$outStack = $$outStack || [];
4228             $$outStack.push(out);
4229             out = ''; /* istanbul ignore else */
4230             if (it.createErrors !== false) {
4231               out += ' { keyword: \'' + ($errorKeyword || 'switch') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { caseIndex: ' + ($caseIndex) + ' } ';
4232               if (it.opts.messages !== false) {
4233                 out += ' , message: \'should pass "switch" keyword validation\' ';
4234               }
4235               if (it.opts.verbose) {
4236                 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4237               }
4238               out += ' } ';
4239             } else {
4240               out += ' {} ';
4241             }
4242             var __err = out;
4243             out = $$outStack.pop();
4244             if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
4245               if (it.async) {
4246                 out += ' throw new ValidationError([' + (__err) + ']); ';
4247               } else {
4248                 out += ' validate.errors = [' + (__err) + ']; return false; ';
4249               }
4250             } else {
4251               out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4252             }
4253           }
4254           out += ' var ' + ($nextValid) + ' = ' + ($sch.then) + '; ';
4255         } else {
4256           $it.schema = $sch.then;
4257           $it.schemaPath = $schemaPath + '[' + $caseIndex + '].then';
4258           $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/then';
4259           out += '  ' + (it.validate($it)) + ' ';
4260           $it.baseId = $currentBaseId;
4261         }
4262       }
4263       $shouldContinue = $sch.continue
4264     }
4265   }
4266   out += '' + ($closingBraces) + 'var ' + ($valid) + ' = ' + ($nextValid) + '; ';
4267   out = it.util.cleanUpCode(out);
4268   return out;
4269 }
4270
4271 },{}],35:[function(require,module,exports){
4272 'use strict';
4273 module.exports = function generate_uniqueItems(it, $keyword) {
4274   var out = ' ';
4275   var $lvl = it.level;
4276   var $dataLvl = it.dataLevel;
4277   var $schema = it.schema[$keyword];
4278   var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4279   var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4280   var $breakOnError = !it.opts.allErrors;
4281   var $errorKeyword;
4282   var $data = 'data' + ($dataLvl || '');
4283   var $valid = 'valid' + $lvl;
4284   var $isData = it.opts.v5 && $schema && $schema.$data,
4285     $schemaValue;
4286   if ($isData) {
4287     out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
4288     $schemaValue = 'schema' + $lvl;
4289   } else {
4290     $schemaValue = $schema;
4291   }
4292   if (($schema || $isData) && it.opts.uniqueItems !== false) {
4293     if ($isData) {
4294       out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { ';
4295     }
4296     out += ' var ' + ($valid) + ' = true; if (' + ($data) + '.length > 1) { var i = ' + ($data) + '.length, j; outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } } ';
4297     if ($isData) {
4298       out += '  }  ';
4299     }
4300     out += ' if (!' + ($valid) + ') {   ';
4301     var $$outStack = $$outStack || [];
4302     $$outStack.push(out);
4303     out = ''; /* istanbul ignore else */
4304     if (it.createErrors !== false) {
4305       out += ' { keyword: \'' + ($errorKeyword || 'uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } ';
4306       if (it.opts.messages !== false) {
4307         out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' ';
4308       }
4309       if (it.opts.verbose) {
4310         out += ' , schema:  ';
4311         if ($isData) {
4312           out += 'validate.schema' + ($schemaPath);
4313         } else {
4314           out += '' + ($schema);
4315         }
4316         out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4317       }
4318       out += ' } ';
4319     } else {
4320       out += ' {} ';
4321     }
4322     var __err = out;
4323     out = $$outStack.pop();
4324     if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
4325       if (it.async) {
4326         out += ' throw new ValidationError([' + (__err) + ']); ';
4327       } else {
4328         out += ' validate.errors = [' + (__err) + ']; return false; ';
4329       }
4330     } else {
4331       out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4332     }
4333     out += ' } ';
4334     if ($breakOnError) {
4335       out += ' else { ';
4336     }
4337   } else {
4338     if ($breakOnError) {
4339       out += ' if (true) { ';
4340     }
4341   }
4342   return out;
4343 }
4344
4345 },{}],36:[function(require,module,exports){
4346 'use strict';
4347 module.exports = function generate_validate(it, $keyword) {
4348   var out = '';
4349   var $async = it.schema.$async === true;
4350   if (it.isTop) {
4351     var $top = it.isTop,
4352       $lvl = it.level = 0,
4353       $dataLvl = it.dataLevel = 0,
4354       $data = 'data';
4355     it.rootId = it.resolve.fullPath(it.root.schema.id);
4356     it.baseId = it.baseId || it.rootId;
4357     if ($async) {
4358       it.async = true;
4359       var $es7 = it.opts.async == 'es7';
4360       it.yieldAwait = $es7 ? 'await' : 'yield';
4361     }
4362     delete it.isTop;
4363     it.dataPathArr = [undefined];
4364     out += ' var validate = ';
4365     if ($async) {
4366       if ($es7) {
4367         out += ' (async function ';
4368       } else {
4369         if (it.opts.async == 'co*') {
4370           out += 'co.wrap';
4371         }
4372         out += '(function* ';
4373       }
4374     } else {
4375       out += ' (function ';
4376     }
4377     out += ' (data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; var vErrors = null; ';
4378     out += ' var errors = 0;     ';
4379     out += ' if (rootData === undefined) rootData = data;';
4380   } else {
4381     var $lvl = it.level,
4382       $dataLvl = it.dataLevel,
4383       $data = 'data' + ($dataLvl || '');
4384     if (it.schema.id) it.baseId = it.resolve.url(it.baseId, it.schema.id);
4385     if ($async && !it.async) throw new Error('async schema in sync schema');
4386     out += ' var errs_' + ($lvl) + ' = errors;';
4387   }
4388   var $valid = 'valid' + $lvl,
4389     $breakOnError = !it.opts.allErrors,
4390     $closingBraces1 = '',
4391     $closingBraces2 = '',
4392     $errorKeyword;
4393   var $typeSchema = it.schema.type,
4394     $typeIsArray = Array.isArray($typeSchema);
4395   if ($typeSchema && it.opts.coerceTypes) {
4396     var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
4397     if ($coerceToTypes) {
4398       var $schemaPath = it.schemaPath + '.type',
4399         $errSchemaPath = it.errSchemaPath + '/type',
4400         $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
4401       out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') {  ';
4402       var $dataType = 'dataType' + $lvl,
4403         $coerced = 'coerced' + $lvl;
4404       out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; ';
4405       if (it.opts.coerceTypes == 'array') {
4406         out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; ';
4407       }
4408       out += ' var ' + ($coerced) + ' = undefined; ';
4409       var $bracesCoercion = '';
4410       var arr1 = $coerceToTypes;
4411       if (arr1) {
4412         var $type, $i = -1,
4413           l1 = arr1.length - 1;
4414         while ($i < l1) {
4415           $type = arr1[$i += 1];
4416           if ($i) {
4417             out += ' if (' + ($coerced) + ' === undefined) { ';
4418             $bracesCoercion += '}';
4419           }
4420           if (it.opts.coerceTypes == 'array' && $type != 'array') {
4421             out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + ';  } ';
4422           }
4423           if ($type == 'string') {
4424             out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; ';
4425           } else if ($type == 'number' || $type == 'integer') {
4426             out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' ';
4427             if ($type == 'integer') {
4428               out += ' && !(' + ($data) + ' % 1)';
4429             }
4430             out += ')) ' + ($coerced) + ' = +' + ($data) + '; ';
4431           } else if ($type == 'boolean') {
4432             out += ' if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; ';
4433           } else if ($type == 'null') {
4434             out += ' if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; ';
4435           } else if (it.opts.coerceTypes == 'array' && $type == 'array') {
4436             out += ' if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; ';
4437           }
4438         }
4439       }
4440       out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) {   ';
4441       var $$outStack = $$outStack || [];
4442       $$outStack.push(out);
4443       out = ''; /* istanbul ignore else */
4444       if (it.createErrors !== false) {
4445         out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
4446         if ($typeIsArray) {
4447           out += '' + ($typeSchema.join(","));
4448         } else {
4449           out += '' + ($typeSchema);
4450         }
4451         out += '\' } ';
4452         if (it.opts.messages !== false) {
4453           out += ' , message: \'should be ';
4454           if ($typeIsArray) {
4455             out += '' + ($typeSchema.join(","));
4456           } else {
4457             out += '' + ($typeSchema);
4458           }
4459           out += '\' ';
4460         }
4461         if (it.opts.verbose) {
4462           out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4463         }
4464         out += ' } ';
4465       } else {
4466         out += ' {} ';
4467       }
4468       var __err = out;
4469       out = $$outStack.pop();
4470       if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
4471         if (it.async) {
4472           out += ' throw new ValidationError([' + (__err) + ']); ';
4473         } else {
4474           out += ' validate.errors = [' + (__err) + ']; return false; ';
4475         }
4476       } else {
4477         out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4478       }
4479       out += ' } else {  ';
4480       var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
4481         $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
4482       out += ' ' + ($data) + ' = ' + ($coerced) + '; ';
4483       if (!$dataLvl) {
4484         out += 'if (' + ($parentData) + ' !== undefined)';
4485       }
4486       out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } } ';
4487     }
4488   }
4489   var $refKeywords;
4490   if (it.schema.$ref && ($refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'))) {
4491     if (it.opts.extendRefs == 'fail') {
4492       throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '"');
4493     } else if (it.opts.extendRefs == 'ignore') {
4494       $refKeywords = false;
4495       console.log('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
4496     } else if (it.opts.extendRefs !== true) {
4497       console.log('$ref: all keywords used in schema at path "' + it.errSchemaPath + '". It will change in the next major version, see issue #260. Use option { extendRefs: true } to keep current behaviour');
4498     }
4499   }
4500   if (it.schema.$ref && !$refKeywords) {
4501     out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' ';
4502     if ($breakOnError) {
4503       out += ' } if (errors === ';
4504       if ($top) {
4505         out += '0';
4506       } else {
4507         out += 'errs_' + ($lvl);
4508       }
4509       out += ') { ';
4510       $closingBraces2 += '}';
4511     }
4512   } else {
4513     var arr2 = it.RULES;
4514     if (arr2) {
4515       var $rulesGroup, i2 = -1,
4516         l2 = arr2.length - 1;
4517       while (i2 < l2) {
4518         $rulesGroup = arr2[i2 += 1];
4519         if ($shouldUseGroup($rulesGroup)) {
4520           if ($rulesGroup.type) {
4521             out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { ';
4522           }
4523           if (it.opts.useDefaults && !it.compositeRule) {
4524             if ($rulesGroup.type == 'object' && it.schema.properties) {
4525               var $schema = it.schema.properties,
4526                 $schemaKeys = Object.keys($schema);
4527               var arr3 = $schemaKeys;
4528               if (arr3) {
4529                 var $propertyKey, i3 = -1,
4530                   l3 = arr3.length - 1;
4531                 while (i3 < l3) {
4532                   $propertyKey = arr3[i3 += 1];
4533                   var $sch = $schema[$propertyKey];
4534                   if ($sch.default !== undefined) {
4535                     var $passData = $data + it.util.getProperty($propertyKey);
4536                     out += '  if (' + ($passData) + ' === undefined) ' + ($passData) + ' = ';
4537                     if (it.opts.useDefaults == 'shared') {
4538                       out += ' ' + (it.useDefault($sch.default)) + ' ';
4539                     } else {
4540                       out += ' ' + (JSON.stringify($sch.default)) + ' ';
4541                     }
4542                     out += '; ';
4543                   }
4544                 }
4545               }
4546             } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {
4547               var arr4 = it.schema.items;
4548               if (arr4) {
4549                 var $sch, $i = -1,
4550                   l4 = arr4.length - 1;
4551                 while ($i < l4) {
4552                   $sch = arr4[$i += 1];
4553                   if ($sch.default !== undefined) {
4554                     var $passData = $data + '[' + $i + ']';
4555                     out += '  if (' + ($passData) + ' === undefined) ' + ($passData) + ' = ';
4556                     if (it.opts.useDefaults == 'shared') {
4557                       out += ' ' + (it.useDefault($sch.default)) + ' ';
4558                     } else {
4559                       out += ' ' + (JSON.stringify($sch.default)) + ' ';
4560                     }
4561                     out += '; ';
4562                   }
4563                 }
4564               }
4565             }
4566           }
4567           var arr5 = $rulesGroup.rules;
4568           if (arr5) {
4569             var $rule, i5 = -1,
4570               l5 = arr5.length - 1;
4571             while (i5 < l5) {
4572               $rule = arr5[i5 += 1];
4573               if ($shouldUseRule($rule)) {
4574                 out += ' ' + ($rule.code(it, $rule.keyword)) + ' ';
4575                 if ($breakOnError) {
4576                   $closingBraces1 += '}';
4577                 }
4578               }
4579             }
4580           }
4581           if ($breakOnError) {
4582             out += ' ' + ($closingBraces1) + ' ';
4583             $closingBraces1 = '';
4584           }
4585           if ($rulesGroup.type) {
4586             out += ' } ';
4587             if ($typeSchema && $typeSchema === $rulesGroup.type) {
4588               var $typeChecked = true;
4589               out += ' else { ';
4590               var $schemaPath = it.schemaPath + '.type',
4591                 $errSchemaPath = it.errSchemaPath + '/type';
4592               var $$outStack = $$outStack || [];
4593               $$outStack.push(out);
4594               out = ''; /* istanbul ignore else */
4595               if (it.createErrors !== false) {
4596                 out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
4597                 if ($typeIsArray) {
4598                   out += '' + ($typeSchema.join(","));
4599                 } else {
4600                   out += '' + ($typeSchema);
4601                 }
4602                 out += '\' } ';
4603                 if (it.opts.messages !== false) {
4604                   out += ' , message: \'should be ';
4605                   if ($typeIsArray) {
4606                     out += '' + ($typeSchema.join(","));
4607                   } else {
4608                     out += '' + ($typeSchema);
4609                   }
4610                   out += '\' ';
4611                 }
4612                 if (it.opts.verbose) {
4613                   out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4614                 }
4615                 out += ' } ';
4616               } else {
4617                 out += ' {} ';
4618               }
4619               var __err = out;
4620               out = $$outStack.pop();
4621               if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
4622                 if (it.async) {
4623                   out += ' throw new ValidationError([' + (__err) + ']); ';
4624                 } else {
4625                   out += ' validate.errors = [' + (__err) + ']; return false; ';
4626                 }
4627               } else {
4628                 out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4629               }
4630               out += ' } ';
4631             }
4632           }
4633           if ($breakOnError) {
4634             out += ' if (errors === ';
4635             if ($top) {
4636               out += '0';
4637             } else {
4638               out += 'errs_' + ($lvl);
4639             }
4640             out += ') { ';
4641             $closingBraces2 += '}';
4642           }
4643         }
4644       }
4645     }
4646   }
4647   if ($typeSchema && !$typeChecked && !(it.opts.coerceTypes && $coerceToTypes)) {
4648     var $schemaPath = it.schemaPath + '.type',
4649       $errSchemaPath = it.errSchemaPath + '/type',
4650       $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
4651     out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') {   ';
4652     var $$outStack = $$outStack || [];
4653     $$outStack.push(out);
4654     out = ''; /* istanbul ignore else */
4655     if (it.createErrors !== false) {
4656       out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
4657       if ($typeIsArray) {
4658         out += '' + ($typeSchema.join(","));
4659       } else {
4660         out += '' + ($typeSchema);
4661       }
4662       out += '\' } ';
4663       if (it.opts.messages !== false) {
4664         out += ' , message: \'should be ';
4665         if ($typeIsArray) {
4666           out += '' + ($typeSchema.join(","));
4667         } else {
4668           out += '' + ($typeSchema);
4669         }
4670         out += '\' ';
4671       }
4672       if (it.opts.verbose) {
4673         out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4674       }
4675       out += ' } ';
4676     } else {
4677       out += ' {} ';
4678     }
4679     var __err = out;
4680     out = $$outStack.pop();
4681     if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
4682       if (it.async) {
4683         out += ' throw new ValidationError([' + (__err) + ']); ';
4684       } else {
4685         out += ' validate.errors = [' + (__err) + ']; return false; ';
4686       }
4687     } else {
4688       out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4689     }
4690     out += ' }';
4691   }
4692   if ($breakOnError) {
4693     out += ' ' + ($closingBraces2) + ' ';
4694   }
4695   if ($top) {
4696     if ($async) {
4697       out += ' if (errors === 0) return true;           ';
4698       out += ' else throw new ValidationError(vErrors); ';
4699     } else {
4700       out += ' validate.errors = vErrors; ';
4701       out += ' return errors === 0;       ';
4702     }
4703     out += ' }); return validate;';
4704   } else {
4705     out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
4706   }
4707   out = it.util.cleanUpCode(out);
4708   if ($top && $breakOnError) {
4709     out = it.util.cleanUpVarErrors(out, $async);
4710   }
4711
4712   function $shouldUseGroup($rulesGroup) {
4713     for (var i = 0; i < $rulesGroup.rules.length; i++)
4714       if ($shouldUseRule($rulesGroup.rules[i])) return true;
4715   }
4716
4717   function $shouldUseRule($rule) {
4718     return it.schema[$rule.keyword] !== undefined || ($rule.keyword == 'properties' && (it.schema.additionalProperties === false || typeof it.schema.additionalProperties == 'object' || (it.schema.patternProperties && Object.keys(it.schema.patternProperties).length) || (it.opts.v5 && it.schema.patternGroups && Object.keys(it.schema.patternGroups).length)));
4719   }
4720   return out;
4721 }
4722
4723 },{}],37:[function(require,module,exports){
4724 'use strict';
4725
4726 var IDENTIFIER = /^[a-z_$][a-z0-9_$\-]*$/i;
4727 var customRuleCode = require('./dotjs/custom');
4728
4729 module.exports = {
4730   add: addKeyword,
4731   get: getKeyword,
4732   remove: removeKeyword
4733 };
4734
4735 /**
4736  * Define custom keyword
4737  * @this  Ajv
4738  * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).
4739  * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
4740  */
4741 function addKeyword(keyword, definition) {
4742   /* jshint validthis: true */
4743   /* eslint no-shadow: 0 */
4744   var RULES = this.RULES;
4745
4746   if (RULES.keywords[keyword])
4747     throw new Error('Keyword ' + keyword + ' is already defined');
4748
4749   if (!IDENTIFIER.test(keyword))
4750     throw new Error('Keyword ' + keyword + ' is not a valid identifier');
4751
4752   if (definition) {
4753     if (definition.macro && definition.valid !== undefined)
4754       throw new Error('"valid" option cannot be used with macro keywords');
4755
4756     var dataType = definition.type;
4757     if (Array.isArray(dataType)) {
4758       var i, len = dataType.length;
4759       for (i=0; i<len; i++) checkDataType(dataType[i]);
4760       for (i=0; i<len; i++) _addRule(keyword, dataType[i], definition);
4761     } else {
4762       if (dataType) checkDataType(dataType);
4763       _addRule(keyword, dataType, definition);
4764     }
4765
4766     var $data = definition.$data === true && this._opts.v5;
4767     if ($data && !definition.validate)
4768       throw new Error('$data support: "validate" function is not defined');
4769
4770     var metaSchema = definition.metaSchema;
4771     if (metaSchema) {
4772       if ($data) {
4773         metaSchema = {
4774           anyOf: [
4775             metaSchema,
4776             { '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#/definitions/$data' }
4777           ]
4778         };
4779       }
4780       definition.validateSchema = this.compile(metaSchema, true);
4781     }
4782   }
4783
4784   RULES.keywords[keyword] = RULES.all[keyword] = true;
4785
4786
4787   function _addRule(keyword, dataType, definition) {
4788     var ruleGroup;
4789     for (var i=0; i<RULES.length; i++) {
4790       var rg = RULES[i];
4791       if (rg.type == dataType) {
4792         ruleGroup = rg;
4793         break;
4794       }
4795     }
4796
4797     if (!ruleGroup) {
4798       ruleGroup = { type: dataType, rules: [] };
4799       RULES.push(ruleGroup);
4800     }
4801
4802     var rule = {
4803       keyword: keyword,
4804       definition: definition,
4805       custom: true,
4806       code: customRuleCode
4807     };
4808     ruleGroup.rules.push(rule);
4809     RULES.custom[keyword] = rule;
4810   }
4811
4812
4813   function checkDataType(dataType) {
4814     if (!RULES.types[dataType]) throw new Error('Unknown type ' + dataType);
4815   }
4816 }
4817
4818
4819 /**
4820  * Get keyword
4821  * @this  Ajv
4822  * @param {String} keyword pre-defined or custom keyword.
4823  * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
4824  */
4825 function getKeyword(keyword) {
4826   /* jshint validthis: true */
4827   var rule = this.RULES.custom[keyword];
4828   return rule ? rule.definition : this.RULES.keywords[keyword] || false;
4829 }
4830
4831
4832 /**
4833  * Remove keyword
4834  * @this  Ajv
4835  * @param {String} keyword pre-defined or custom keyword.
4836  */
4837 function removeKeyword(keyword) {
4838   /* jshint validthis: true */
4839   var RULES = this.RULES;
4840   delete RULES.keywords[keyword];
4841   delete RULES.all[keyword];
4842   delete RULES.custom[keyword];
4843   for (var i=0; i<RULES.length; i++) {
4844     var rules = RULES[i].rules;
4845     for (var j=0; j<rules.length; j++) {
4846       if (rules[j].keyword == keyword) {
4847         rules.splice(j, 1);
4848         break;
4849       }
4850     }
4851   }
4852 }
4853
4854 },{"./dotjs/custom":21}],38:[function(require,module,exports){
4855 module.exports={
4856     "id": "http://json-schema.org/draft-04/schema#",
4857     "$schema": "http://json-schema.org/draft-04/schema#",
4858     "description": "Core schema meta-schema",
4859     "definitions": {
4860         "schemaArray": {
4861             "type": "array",
4862             "minItems": 1,
4863             "items": { "$ref": "#" }
4864         },
4865         "positiveInteger": {
4866             "type": "integer",
4867             "minimum": 0
4868         },
4869         "positiveIntegerDefault0": {
4870             "allOf": [ { "$ref": "#/definitions/positiveInteger" }, { "default": 0 } ]
4871         },
4872         "simpleTypes": {
4873             "enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ]
4874         },
4875         "stringArray": {
4876             "type": "array",
4877             "items": { "type": "string" },
4878             "minItems": 1,
4879             "uniqueItems": true
4880         }
4881     },
4882     "type": "object",
4883     "properties": {
4884         "id": {
4885             "type": "string",
4886             "format": "uri"
4887         },
4888         "$schema": {
4889             "type": "string",
4890             "format": "uri"
4891         },
4892         "title": {
4893             "type": "string"
4894         },
4895         "description": {
4896             "type": "string"
4897         },
4898         "default": {},
4899         "multipleOf": {
4900             "type": "number",
4901             "minimum": 0,
4902             "exclusiveMinimum": true
4903         },
4904         "maximum": {
4905             "type": "number"
4906         },
4907         "exclusiveMaximum": {
4908             "type": "boolean",
4909             "default": false
4910         },
4911         "minimum": {
4912             "type": "number"
4913         },
4914         "exclusiveMinimum": {
4915             "type": "boolean",
4916             "default": false
4917         },
4918         "maxLength": { "$ref": "#/definitions/positiveInteger" },
4919         "minLength": { "$ref": "#/definitions/positiveIntegerDefault0" },
4920         "pattern": {
4921             "type": "string",
4922             "format": "regex"
4923         },
4924         "additionalItems": {
4925             "anyOf": [
4926                 { "type": "boolean" },
4927                 { "$ref": "#" }
4928             ],
4929             "default": {}
4930         },
4931         "items": {
4932             "anyOf": [
4933                 { "$ref": "#" },
4934                 { "$ref": "#/definitions/schemaArray" }
4935             ],
4936             "default": {}
4937         },
4938         "maxItems": { "$ref": "#/definitions/positiveInteger" },
4939         "minItems": { "$ref": "#/definitions/positiveIntegerDefault0" },
4940         "uniqueItems": {
4941             "type": "boolean",
4942             "default": false
4943         },
4944         "maxProperties": { "$ref": "#/definitions/positiveInteger" },
4945         "minProperties": { "$ref": "#/definitions/positiveIntegerDefault0" },
4946         "required": { "$ref": "#/definitions/stringArray" },
4947         "additionalProperties": {
4948             "anyOf": [
4949                 { "type": "boolean" },
4950                 { "$ref": "#" }
4951             ],
4952             "default": {}
4953         },
4954         "definitions": {
4955             "type": "object",
4956             "additionalProperties": { "$ref": "#" },
4957             "default": {}
4958         },
4959         "properties": {
4960             "type": "object",
4961             "additionalProperties": { "$ref": "#" },
4962             "default": {}
4963         },
4964         "patternProperties": {
4965             "type": "object",
4966             "additionalProperties": { "$ref": "#" },
4967             "default": {}
4968         },
4969         "dependencies": {
4970             "type": "object",
4971             "additionalProperties": {
4972                 "anyOf": [
4973                     { "$ref": "#" },
4974                     { "$ref": "#/definitions/stringArray" }
4975                 ]
4976             }
4977         },
4978         "enum": {
4979             "type": "array",
4980             "minItems": 1,
4981             "uniqueItems": true
4982         },
4983         "type": {
4984             "anyOf": [
4985                 { "$ref": "#/definitions/simpleTypes" },
4986                 {
4987                     "type": "array",
4988                     "items": { "$ref": "#/definitions/simpleTypes" },
4989                     "minItems": 1,
4990                     "uniqueItems": true
4991                 }
4992             ]
4993         },
4994         "allOf": { "$ref": "#/definitions/schemaArray" },
4995         "anyOf": { "$ref": "#/definitions/schemaArray" },
4996         "oneOf": { "$ref": "#/definitions/schemaArray" },
4997         "not": { "$ref": "#" }
4998     },
4999     "dependencies": {
5000         "exclusiveMaximum": [ "maximum" ],
5001         "exclusiveMinimum": [ "minimum" ]
5002     },
5003     "default": {}
5004 }
5005
5006 },{}],39:[function(require,module,exports){
5007 module.exports={
5008     "id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#",
5009     "$schema": "http://json-schema.org/draft-04/schema#",
5010     "description": "Core schema meta-schema (v5 proposals)",
5011     "definitions": {
5012         "schemaArray": {
5013             "type": "array",
5014             "minItems": 1,
5015             "items": { "$ref": "#" }
5016         },
5017         "positiveInteger": {
5018             "type": "integer",
5019             "minimum": 0
5020         },
5021         "positiveIntegerDefault0": {
5022             "allOf": [ { "$ref": "#/definitions/positiveInteger" }, { "default": 0 } ]
5023         },
5024         "simpleTypes": {
5025             "enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ]
5026         },
5027         "stringArray": {
5028             "type": "array",
5029             "items": { "type": "string" },
5030             "minItems": 1,
5031             "uniqueItems": true
5032         },
5033         "$data": {
5034             "type": "object",
5035             "required": [ "$data" ],
5036             "properties": {
5037                 "$data": {
5038                     "type": "string",
5039                     "anyOf": [
5040                         { "format": "relative-json-pointer" }, 
5041                         { "format": "json-pointer" }
5042                     ]
5043                 }
5044             },
5045             "additionalProperties": false
5046         }
5047     },
5048     "type": "object",
5049     "properties": {
5050         "id": {
5051             "type": "string",
5052             "format": "uri"
5053         },
5054         "$schema": {
5055             "type": "string",
5056             "format": "uri"
5057         },
5058         "title": {
5059             "type": "string"
5060         },
5061         "description": {
5062             "type": "string"
5063         },
5064         "default": {},
5065         "multipleOf": {
5066             "anyOf": [
5067                 {
5068                     "type": "number",
5069                     "minimum": 0,
5070                     "exclusiveMinimum": true
5071                 },
5072                 { "$ref": "#/definitions/$data" }
5073             ]
5074         },
5075         "maximum": {
5076             "anyOf": [
5077                 { "type": "number" },
5078                 { "$ref": "#/definitions/$data" }
5079             ]
5080         },
5081         "exclusiveMaximum": {
5082             "anyOf": [
5083                 {
5084                     "type": "boolean",
5085                     "default": false
5086                 },
5087                 { "$ref": "#/definitions/$data" }
5088             ]
5089         },
5090         "minimum": {
5091             "anyOf": [
5092                 { "type": "number" },
5093                 { "$ref": "#/definitions/$data" }
5094             ]
5095         },
5096         "exclusiveMinimum": {
5097             "anyOf": [
5098                 {
5099                     "type": "boolean",
5100                     "default": false
5101                 },
5102                 { "$ref": "#/definitions/$data" }
5103             ]
5104         },
5105         "maxLength": {
5106             "anyOf": [
5107                 { "$ref": "#/definitions/positiveInteger" },
5108                 { "$ref": "#/definitions/$data" }
5109             ]
5110         },
5111         "minLength": {
5112             "anyOf": [
5113                 { "$ref": "#/definitions/positiveIntegerDefault0" },
5114                 { "$ref": "#/definitions/$data" }
5115             ]
5116         },
5117         "pattern": {
5118             "anyOf": [
5119                 {
5120                     "type": "string",
5121                     "format": "regex"
5122                 },
5123                 { "$ref": "#/definitions/$data" }
5124             ]
5125         },
5126         "additionalItems": {
5127             "anyOf": [
5128                 { "type": "boolean" },
5129                 { "$ref": "#" },
5130                 { "$ref": "#/definitions/$data" }
5131             ],
5132             "default": {}
5133         },
5134         "items": {
5135             "anyOf": [
5136                 { "$ref": "#" },
5137                 { "$ref": "#/definitions/schemaArray" }
5138             ],
5139             "default": {}
5140         },
5141         "maxItems": {
5142             "anyOf": [
5143                 { "$ref": "#/definitions/positiveInteger" },
5144                 { "$ref": "#/definitions/$data" }
5145             ]
5146         },
5147         "minItems": {
5148             "anyOf": [
5149                 { "$ref": "#/definitions/positiveIntegerDefault0" },
5150                 { "$ref": "#/definitions/$data" }
5151             ]
5152         },
5153         "uniqueItems": {
5154             "anyOf": [
5155                 {
5156                     "type": "boolean",
5157                     "default": false
5158                 },
5159                 { "$ref": "#/definitions/$data" }
5160             ]
5161         },
5162         "maxProperties": {
5163             "anyOf": [
5164                 { "$ref": "#/definitions/positiveInteger" },
5165                 { "$ref": "#/definitions/$data" }
5166             ]
5167         },
5168         "minProperties": {
5169             "anyOf": [
5170                 { "$ref": "#/definitions/positiveIntegerDefault0" },
5171                 { "$ref": "#/definitions/$data" }
5172             ]
5173         },
5174         "required": {
5175             "anyOf": [
5176                 { "$ref": "#/definitions/stringArray" },
5177                 { "$ref": "#/definitions/$data" }
5178             ]
5179         },
5180         "additionalProperties": {
5181             "anyOf": [
5182                 { "type": "boolean" },
5183                 { "$ref": "#" },
5184                 { "$ref": "#/definitions/$data" }
5185             ],
5186             "default": {}
5187         },
5188         "definitions": {
5189             "type": "object",
5190             "additionalProperties": { "$ref": "#" },
5191             "default": {}
5192         },
5193         "properties": {
5194             "type": "object",
5195             "additionalProperties": { "$ref": "#" },
5196             "default": {}
5197         },
5198         "patternProperties": {
5199             "type": "object",
5200             "additionalProperties": { "$ref": "#" },
5201             "default": {}
5202         },
5203         "dependencies": {
5204             "type": "object",
5205             "additionalProperties": {
5206                 "anyOf": [
5207                     { "$ref": "#" },
5208                     { "$ref": "#/definitions/stringArray" }
5209                 ]
5210             }
5211         },
5212         "enum": {
5213             "anyOf": [
5214                 {
5215                     "type": "array",
5216                     "minItems": 1,
5217                     "uniqueItems": true
5218                 },
5219                 { "$ref": "#/definitions/$data" }
5220             ]
5221         },
5222         "type": {
5223             "anyOf": [
5224                 { "$ref": "#/definitions/simpleTypes" },
5225                 {
5226                     "type": "array",
5227                     "items": { "$ref": "#/definitions/simpleTypes" },
5228                     "minItems": 1,
5229                     "uniqueItems": true
5230                 }
5231             ]
5232         },
5233         "allOf": { "$ref": "#/definitions/schemaArray" },
5234         "anyOf": { "$ref": "#/definitions/schemaArray" },
5235         "oneOf": { "$ref": "#/definitions/schemaArray" },
5236         "not": { "$ref": "#" },
5237         "format": {
5238             "anyOf": [
5239                 { "type": "string" },
5240                 { "$ref": "#/definitions/$data" }
5241             ]
5242         },
5243         "formatMaximum": {
5244             "anyOf": [
5245                 { "type": "string" },
5246                 { "$ref": "#/definitions/$data" }
5247             ]
5248         },
5249         "formatMinimum": {
5250             "anyOf": [
5251                 { "type": "string" },
5252                 { "$ref": "#/definitions/$data" }
5253             ]
5254         },
5255         "formatExclusiveMaximum": {
5256             "anyOf": [
5257                 {
5258                     "type": "boolean",
5259                     "default": false
5260                 },
5261                 { "$ref": "#/definitions/$data" }
5262             ]
5263         },
5264         "formatExclusiveMinimum": {
5265             "anyOf": [
5266                 {
5267                     "type": "boolean",
5268                     "default": false
5269                 },
5270                 { "$ref": "#/definitions/$data" }
5271             ]
5272         },
5273         "constant": {
5274             "anyOf": [
5275                 {},
5276                 { "$ref": "#/definitions/$data" }
5277             ]
5278         },
5279         "contains": { "$ref": "#" },
5280         "patternGroups": {
5281             "type": "object",
5282             "additionalProperties": {
5283                 "type": "object",
5284                 "required": [ "schema" ],
5285                 "properties": {
5286                     "maximum": {
5287                         "anyOf": [
5288                             { "$ref": "#/definitions/positiveInteger" },
5289                             { "$ref": "#/definitions/$data" }
5290                         ]
5291                     },
5292                     "minimum": {
5293                         "anyOf": [
5294                             { "$ref": "#/definitions/positiveIntegerDefault0" },
5295                             { "$ref": "#/definitions/$data" }
5296                         ]
5297                     },
5298                     "schema": { "$ref": "#" }
5299                 },
5300                 "additionalProperties": false
5301             },
5302             "default": {}
5303         },
5304         "switch": {
5305             "type": "array",
5306             "items": {
5307                 "required": [ "then" ],
5308                 "properties": {
5309                     "if": { "$ref": "#" },
5310                     "then": {
5311                         "anyOf": [
5312                             { "type": "boolean" },
5313                             { "$ref": "#" }
5314                         ]
5315                     },
5316                     "continue": { "type": "boolean" }
5317                 },
5318                 "additionalProperties": false,
5319                 "dependencies": {
5320                     "continue": [ "if" ]
5321                 }
5322             }
5323         }
5324     },
5325     "dependencies": {
5326         "exclusiveMaximum": [ "maximum" ],
5327         "exclusiveMinimum": [ "minimum" ],
5328         "formatMaximum": [ "format" ],
5329         "formatMinimum": [ "format" ],
5330         "formatExclusiveMaximum": [ "formatMaximum" ],
5331         "formatExclusiveMinimum": [ "formatMinimum" ]
5332     },
5333     "default": {}
5334 }
5335
5336 },{}],40:[function(require,module,exports){
5337 'use strict';
5338
5339 var META_SCHEMA_ID = 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json';
5340
5341 module.exports = {
5342   enable: enableV5,
5343   META_SCHEMA_ID: META_SCHEMA_ID
5344 };
5345
5346
5347 function enableV5(ajv) {
5348   var inlineFunctions = {
5349     'switch': require('./dotjs/switch'),
5350     'constant': require('./dotjs/constant'),
5351     '_formatLimit': require('./dotjs/_formatLimit'),
5352     'patternRequired': require('./dotjs/patternRequired')
5353   };
5354
5355   if (ajv._opts.meta !== false) {
5356     var metaSchema = require('./refs/json-schema-v5.json');
5357     ajv.addMetaSchema(metaSchema, META_SCHEMA_ID);
5358   }
5359   _addKeyword('constant');
5360   ajv.addKeyword('contains', { type: 'array', macro: containsMacro });
5361
5362   _addKeyword('formatMaximum', 'string', inlineFunctions._formatLimit);
5363   _addKeyword('formatMinimum', 'string', inlineFunctions._formatLimit);
5364   ajv.addKeyword('formatExclusiveMaximum');
5365   ajv.addKeyword('formatExclusiveMinimum');
5366
5367   ajv.addKeyword('patternGroups'); // implemented in properties.jst
5368   _addKeyword('patternRequired', 'object');
5369   _addKeyword('switch');
5370
5371
5372   function _addKeyword(keyword, types, inlineFunc) {
5373     var definition = {
5374       inline: inlineFunc || inlineFunctions[keyword],
5375       statements: true,
5376       errors: 'full'
5377     };
5378     if (types) definition.type = types;
5379     ajv.addKeyword(keyword, definition);
5380   }
5381 }
5382
5383
5384 function containsMacro(schema) {
5385   return {
5386     not: { items: { not: schema } }
5387   };
5388 }
5389
5390 },{"./dotjs/_formatLimit":13,"./dotjs/constant":20,"./dotjs/patternRequired":30,"./dotjs/switch":34,"./refs/json-schema-v5.json":39}],41:[function(require,module,exports){
5391 (function (global){
5392 /*! https://mths.be/punycode v1.4.1 by @mathias */
5393 ;(function(root) {
5394
5395         /** Detect free variables */
5396         var freeExports = typeof exports == 'object' && exports &&
5397                 !exports.nodeType && exports;
5398         var freeModule = typeof module == 'object' && module &&
5399                 !module.nodeType && module;
5400         var freeGlobal = typeof global == 'object' && global;
5401         if (
5402                 freeGlobal.global === freeGlobal ||
5403                 freeGlobal.window === freeGlobal ||
5404                 freeGlobal.self === freeGlobal
5405         ) {
5406                 root = freeGlobal;
5407         }
5408
5409         /**
5410          * The `punycode` object.
5411          * @name punycode
5412          * @type Object
5413          */
5414         var punycode,
5415
5416         /** Highest positive signed 32-bit float value */
5417         maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
5418
5419         /** Bootstring parameters */
5420         base = 36,
5421         tMin = 1,
5422         tMax = 26,
5423         skew = 38,
5424         damp = 700,
5425         initialBias = 72,
5426         initialN = 128, // 0x80
5427         delimiter = '-', // '\x2D'
5428
5429         /** Regular expressions */
5430         regexPunycode = /^xn--/,
5431         regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
5432         regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
5433
5434         /** Error messages */
5435         errors = {
5436                 'overflow': 'Overflow: input needs wider integers to process',
5437                 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
5438                 'invalid-input': 'Invalid input'
5439         },
5440
5441         /** Convenience shortcuts */
5442         baseMinusTMin = base - tMin,
5443         floor = Math.floor,
5444         stringFromCharCode = String.fromCharCode,
5445
5446         /** Temporary variable */
5447         key;
5448
5449         /*--------------------------------------------------------------------------*/
5450
5451         /**
5452          * A generic error utility function.
5453          * @private
5454          * @param {String} type The error type.
5455          * @returns {Error} Throws a `RangeError` with the applicable error message.
5456          */
5457         function error(type) {
5458                 throw new RangeError(errors[type]);
5459         }
5460
5461         /**
5462          * A generic `Array#map` utility function.
5463          * @private
5464          * @param {Array} array The array to iterate over.
5465          * @param {Function} callback The function that gets called for every array
5466          * item.
5467          * @returns {Array} A new array of values returned by the callback function.
5468          */
5469         function map(array, fn) {
5470                 var length = array.length;
5471                 var result = [];
5472                 while (length--) {
5473                         result[length] = fn(array[length]);
5474                 }
5475                 return result;
5476         }
5477
5478         /**
5479          * A simple `Array#map`-like wrapper to work with domain name strings or email
5480          * addresses.
5481          * @private
5482          * @param {String} domain The domain name or email address.
5483          * @param {Function} callback The function that gets called for every
5484          * character.
5485          * @returns {Array} A new string of characters returned by the callback
5486          * function.
5487          */
5488         function mapDomain(string, fn) {
5489                 var parts = string.split('@');
5490                 var result = '';
5491                 if (parts.length > 1) {
5492                         // In email addresses, only the domain name should be punycoded. Leave
5493                         // the local part (i.e. everything up to `@`) intact.
5494                         result = parts[0] + '@';
5495                         string = parts[1];
5496                 }
5497                 // Avoid `split(regex)` for IE8 compatibility. See #17.
5498                 string = string.replace(regexSeparators, '\x2E');
5499                 var labels = string.split('.');
5500                 var encoded = map(labels, fn).join('.');
5501                 return result + encoded;
5502         }
5503
5504         /**
5505          * Creates an array containing the numeric code points of each Unicode
5506          * character in the string. While JavaScript uses UCS-2 internally,
5507          * this function will convert a pair of surrogate halves (each of which
5508          * UCS-2 exposes as separate characters) into a single code point,
5509          * matching UTF-16.
5510          * @see `punycode.ucs2.encode`
5511          * @see <https://mathiasbynens.be/notes/javascript-encoding>
5512          * @memberOf punycode.ucs2
5513          * @name decode
5514          * @param {String} string The Unicode input string (UCS-2).
5515          * @returns {Array} The new array of code points.
5516          */
5517         function ucs2decode(string) {
5518                 var output = [],
5519                     counter = 0,
5520                     length = string.length,
5521                     value,
5522                     extra;
5523                 while (counter < length) {
5524                         value = string.charCodeAt(counter++);
5525                         if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
5526                                 // high surrogate, and there is a next character
5527                                 extra = string.charCodeAt(counter++);
5528                                 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
5529                                         output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
5530                                 } else {
5531                                         // unmatched surrogate; only append this code unit, in case the next
5532                                         // code unit is the high surrogate of a surrogate pair
5533                                         output.push(value);
5534                                         counter--;
5535                                 }
5536                         } else {
5537                                 output.push(value);
5538                         }
5539                 }
5540                 return output;
5541         }
5542
5543         /**
5544          * Creates a string based on an array of numeric code points.
5545          * @see `punycode.ucs2.decode`
5546          * @memberOf punycode.ucs2
5547          * @name encode
5548          * @param {Array} codePoints The array of numeric code points.
5549          * @returns {String} The new Unicode string (UCS-2).
5550          */
5551         function ucs2encode(array) {
5552                 return map(array, function(value) {
5553                         var output = '';
5554                         if (value > 0xFFFF) {
5555                                 value -= 0x10000;
5556                                 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
5557                                 value = 0xDC00 | value & 0x3FF;
5558                         }
5559                         output += stringFromCharCode(value);
5560                         return output;
5561                 }).join('');
5562         }
5563
5564         /**
5565          * Converts a basic code point into a digit/integer.
5566          * @see `digitToBasic()`
5567          * @private
5568          * @param {Number} codePoint The basic numeric code point value.
5569          * @returns {Number} The numeric value of a basic code point (for use in
5570          * representing integers) in the range `0` to `base - 1`, or `base` if
5571          * the code point does not represent a value.
5572          */
5573         function basicToDigit(codePoint) {
5574                 if (codePoint - 48 < 10) {
5575                         return codePoint - 22;
5576                 }
5577                 if (codePoint - 65 < 26) {
5578                         return codePoint - 65;
5579                 }
5580                 if (codePoint - 97 < 26) {
5581                         return codePoint - 97;
5582                 }
5583                 return base;
5584         }
5585
5586         /**
5587          * Converts a digit/integer into a basic code point.
5588          * @see `basicToDigit()`
5589          * @private
5590          * @param {Number} digit The numeric value of a basic code point.
5591          * @returns {Number} The basic code point whose value (when used for
5592          * representing integers) is `digit`, which needs to be in the range
5593          * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
5594          * used; else, the lowercase form is used. The behavior is undefined
5595          * if `flag` is non-zero and `digit` has no uppercase form.
5596          */
5597         function digitToBasic(digit, flag) {
5598                 //  0..25 map to ASCII a..z or A..Z
5599                 // 26..35 map to ASCII 0..9
5600                 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
5601         }
5602
5603         /**
5604          * Bias adaptation function as per section 3.4 of RFC 3492.
5605          * https://tools.ietf.org/html/rfc3492#section-3.4
5606          * @private
5607          */
5608         function adapt(delta, numPoints, firstTime) {
5609                 var k = 0;
5610                 delta = firstTime ? floor(delta / damp) : delta >> 1;
5611                 delta += floor(delta / numPoints);
5612                 for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
5613                         delta = floor(delta / baseMinusTMin);
5614                 }
5615                 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
5616         }
5617
5618         /**
5619          * Converts a Punycode string of ASCII-only symbols to a string of Unicode
5620          * symbols.
5621          * @memberOf punycode
5622          * @param {String} input The Punycode string of ASCII-only symbols.
5623          * @returns {String} The resulting string of Unicode symbols.
5624          */
5625         function decode(input) {
5626                 // Don't use UCS-2
5627                 var output = [],
5628                     inputLength = input.length,
5629                     out,
5630                     i = 0,
5631                     n = initialN,
5632                     bias = initialBias,
5633                     basic,
5634                     j,
5635                     index,
5636                     oldi,
5637                     w,
5638                     k,
5639                     digit,
5640                     t,
5641                     /** Cached calculation results */
5642                     baseMinusT;
5643
5644                 // Handle the basic code points: let `basic` be the number of input code
5645                 // points before the last delimiter, or `0` if there is none, then copy
5646                 // the first basic code points to the output.
5647
5648                 basic = input.lastIndexOf(delimiter);
5649                 if (basic < 0) {
5650                         basic = 0;
5651                 }
5652
5653                 for (j = 0; j < basic; ++j) {
5654                         // if it's not a basic code point
5655                         if (input.charCodeAt(j) >= 0x80) {
5656                                 error('not-basic');
5657                         }
5658                         output.push(input.charCodeAt(j));
5659                 }
5660
5661                 // Main decoding loop: start just after the last delimiter if any basic code
5662                 // points were copied; start at the beginning otherwise.
5663
5664                 for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
5665
5666                         // `index` is the index of the next character to be consumed.
5667                         // Decode a generalized variable-length integer into `delta`,
5668                         // which gets added to `i`. The overflow checking is easier
5669                         // if we increase `i` as we go, then subtract off its starting
5670                         // value at the end to obtain `delta`.
5671                         for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
5672
5673                                 if (index >= inputLength) {
5674                                         error('invalid-input');
5675                                 }
5676
5677                                 digit = basicToDigit(input.charCodeAt(index++));
5678
5679                                 if (digit >= base || digit > floor((maxInt - i) / w)) {
5680                                         error('overflow');
5681                                 }
5682
5683                                 i += digit * w;
5684                                 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
5685
5686                                 if (digit < t) {
5687                                         break;
5688                                 }
5689
5690                                 baseMinusT = base - t;
5691                                 if (w > floor(maxInt / baseMinusT)) {
5692                                         error('overflow');
5693                                 }
5694
5695                                 w *= baseMinusT;
5696
5697                         }
5698
5699                         out = output.length + 1;
5700                         bias = adapt(i - oldi, out, oldi == 0);
5701
5702                         // `i` was supposed to wrap around from `out` to `0`,
5703                         // incrementing `n` each time, so we'll fix that now:
5704                         if (floor(i / out) > maxInt - n) {
5705                                 error('overflow');
5706                         }
5707
5708                         n += floor(i / out);
5709                         i %= out;
5710
5711                         // Insert `n` at position `i` of the output
5712                         output.splice(i++, 0, n);
5713
5714                 }
5715
5716                 return ucs2encode(output);
5717         }
5718
5719         /**
5720          * Converts a string of Unicode symbols (e.g. a domain name label) to a
5721          * Punycode string of ASCII-only symbols.
5722          * @memberOf punycode
5723          * @param {String} input The string of Unicode symbols.
5724          * @returns {String} The resulting Punycode string of ASCII-only symbols.
5725          */
5726         function encode(input) {
5727                 var n,
5728                     delta,
5729                     handledCPCount,
5730                     basicLength,
5731                     bias,
5732                     j,
5733                     m,
5734                     q,
5735                     k,
5736                     t,
5737                     currentValue,
5738                     output = [],
5739                     /** `inputLength` will hold the number of code points in `input`. */
5740                     inputLength,
5741                     /** Cached calculation results */
5742                     handledCPCountPlusOne,
5743                     baseMinusT,
5744                     qMinusT;
5745
5746                 // Convert the input in UCS-2 to Unicode
5747                 input = ucs2decode(input);
5748
5749                 // Cache the length
5750                 inputLength = input.length;
5751
5752                 // Initialize the state
5753                 n = initialN;
5754                 delta = 0;
5755                 bias = initialBias;
5756
5757                 // Handle the basic code points
5758                 for (j = 0; j < inputLength; ++j) {
5759                         currentValue = input[j];
5760                         if (currentValue < 0x80) {
5761                                 output.push(stringFromCharCode(currentValue));
5762                         }
5763                 }
5764
5765                 handledCPCount = basicLength = output.length;
5766
5767                 // `handledCPCount` is the number of code points that have been handled;
5768                 // `basicLength` is the number of basic code points.
5769
5770                 // Finish the basic string - if it is not empty - with a delimiter
5771                 if (basicLength) {
5772                         output.push(delimiter);
5773                 }
5774
5775                 // Main encoding loop:
5776                 while (handledCPCount < inputLength) {
5777
5778                         // All non-basic code points < n have been handled already. Find the next
5779                         // larger one:
5780                         for (m = maxInt, j = 0; j < inputLength; ++j) {
5781                                 currentValue = input[j];
5782                                 if (currentValue >= n && currentValue < m) {
5783                                         m = currentValue;
5784                                 }
5785                         }
5786
5787                         // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
5788                         // but guard against overflow
5789                         handledCPCountPlusOne = handledCPCount + 1;
5790                         if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
5791                                 error('overflow');
5792                         }
5793
5794                         delta += (m - n) * handledCPCountPlusOne;
5795                         n = m;
5796
5797                         for (j = 0; j < inputLength; ++j) {
5798                                 currentValue = input[j];
5799
5800                                 if (currentValue < n && ++delta > maxInt) {
5801                                         error('overflow');
5802                                 }
5803
5804                                 if (currentValue == n) {
5805                                         // Represent delta as a generalized variable-length integer
5806                                         for (q = delta, k = base; /* no condition */; k += base) {
5807                                                 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
5808                                                 if (q < t) {
5809                                                         break;
5810                                                 }
5811                                                 qMinusT = q - t;
5812                                                 baseMinusT = base - t;
5813                                                 output.push(
5814                                                         stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
5815                                                 );
5816                                                 q = floor(qMinusT / baseMinusT);
5817                                         }
5818
5819                                         output.push(stringFromCharCode(digitToBasic(q, 0)));
5820                                         bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
5821                                         delta = 0;
5822                                         ++handledCPCount;
5823                                 }
5824                         }
5825
5826                         ++delta;
5827                         ++n;
5828
5829                 }
5830                 return output.join('');
5831         }
5832
5833         /**
5834          * Converts a Punycode string representing a domain name or an email address
5835          * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
5836          * it doesn't matter if you call it on a string that has already been
5837          * converted to Unicode.
5838          * @memberOf punycode
5839          * @param {String} input The Punycoded domain name or email address to
5840          * convert to Unicode.
5841          * @returns {String} The Unicode representation of the given Punycode
5842          * string.
5843          */
5844         function toUnicode(input) {
5845                 return mapDomain(input, function(string) {
5846                         return regexPunycode.test(string)
5847                                 ? decode(string.slice(4).toLowerCase())
5848                                 : string;
5849                 });
5850         }
5851
5852         /**
5853          * Converts a Unicode string representing a domain name or an email address to
5854          * Punycode. Only the non-ASCII parts of the domain name will be converted,
5855          * i.e. it doesn't matter if you call it with a domain that's already in
5856          * ASCII.
5857          * @memberOf punycode
5858          * @param {String} input The domain name or email address to convert, as a
5859          * Unicode string.
5860          * @returns {String} The Punycode representation of the given domain name or
5861          * email address.
5862          */
5863         function toASCII(input) {
5864                 return mapDomain(input, function(string) {
5865                         return regexNonASCII.test(string)
5866                                 ? 'xn--' + encode(string)
5867                                 : string;
5868                 });
5869         }
5870
5871         /*--------------------------------------------------------------------------*/
5872
5873         /** Define the public API */
5874         punycode = {
5875                 /**
5876                  * A string representing the current Punycode.js version number.
5877                  * @memberOf punycode
5878                  * @type String
5879                  */
5880                 'version': '1.4.1',
5881                 /**
5882                  * An object of methods to convert from JavaScript's internal character
5883                  * representation (UCS-2) to Unicode code points, and back.
5884                  * @see <https://mathiasbynens.be/notes/javascript-encoding>
5885                  * @memberOf punycode
5886                  * @type Object
5887                  */
5888                 'ucs2': {
5889                         'decode': ucs2decode,
5890                         'encode': ucs2encode
5891                 },
5892                 'decode': decode,
5893                 'encode': encode,
5894                 'toASCII': toASCII,
5895                 'toUnicode': toUnicode
5896         };
5897
5898         /** Expose `punycode` */
5899         // Some AMD build optimizers, like r.js, check for specific condition patterns
5900         // like the following:
5901         if (
5902                 typeof define == 'function' &&
5903                 typeof define.amd == 'object' &&
5904                 define.amd
5905         ) {
5906                 define('punycode', function() {
5907                         return punycode;
5908                 });
5909         } else if (freeExports && freeModule) {
5910                 if (module.exports == freeExports) {
5911                         // in Node.js, io.js, or RingoJS v0.8.0+
5912                         freeModule.exports = punycode;
5913                 } else {
5914                         // in Narwhal or RingoJS v0.7.0-
5915                         for (key in punycode) {
5916                                 punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
5917                         }
5918                 }
5919         } else {
5920                 // in Rhino or a web browser
5921                 root.punycode = punycode;
5922         }
5923
5924 }(this));
5925
5926 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5927 },{}],42:[function(require,module,exports){
5928 // Copyright Joyent, Inc. and other Node contributors.
5929 //
5930 // Permission is hereby granted, free of charge, to any person obtaining a
5931 // copy of this software and associated documentation files (the
5932 // "Software"), to deal in the Software without restriction, including
5933 // without limitation the rights to use, copy, modify, merge, publish,
5934 // distribute, sublicense, and/or sell copies of the Software, and to permit
5935 // persons to whom the Software is furnished to do so, subject to the
5936 // following conditions:
5937 //
5938 // The above copyright notice and this permission notice shall be included
5939 // in all copies or substantial portions of the Software.
5940 //
5941 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5942 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5943 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5944 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5945 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5946 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5947 // USE OR OTHER DEALINGS IN THE SOFTWARE.
5948
5949 'use strict';
5950
5951 // If obj.hasOwnProperty has been overridden, then calling
5952 // obj.hasOwnProperty(prop) will break.
5953 // See: https://github.com/joyent/node/issues/1707
5954 function hasOwnProperty(obj, prop) {
5955   return Object.prototype.hasOwnProperty.call(obj, prop);
5956 }
5957
5958 module.exports = function(qs, sep, eq, options) {
5959   sep = sep || '&';
5960   eq = eq || '=';
5961   var obj = {};
5962
5963   if (typeof qs !== 'string' || qs.length === 0) {
5964     return obj;
5965   }
5966
5967   var regexp = /\+/g;
5968   qs = qs.split(sep);
5969
5970   var maxKeys = 1000;
5971   if (options && typeof options.maxKeys === 'number') {
5972     maxKeys = options.maxKeys;
5973   }
5974
5975   var len = qs.length;
5976   // maxKeys <= 0 means that we should not limit keys count
5977   if (maxKeys > 0 && len > maxKeys) {
5978     len = maxKeys;
5979   }
5980
5981   for (var i = 0; i < len; ++i) {
5982     var x = qs[i].replace(regexp, '%20'),
5983         idx = x.indexOf(eq),
5984         kstr, vstr, k, v;
5985
5986     if (idx >= 0) {
5987       kstr = x.substr(0, idx);
5988       vstr = x.substr(idx + 1);
5989     } else {
5990       kstr = x;
5991       vstr = '';
5992     }
5993
5994     k = decodeURIComponent(kstr);
5995     v = decodeURIComponent(vstr);
5996
5997     if (!hasOwnProperty(obj, k)) {
5998       obj[k] = v;
5999     } else if (isArray(obj[k])) {
6000       obj[k].push(v);
6001     } else {
6002       obj[k] = [obj[k], v];
6003     }
6004   }
6005
6006   return obj;
6007 };
6008
6009 var isArray = Array.isArray || function (xs) {
6010   return Object.prototype.toString.call(xs) === '[object Array]';
6011 };
6012
6013 },{}],43:[function(require,module,exports){
6014 // Copyright Joyent, Inc. and other Node contributors.
6015 //
6016 // Permission is hereby granted, free of charge, to any person obtaining a
6017 // copy of this software and associated documentation files (the
6018 // "Software"), to deal in the Software without restriction, including
6019 // without limitation the rights to use, copy, modify, merge, publish,
6020 // distribute, sublicense, and/or sell copies of the Software, and to permit
6021 // persons to whom the Software is furnished to do so, subject to the
6022 // following conditions:
6023 //
6024 // The above copyright notice and this permission notice shall be included
6025 // in all copies or substantial portions of the Software.
6026 //
6027 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6028 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6029 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6030 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6031 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6032 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6033 // USE OR OTHER DEALINGS IN THE SOFTWARE.
6034
6035 'use strict';
6036
6037 var stringifyPrimitive = function(v) {
6038   switch (typeof v) {
6039     case 'string':
6040       return v;
6041
6042     case 'boolean':
6043       return v ? 'true' : 'false';
6044
6045     case 'number':
6046       return isFinite(v) ? v : '';
6047
6048     default:
6049       return '';
6050   }
6051 };
6052
6053 module.exports = function(obj, sep, eq, name) {
6054   sep = sep || '&';
6055   eq = eq || '=';
6056   if (obj === null) {
6057     obj = undefined;
6058   }
6059
6060   if (typeof obj === 'object') {
6061     return map(objectKeys(obj), function(k) {
6062       var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
6063       if (isArray(obj[k])) {
6064         return map(obj[k], function(v) {
6065           return ks + encodeURIComponent(stringifyPrimitive(v));
6066         }).join(sep);
6067       } else {
6068         return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
6069       }
6070     }).join(sep);
6071
6072   }
6073
6074   if (!name) return '';
6075   return encodeURIComponent(stringifyPrimitive(name)) + eq +
6076          encodeURIComponent(stringifyPrimitive(obj));
6077 };
6078
6079 var isArray = Array.isArray || function (xs) {
6080   return Object.prototype.toString.call(xs) === '[object Array]';
6081 };
6082
6083 function map (xs, f) {
6084   if (xs.map) return xs.map(f);
6085   var res = [];
6086   for (var i = 0; i < xs.length; i++) {
6087     res.push(f(xs[i], i));
6088   }
6089   return res;
6090 }
6091
6092 var objectKeys = Object.keys || function (obj) {
6093   var res = [];
6094   for (var key in obj) {
6095     if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
6096   }
6097   return res;
6098 };
6099
6100 },{}],44:[function(require,module,exports){
6101 'use strict';
6102
6103 exports.decode = exports.parse = require('./decode');
6104 exports.encode = exports.stringify = require('./encode');
6105
6106 },{"./decode":42,"./encode":43}],45:[function(require,module,exports){
6107 // Copyright Joyent, Inc. and other Node contributors.
6108 //
6109 // Permission is hereby granted, free of charge, to any person obtaining a
6110 // copy of this software and associated documentation files (the
6111 // "Software"), to deal in the Software without restriction, including
6112 // without limitation the rights to use, copy, modify, merge, publish,
6113 // distribute, sublicense, and/or sell copies of the Software, and to permit
6114 // persons to whom the Software is furnished to do so, subject to the
6115 // following conditions:
6116 //
6117 // The above copyright notice and this permission notice shall be included
6118 // in all copies or substantial portions of the Software.
6119 //
6120 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6121 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6122 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6123 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6124 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6125 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6126 // USE OR OTHER DEALINGS IN THE SOFTWARE.
6127
6128 'use strict';
6129
6130 var punycode = require('punycode');
6131 var util = require('./util');
6132
6133 exports.parse = urlParse;
6134 exports.resolve = urlResolve;
6135 exports.resolveObject = urlResolveObject;
6136 exports.format = urlFormat;
6137
6138 exports.Url = Url;
6139
6140 function Url() {
6141   this.protocol = null;
6142   this.slashes = null;
6143   this.auth = null;
6144   this.host = null;
6145   this.port = null;
6146   this.hostname = null;
6147   this.hash = null;
6148   this.search = null;
6149   this.query = null;
6150   this.pathname = null;
6151   this.path = null;
6152   this.href = null;
6153 }
6154
6155 // Reference: RFC 3986, RFC 1808, RFC 2396
6156
6157 // define these here so at least they only have to be
6158 // compiled once on the first module load.
6159 var protocolPattern = /^([a-z0-9.+-]+:)/i,
6160     portPattern = /:[0-9]*$/,
6161
6162     // Special case for a simple path URL
6163     simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
6164
6165     // RFC 2396: characters reserved for delimiting URLs.
6166     // We actually just auto-escape these.
6167     delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
6168
6169     // RFC 2396: characters not allowed for various reasons.
6170     unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
6171
6172     // Allowed by RFCs, but cause of XSS attacks.  Always escape these.
6173     autoEscape = ['\''].concat(unwise),
6174     // Characters that are never ever allowed in a hostname.
6175     // Note that any invalid chars are also handled, but these
6176     // are the ones that are *expected* to be seen, so we fast-path
6177     // them.
6178     nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
6179     hostEndingChars = ['/', '?', '#'],
6180     hostnameMaxLen = 255,
6181     hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
6182     hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
6183     // protocols that can allow "unsafe" and "unwise" chars.
6184     unsafeProtocol = {
6185       'javascript': true,
6186       'javascript:': true
6187     },
6188     // protocols that never have a hostname.
6189     hostlessProtocol = {
6190       'javascript': true,
6191       'javascript:': true
6192     },
6193     // protocols that always contain a // bit.
6194     slashedProtocol = {
6195       'http': true,
6196       'https': true,
6197       'ftp': true,
6198       'gopher': true,
6199       'file': true,
6200       'http:': true,
6201       'https:': true,
6202       'ftp:': true,
6203       'gopher:': true,
6204       'file:': true
6205     },
6206     querystring = require('querystring');
6207
6208 function urlParse(url, parseQueryString, slashesDenoteHost) {
6209   if (url && util.isObject(url) && url instanceof Url) return url;
6210
6211   var u = new Url;
6212   u.parse(url, parseQueryString, slashesDenoteHost);
6213   return u;
6214 }
6215
6216 Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
6217   if (!util.isString(url)) {
6218     throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
6219   }
6220
6221   // Copy chrome, IE, opera backslash-handling behavior.
6222   // Back slashes before the query string get converted to forward slashes
6223   // See: https://code.google.com/p/chromium/issues/detail?id=25916
6224   var queryIndex = url.indexOf('?'),
6225       splitter =
6226           (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
6227       uSplit = url.split(splitter),
6228       slashRegex = /\\/g;
6229   uSplit[0] = uSplit[0].replace(slashRegex, '/');
6230   url = uSplit.join(splitter);
6231
6232   var rest = url;
6233
6234   // trim before proceeding.
6235   // This is to support parse stuff like "  http://foo.com  \n"
6236   rest = rest.trim();
6237
6238   if (!slashesDenoteHost && url.split('#').length === 1) {
6239     // Try fast path regexp
6240     var simplePath = simplePathPattern.exec(rest);
6241     if (simplePath) {
6242       this.path = rest;
6243       this.href = rest;
6244       this.pathname = simplePath[1];
6245       if (simplePath[2]) {
6246         this.search = simplePath[2];
6247         if (parseQueryString) {
6248           this.query = querystring.parse(this.search.substr(1));
6249         } else {
6250           this.query = this.search.substr(1);
6251         }
6252       } else if (parseQueryString) {
6253         this.search = '';
6254         this.query = {};
6255       }
6256       return this;
6257     }
6258   }
6259
6260   var proto = protocolPattern.exec(rest);
6261   if (proto) {
6262     proto = proto[0];
6263     var lowerProto = proto.toLowerCase();
6264     this.protocol = lowerProto;
6265     rest = rest.substr(proto.length);
6266   }
6267
6268   // figure out if it's got a host
6269   // user@server is *always* interpreted as a hostname, and url
6270   // resolution will treat //foo/bar as host=foo,path=bar because that's
6271   // how the browser resolves relative URLs.
6272   if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
6273     var slashes = rest.substr(0, 2) === '//';
6274     if (slashes && !(proto && hostlessProtocol[proto])) {
6275       rest = rest.substr(2);
6276       this.slashes = true;
6277     }
6278   }
6279
6280   if (!hostlessProtocol[proto] &&
6281       (slashes || (proto && !slashedProtocol[proto]))) {
6282
6283     // there's a hostname.
6284     // the first instance of /, ?, ;, or # ends the host.
6285     //
6286     // If there is an @ in the hostname, then non-host chars *are* allowed
6287     // to the left of the last @ sign, unless some host-ending character
6288     // comes *before* the @-sign.
6289     // URLs are obnoxious.
6290     //
6291     // ex:
6292     // http://a@b@c/ => user:a@b host:c
6293     // http://a@b?@c => user:a host:c path:/?@c
6294
6295     // v0.12 TODO(isaacs): This is not quite how Chrome does things.
6296     // Review our test case against browsers more comprehensively.
6297
6298     // find the first instance of any hostEndingChars
6299     var hostEnd = -1;
6300     for (var i = 0; i < hostEndingChars.length; i++) {
6301       var hec = rest.indexOf(hostEndingChars[i]);
6302       if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
6303         hostEnd = hec;
6304     }
6305
6306     // at this point, either we have an explicit point where the
6307     // auth portion cannot go past, or the last @ char is the decider.
6308     var auth, atSign;
6309     if (hostEnd === -1) {
6310       // atSign can be anywhere.
6311       atSign = rest.lastIndexOf('@');
6312     } else {
6313       // atSign must be in auth portion.
6314       // http://a@b/c@d => host:b auth:a path:/c@d
6315       atSign = rest.lastIndexOf('@', hostEnd);
6316     }
6317
6318     // Now we have a portion which is definitely the auth.
6319     // Pull that off.
6320     if (atSign !== -1) {
6321       auth = rest.slice(0, atSign);
6322       rest = rest.slice(atSign + 1);
6323       this.auth = decodeURIComponent(auth);
6324     }
6325
6326     // the host is the remaining to the left of the first non-host char
6327     hostEnd = -1;
6328     for (var i = 0; i < nonHostChars.length; i++) {
6329       var hec = rest.indexOf(nonHostChars[i]);
6330       if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
6331         hostEnd = hec;
6332     }
6333     // if we still have not hit it, then the entire thing is a host.
6334     if (hostEnd === -1)
6335       hostEnd = rest.length;
6336
6337     this.host = rest.slice(0, hostEnd);
6338     rest = rest.slice(hostEnd);
6339
6340     // pull out port.
6341     this.parseHost();
6342
6343     // we've indicated that there is a hostname,
6344     // so even if it's empty, it has to be present.
6345     this.hostname = this.hostname || '';
6346
6347     // if hostname begins with [ and ends with ]
6348     // assume that it's an IPv6 address.
6349     var ipv6Hostname = this.hostname[0] === '[' &&
6350         this.hostname[this.hostname.length - 1] === ']';
6351
6352     // validate a little.
6353     if (!ipv6Hostname) {
6354       var hostparts = this.hostname.split(/\./);
6355       for (var i = 0, l = hostparts.length; i < l; i++) {
6356         var part = hostparts[i];
6357         if (!part) continue;
6358         if (!part.match(hostnamePartPattern)) {
6359           var newpart = '';
6360           for (var j = 0, k = part.length; j < k; j++) {
6361             if (part.charCodeAt(j) > 127) {
6362               // we replace non-ASCII char with a temporary placeholder
6363               // we need this to make sure size of hostname is not
6364               // broken by replacing non-ASCII by nothing
6365               newpart += 'x';
6366             } else {
6367               newpart += part[j];
6368             }
6369           }
6370           // we test again with ASCII char only
6371           if (!newpart.match(hostnamePartPattern)) {
6372             var validParts = hostparts.slice(0, i);
6373             var notHost = hostparts.slice(i + 1);
6374             var bit = part.match(hostnamePartStart);
6375             if (bit) {
6376               validParts.push(bit[1]);
6377               notHost.unshift(bit[2]);
6378             }
6379             if (notHost.length) {
6380               rest = '/' + notHost.join('.') + rest;
6381             }
6382             this.hostname = validParts.join('.');
6383             break;
6384           }
6385         }
6386       }
6387     }
6388
6389     if (this.hostname.length > hostnameMaxLen) {
6390       this.hostname = '';
6391     } else {
6392       // hostnames are always lower case.
6393       this.hostname = this.hostname.toLowerCase();
6394     }
6395
6396     if (!ipv6Hostname) {
6397       // IDNA Support: Returns a punycoded representation of "domain".
6398       // It only converts parts of the domain name that
6399       // have non-ASCII characters, i.e. it doesn't matter if
6400       // you call it with a domain that already is ASCII-only.
6401       this.hostname = punycode.toASCII(this.hostname);
6402     }
6403
6404     var p = this.port ? ':' + this.port : '';
6405     var h = this.hostname || '';
6406     this.host = h + p;
6407     this.href += this.host;
6408
6409     // strip [ and ] from the hostname
6410     // the host field still retains them, though
6411     if (ipv6Hostname) {
6412       this.hostname = this.hostname.substr(1, this.hostname.length - 2);
6413       if (rest[0] !== '/') {
6414         rest = '/' + rest;
6415       }
6416     }
6417   }
6418
6419   // now rest is set to the post-host stuff.
6420   // chop off any delim chars.
6421   if (!unsafeProtocol[lowerProto]) {
6422
6423     // First, make 100% sure that any "autoEscape" chars get
6424     // escaped, even if encodeURIComponent doesn't think they
6425     // need to be.
6426     for (var i = 0, l = autoEscape.length; i < l; i++) {
6427       var ae = autoEscape[i];
6428       if (rest.indexOf(ae) === -1)
6429         continue;
6430       var esc = encodeURIComponent(ae);
6431       if (esc === ae) {
6432         esc = escape(ae);
6433       }
6434       rest = rest.split(ae).join(esc);
6435     }
6436   }
6437
6438
6439   // chop off from the tail first.
6440   var hash = rest.indexOf('#');
6441   if (hash !== -1) {
6442     // got a fragment string.
6443     this.hash = rest.substr(hash);
6444     rest = rest.slice(0, hash);
6445   }
6446   var qm = rest.indexOf('?');
6447   if (qm !== -1) {
6448     this.search = rest.substr(qm);
6449     this.query = rest.substr(qm + 1);
6450     if (parseQueryString) {
6451       this.query = querystring.parse(this.query);
6452     }
6453     rest = rest.slice(0, qm);
6454   } else if (parseQueryString) {
6455     // no query string, but parseQueryString still requested
6456     this.search = '';
6457     this.query = {};
6458   }
6459   if (rest) this.pathname = rest;
6460   if (slashedProtocol[lowerProto] &&
6461       this.hostname && !this.pathname) {
6462     this.pathname = '/';
6463   }
6464
6465   //to support http.request
6466   if (this.pathname || this.search) {
6467     var p = this.pathname || '';
6468     var s = this.search || '';
6469     this.path = p + s;
6470   }
6471
6472   // finally, reconstruct the href based on what has been validated.
6473   this.href = this.format();
6474   return this;
6475 };
6476
6477 // format a parsed object into a url string
6478 function urlFormat(obj) {
6479   // ensure it's an object, and not a string url.
6480   // If it's an obj, this is a no-op.
6481   // this way, you can call url_format() on strings
6482   // to clean up potentially wonky urls.
6483   if (util.isString(obj)) obj = urlParse(obj);
6484   if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
6485   return obj.format();
6486 }
6487
6488 Url.prototype.format = function() {
6489   var auth = this.auth || '';
6490   if (auth) {
6491     auth = encodeURIComponent(auth);
6492     auth = auth.replace(/%3A/i, ':');
6493     auth += '@';
6494   }
6495
6496   var protocol = this.protocol || '',
6497       pathname = this.pathname || '',
6498       hash = this.hash || '',
6499       host = false,
6500       query = '';
6501
6502   if (this.host) {
6503     host = auth + this.host;
6504   } else if (this.hostname) {
6505     host = auth + (this.hostname.indexOf(':') === -1 ?
6506         this.hostname :
6507         '[' + this.hostname + ']');
6508     if (this.port) {
6509       host += ':' + this.port;
6510     }
6511   }
6512
6513   if (this.query &&
6514       util.isObject(this.query) &&
6515       Object.keys(this.query).length) {
6516     query = querystring.stringify(this.query);
6517   }
6518
6519   var search = this.search || (query && ('?' + query)) || '';
6520
6521   if (protocol && protocol.substr(-1) !== ':') protocol += ':';
6522
6523   // only the slashedProtocols get the //.  Not mailto:, xmpp:, etc.
6524   // unless they had them to begin with.
6525   if (this.slashes ||
6526       (!protocol || slashedProtocol[protocol]) && host !== false) {
6527     host = '//' + (host || '');
6528     if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
6529   } else if (!host) {
6530     host = '';
6531   }
6532
6533   if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
6534   if (search && search.charAt(0) !== '?') search = '?' + search;
6535
6536   pathname = pathname.replace(/[?#]/g, function(match) {
6537     return encodeURIComponent(match);
6538   });
6539   search = search.replace('#', '%23');
6540
6541   return protocol + host + pathname + search + hash;
6542 };
6543
6544 function urlResolve(source, relative) {
6545   return urlParse(source, false, true).resolve(relative);
6546 }
6547
6548 Url.prototype.resolve = function(relative) {
6549   return this.resolveObject(urlParse(relative, false, true)).format();
6550 };
6551
6552 function urlResolveObject(source, relative) {
6553   if (!source) return relative;
6554   return urlParse(source, false, true).resolveObject(relative);
6555 }
6556
6557 Url.prototype.resolveObject = function(relative) {
6558   if (util.isString(relative)) {
6559     var rel = new Url();
6560     rel.parse(relative, false, true);
6561     relative = rel;
6562   }
6563
6564   var result = new Url();
6565   var tkeys = Object.keys(this);
6566   for (var tk = 0; tk < tkeys.length; tk++) {
6567     var tkey = tkeys[tk];
6568     result[tkey] = this[tkey];
6569   }
6570
6571   // hash is always overridden, no matter what.
6572   // even href="" will remove it.
6573   result.hash = relative.hash;
6574
6575   // if the relative url is empty, then there's nothing left to do here.
6576   if (relative.href === '') {
6577     result.href = result.format();
6578     return result;
6579   }
6580
6581   // hrefs like //foo/bar always cut to the protocol.
6582   if (relative.slashes && !relative.protocol) {
6583     // take everything except the protocol from relative
6584     var rkeys = Object.keys(relative);
6585     for (var rk = 0; rk < rkeys.length; rk++) {
6586       var rkey = rkeys[rk];
6587       if (rkey !== 'protocol')
6588         result[rkey] = relative[rkey];
6589     }
6590
6591     //urlParse appends trailing / to urls like http://www.example.com
6592     if (slashedProtocol[result.protocol] &&
6593         result.hostname && !result.pathname) {
6594       result.path = result.pathname = '/';
6595     }
6596
6597     result.href = result.format();
6598     return result;
6599   }
6600
6601   if (relative.protocol && relative.protocol !== result.protocol) {
6602     // if it's a known url protocol, then changing
6603     // the protocol does weird things
6604     // first, if it's not file:, then we MUST have a host,
6605     // and if there was a path
6606     // to begin with, then we MUST have a path.
6607     // if it is file:, then the host is dropped,
6608     // because that's known to be hostless.
6609     // anything else is assumed to be absolute.
6610     if (!slashedProtocol[relative.protocol]) {
6611       var keys = Object.keys(relative);
6612       for (var v = 0; v < keys.length; v++) {
6613         var k = keys[v];
6614         result[k] = relative[k];
6615       }
6616       result.href = result.format();
6617       return result;
6618     }
6619
6620     result.protocol = relative.protocol;
6621     if (!relative.host && !hostlessProtocol[relative.protocol]) {
6622       var relPath = (relative.pathname || '').split('/');
6623       while (relPath.length && !(relative.host = relPath.shift()));
6624       if (!relative.host) relative.host = '';
6625       if (!relative.hostname) relative.hostname = '';
6626       if (relPath[0] !== '') relPath.unshift('');
6627       if (relPath.length < 2) relPath.unshift('');
6628       result.pathname = relPath.join('/');
6629     } else {
6630       result.pathname = relative.pathname;
6631     }
6632     result.search = relative.search;
6633     result.query = relative.query;
6634     result.host = relative.host || '';
6635     result.auth = relative.auth;
6636     result.hostname = relative.hostname || relative.host;
6637     result.port = relative.port;
6638     // to support http.request
6639     if (result.pathname || result.search) {
6640       var p = result.pathname || '';
6641       var s = result.search || '';
6642       result.path = p + s;
6643     }
6644     result.slashes = result.slashes || relative.slashes;
6645     result.href = result.format();
6646     return result;
6647   }
6648
6649   var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
6650       isRelAbs = (
6651           relative.host ||
6652           relative.pathname && relative.pathname.charAt(0) === '/'
6653       ),
6654       mustEndAbs = (isRelAbs || isSourceAbs ||
6655                     (result.host && relative.pathname)),
6656       removeAllDots = mustEndAbs,
6657       srcPath = result.pathname && result.pathname.split('/') || [],
6658       relPath = relative.pathname && relative.pathname.split('/') || [],
6659       psychotic = result.protocol && !slashedProtocol[result.protocol];
6660
6661   // if the url is a non-slashed url, then relative
6662   // links like ../.. should be able
6663   // to crawl up to the hostname, as well.  This is strange.
6664   // result.protocol has already been set by now.
6665   // Later on, put the first path part into the host field.
6666   if (psychotic) {
6667     result.hostname = '';
6668     result.port = null;
6669     if (result.host) {
6670       if (srcPath[0] === '') srcPath[0] = result.host;
6671       else srcPath.unshift(result.host);
6672     }
6673     result.host = '';
6674     if (relative.protocol) {
6675       relative.hostname = null;
6676       relative.port = null;
6677       if (relative.host) {
6678         if (relPath[0] === '') relPath[0] = relative.host;
6679         else relPath.unshift(relative.host);
6680       }
6681       relative.host = null;
6682     }
6683     mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
6684   }
6685
6686   if (isRelAbs) {
6687     // it's absolute.
6688     result.host = (relative.host || relative.host === '') ?
6689                   relative.host : result.host;
6690     result.hostname = (relative.hostname || relative.hostname === '') ?
6691                       relative.hostname : result.hostname;
6692     result.search = relative.search;
6693     result.query = relative.query;
6694     srcPath = relPath;
6695     // fall through to the dot-handling below.
6696   } else if (relPath.length) {
6697     // it's relative
6698     // throw away the existing file, and take the new path instead.
6699     if (!srcPath) srcPath = [];
6700     srcPath.pop();
6701     srcPath = srcPath.concat(relPath);
6702     result.search = relative.search;
6703     result.query = relative.query;
6704   } else if (!util.isNullOrUndefined(relative.search)) {
6705     // just pull out the search.
6706     // like href='?foo'.
6707     // Put this after the other two cases because it simplifies the booleans
6708     if (psychotic) {
6709       result.hostname = result.host = srcPath.shift();
6710       //occationaly the auth can get stuck only in host
6711       //this especially happens in cases like
6712       //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
6713       var authInHost = result.host && result.host.indexOf('@') > 0 ?
6714                        result.host.split('@') : false;
6715       if (authInHost) {
6716         result.auth = authInHost.shift();
6717         result.host = result.hostname = authInHost.shift();
6718       }
6719     }
6720     result.search = relative.search;
6721     result.query = relative.query;
6722     //to support http.request
6723     if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
6724       result.path = (result.pathname ? result.pathname : '') +
6725                     (result.search ? result.search : '');
6726     }
6727     result.href = result.format();
6728     return result;
6729   }
6730
6731   if (!srcPath.length) {
6732     // no path at all.  easy.
6733     // we've already handled the other stuff above.
6734     result.pathname = null;
6735     //to support http.request
6736     if (result.search) {
6737       result.path = '/' + result.search;
6738     } else {
6739       result.path = null;
6740     }
6741     result.href = result.format();
6742     return result;
6743   }
6744
6745   // if a url ENDs in . or .., then it must get a trailing slash.
6746   // however, if it ends in anything else non-slashy,
6747   // then it must NOT get a trailing slash.
6748   var last = srcPath.slice(-1)[0];
6749   var hasTrailingSlash = (
6750       (result.host || relative.host || srcPath.length > 1) &&
6751       (last === '.' || last === '..') || last === '');
6752
6753   // strip single dots, resolve double dots to parent dir
6754   // if the path tries to go above the root, `up` ends up > 0
6755   var up = 0;
6756   for (var i = srcPath.length; i >= 0; i--) {
6757     last = srcPath[i];
6758     if (last === '.') {
6759       srcPath.splice(i, 1);
6760     } else if (last === '..') {
6761       srcPath.splice(i, 1);
6762       up++;
6763     } else if (up) {
6764       srcPath.splice(i, 1);
6765       up--;
6766     }
6767   }
6768
6769   // if the path is allowed to go above the root, restore leading ..s
6770   if (!mustEndAbs && !removeAllDots) {
6771     for (; up--; up) {
6772       srcPath.unshift('..');
6773     }
6774   }
6775
6776   if (mustEndAbs && srcPath[0] !== '' &&
6777       (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
6778     srcPath.unshift('');
6779   }
6780
6781   if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
6782     srcPath.push('');
6783   }
6784
6785   var isAbsolute = srcPath[0] === '' ||
6786       (srcPath[0] && srcPath[0].charAt(0) === '/');
6787
6788   // put the host back
6789   if (psychotic) {
6790     result.hostname = result.host = isAbsolute ? '' :
6791                                     srcPath.length ? srcPath.shift() : '';
6792     //occationaly the auth can get stuck only in host
6793     //this especially happens in cases like
6794     //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
6795     var authInHost = result.host && result.host.indexOf('@') > 0 ?
6796                      result.host.split('@') : false;
6797     if (authInHost) {
6798       result.auth = authInHost.shift();
6799       result.host = result.hostname = authInHost.shift();
6800     }
6801   }
6802
6803   mustEndAbs = mustEndAbs || (result.host && srcPath.length);
6804
6805   if (mustEndAbs && !isAbsolute) {
6806     srcPath.unshift('');
6807   }
6808
6809   if (!srcPath.length) {
6810     result.pathname = null;
6811     result.path = null;
6812   } else {
6813     result.pathname = srcPath.join('/');
6814   }
6815
6816   //to support request.http
6817   if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
6818     result.path = (result.pathname ? result.pathname : '') +
6819                   (result.search ? result.search : '');
6820   }
6821   result.auth = relative.auth || result.auth;
6822   result.slashes = result.slashes || relative.slashes;
6823   result.href = result.format();
6824   return result;
6825 };
6826
6827 Url.prototype.parseHost = function() {
6828   var host = this.host;
6829   var port = portPattern.exec(host);
6830   if (port) {
6831     port = port[0];
6832     if (port !== ':') {
6833       this.port = port.substr(1);
6834     }
6835     host = host.substr(0, host.length - port.length);
6836   }
6837   if (host) this.hostname = host;
6838 };
6839
6840 },{"./util":46,"punycode":41,"querystring":44}],46:[function(require,module,exports){
6841 'use strict';
6842
6843 module.exports = {
6844   isString: function(arg) {
6845     return typeof(arg) === 'string';
6846   },
6847   isObject: function(arg) {
6848     return typeof(arg) === 'object' && arg !== null;
6849   },
6850   isNull: function(arg) {
6851     return arg === null;
6852   },
6853   isNullOrUndefined: function(arg) {
6854     return arg == null;
6855   }
6856 };
6857
6858 },{}],47:[function(require,module,exports){
6859
6860 /**
6861  * slice() reference.
6862  */
6863
6864 var slice = Array.prototype.slice;
6865
6866 /**
6867  * Expose `co`.
6868  */
6869
6870 module.exports = co['default'] = co.co = co;
6871
6872 /**
6873  * Wrap the given generator `fn` into a
6874  * function that returns a promise.
6875  * This is a separate function so that
6876  * every `co()` call doesn't create a new,
6877  * unnecessary closure.
6878  *
6879  * @param {GeneratorFunction} fn
6880  * @return {Function}
6881  * @api public
6882  */
6883
6884 co.wrap = function (fn) {
6885   createPromise.__generatorFunction__ = fn;
6886   return createPromise;
6887   function createPromise() {
6888     return co.call(this, fn.apply(this, arguments));
6889   }
6890 };
6891
6892 /**
6893  * Execute the generator function or a generator
6894  * and return a promise.
6895  *
6896  * @param {Function} fn
6897  * @return {Promise}
6898  * @api public
6899  */
6900
6901 function co(gen) {
6902   var ctx = this;
6903   var args = slice.call(arguments, 1)
6904
6905   // we wrap everything in a promise to avoid promise chaining,
6906   // which leads to memory leak errors.
6907   // see https://github.com/tj/co/issues/180
6908   return new Promise(function(resolve, reject) {
6909     if (typeof gen === 'function') gen = gen.apply(ctx, args);
6910     if (!gen || typeof gen.next !== 'function') return resolve(gen);
6911
6912     onFulfilled();
6913
6914     /**
6915      * @param {Mixed} res
6916      * @return {Promise}
6917      * @api private
6918      */
6919
6920     function onFulfilled(res) {
6921       var ret;
6922       try {
6923         ret = gen.next(res);
6924       } catch (e) {
6925         return reject(e);
6926       }
6927       next(ret);
6928     }
6929
6930     /**
6931      * @param {Error} err
6932      * @return {Promise}
6933      * @api private
6934      */
6935
6936     function onRejected(err) {
6937       var ret;
6938       try {
6939         ret = gen.throw(err);
6940       } catch (e) {
6941         return reject(e);
6942       }
6943       next(ret);
6944     }
6945
6946     /**
6947      * Get the next value in the generator,
6948      * return a promise.
6949      *
6950      * @param {Object} ret
6951      * @return {Promise}
6952      * @api private
6953      */
6954
6955     function next(ret) {
6956       if (ret.done) return resolve(ret.value);
6957       var value = toPromise.call(ctx, ret.value);
6958       if (value && isPromise(value)) return value.then(onFulfilled, onRejected);
6959       return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, '
6960         + 'but the following object was passed: "' + String(ret.value) + '"'));
6961     }
6962   });
6963 }
6964
6965 /**
6966  * Convert a `yield`ed value into a promise.
6967  *
6968  * @param {Mixed} obj
6969  * @return {Promise}
6970  * @api private
6971  */
6972
6973 function toPromise(obj) {
6974   if (!obj) return obj;
6975   if (isPromise(obj)) return obj;
6976   if (isGeneratorFunction(obj) || isGenerator(obj)) return co.call(this, obj);
6977   if ('function' == typeof obj) return thunkToPromise.call(this, obj);
6978   if (Array.isArray(obj)) return arrayToPromise.call(this, obj);
6979   if (isObject(obj)) return objectToPromise.call(this, obj);
6980   return obj;
6981 }
6982
6983 /**
6984  * Convert a thunk to a promise.
6985  *
6986  * @param {Function}
6987  * @return {Promise}
6988  * @api private
6989  */
6990
6991 function thunkToPromise(fn) {
6992   var ctx = this;
6993   return new Promise(function (resolve, reject) {
6994     fn.call(ctx, function (err, res) {
6995       if (err) return reject(err);
6996       if (arguments.length > 2) res = slice.call(arguments, 1);
6997       resolve(res);
6998     });
6999   });
7000 }
7001
7002 /**
7003  * Convert an array of "yieldables" to a promise.
7004  * Uses `Promise.all()` internally.
7005  *
7006  * @param {Array} obj
7007  * @return {Promise}
7008  * @api private
7009  */
7010
7011 function arrayToPromise(obj) {
7012   return Promise.all(obj.map(toPromise, this));
7013 }
7014
7015 /**
7016  * Convert an object of "yieldables" to a promise.
7017  * Uses `Promise.all()` internally.
7018  *
7019  * @param {Object} obj
7020  * @return {Promise}
7021  * @api private
7022  */
7023
7024 function objectToPromise(obj){
7025   var results = new obj.constructor();
7026   var keys = Object.keys(obj);
7027   var promises = [];
7028   for (var i = 0; i < keys.length; i++) {
7029     var key = keys[i];
7030     var promise = toPromise.call(this, obj[key]);
7031     if (promise && isPromise(promise)) defer(promise, key);
7032     else results[key] = obj[key];
7033   }
7034   return Promise.all(promises).then(function () {
7035     return results;
7036   });
7037
7038   function defer(promise, key) {
7039     // predefine the key in the result
7040     results[key] = undefined;
7041     promises.push(promise.then(function (res) {
7042       results[key] = res;
7043     }));
7044   }
7045 }
7046
7047 /**
7048  * Check if `obj` is a promise.
7049  *
7050  * @param {Object} obj
7051  * @return {Boolean}
7052  * @api private
7053  */
7054
7055 function isPromise(obj) {
7056   return 'function' == typeof obj.then;
7057 }
7058
7059 /**
7060  * Check if `obj` is a generator.
7061  *
7062  * @param {Mixed} obj
7063  * @return {Boolean}
7064  * @api private
7065  */
7066
7067 function isGenerator(obj) {
7068   return 'function' == typeof obj.next && 'function' == typeof obj.throw;
7069 }
7070
7071 /**
7072  * Check if `obj` is a generator function.
7073  *
7074  * @param {Mixed} obj
7075  * @return {Boolean}
7076  * @api private
7077  */
7078 function isGeneratorFunction(obj) {
7079   var constructor = obj.constructor;
7080   if (!constructor) return false;
7081   if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true;
7082   return isGenerator(constructor.prototype);
7083 }
7084
7085 /**
7086  * Check for plain object.
7087  *
7088  * @param {Mixed} val
7089  * @return {Boolean}
7090  * @api private
7091  */
7092
7093 function isObject(val) {
7094   return Object == val.constructor;
7095 }
7096
7097 },{}],48:[function(require,module,exports){
7098 var json = typeof JSON !== 'undefined' ? JSON : require('jsonify');
7099
7100 module.exports = function (obj, opts) {
7101     if (!opts) opts = {};
7102     if (typeof opts === 'function') opts = { cmp: opts };
7103     var space = opts.space || '';
7104     if (typeof space === 'number') space = Array(space+1).join(' ');
7105     var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
7106     var replacer = opts.replacer || function(key, value) { return value; };
7107
7108     var cmp = opts.cmp && (function (f) {
7109         return function (node) {
7110             return function (a, b) {
7111                 var aobj = { key: a, value: node[a] };
7112                 var bobj = { key: b, value: node[b] };
7113                 return f(aobj, bobj);
7114             };
7115         };
7116     })(opts.cmp);
7117
7118     var seen = [];
7119     return (function stringify (parent, key, node, level) {
7120         var indent = space ? ('\n' + new Array(level + 1).join(space)) : '';
7121         var colonSeparator = space ? ': ' : ':';
7122
7123         if (node && node.toJSON && typeof node.toJSON === 'function') {
7124             node = node.toJSON();
7125         }
7126
7127         node = replacer.call(parent, key, node);
7128
7129         if (node === undefined) {
7130             return;
7131         }
7132         if (typeof node !== 'object' || node === null) {
7133             return json.stringify(node);
7134         }
7135         if (isArray(node)) {
7136             var out = [];
7137             for (var i = 0; i < node.length; i++) {
7138                 var item = stringify(node, i, node[i], level+1) || json.stringify(null);
7139                 out.push(indent + space + item);
7140             }
7141             return '[' + out.join(',') + indent + ']';
7142         }
7143         else {
7144             if (seen.indexOf(node) !== -1) {
7145                 if (cycles) return json.stringify('__cycle__');
7146                 throw new TypeError('Converting circular structure to JSON');
7147             }
7148             else seen.push(node);
7149
7150             var keys = objectKeys(node).sort(cmp && cmp(node));
7151             var out = [];
7152             for (var i = 0; i < keys.length; i++) {
7153                 var key = keys[i];
7154                 var value = stringify(node, key, node[key], level+1);
7155
7156                 if(!value) continue;
7157
7158                 var keyValue = json.stringify(key)
7159                     + colonSeparator
7160                     + value;
7161                 ;
7162                 out.push(indent + space + keyValue);
7163             }
7164             seen.splice(seen.indexOf(node), 1);
7165             return '{' + out.join(',') + indent + '}';
7166         }
7167     })({ '': obj }, '', obj, 0);
7168 };
7169
7170 var isArray = Array.isArray || function (x) {
7171     return {}.toString.call(x) === '[object Array]';
7172 };
7173
7174 var objectKeys = Object.keys || function (obj) {
7175     var has = Object.prototype.hasOwnProperty || function () { return true };
7176     var keys = [];
7177     for (var key in obj) {
7178         if (has.call(obj, key)) keys.push(key);
7179     }
7180     return keys;
7181 };
7182
7183 },{"jsonify":49}],49:[function(require,module,exports){
7184 exports.parse = require('./lib/parse');
7185 exports.stringify = require('./lib/stringify');
7186
7187 },{"./lib/parse":50,"./lib/stringify":51}],50:[function(require,module,exports){
7188 var at, // The index of the current character
7189     ch, // The current character
7190     escapee = {
7191         '"':  '"',
7192         '\\': '\\',
7193         '/':  '/',
7194         b:    '\b',
7195         f:    '\f',
7196         n:    '\n',
7197         r:    '\r',
7198         t:    '\t'
7199     },
7200     text,
7201
7202     error = function (m) {
7203         // Call error when something is wrong.
7204         throw {
7205             name:    'SyntaxError',
7206             message: m,
7207             at:      at,
7208             text:    text
7209         };
7210     },
7211     
7212     next = function (c) {
7213         // If a c parameter is provided, verify that it matches the current character.
7214         if (c && c !== ch) {
7215             error("Expected '" + c + "' instead of '" + ch + "'");
7216         }
7217         
7218         // Get the next character. When there are no more characters,
7219         // return the empty string.
7220         
7221         ch = text.charAt(at);
7222         at += 1;
7223         return ch;
7224     },
7225     
7226     number = function () {
7227         // Parse a number value.
7228         var number,
7229             string = '';
7230         
7231         if (ch === '-') {
7232             string = '-';
7233             next('-');
7234         }
7235         while (ch >= '0' && ch <= '9') {
7236             string += ch;
7237             next();
7238         }
7239         if (ch === '.') {
7240             string += '.';
7241             while (next() && ch >= '0' && ch <= '9') {
7242                 string += ch;
7243             }
7244         }
7245         if (ch === 'e' || ch === 'E') {
7246             string += ch;
7247             next();
7248             if (ch === '-' || ch === '+') {
7249                 string += ch;
7250                 next();
7251             }
7252             while (ch >= '0' && ch <= '9') {
7253                 string += ch;
7254                 next();
7255             }
7256         }
7257         number = +string;
7258         if (!isFinite(number)) {
7259             error("Bad number");
7260         } else {
7261             return number;
7262         }
7263     },
7264     
7265     string = function () {
7266         // Parse a string value.
7267         var hex,
7268             i,
7269             string = '',
7270             uffff;
7271         
7272         // When parsing for string values, we must look for " and \ characters.
7273         if (ch === '"') {
7274             while (next()) {
7275                 if (ch === '"') {
7276                     next();
7277                     return string;
7278                 } else if (ch === '\\') {
7279                     next();
7280                     if (ch === 'u') {
7281                         uffff = 0;
7282                         for (i = 0; i < 4; i += 1) {
7283                             hex = parseInt(next(), 16);
7284                             if (!isFinite(hex)) {
7285                                 break;
7286                             }
7287                             uffff = uffff * 16 + hex;
7288                         }
7289                         string += String.fromCharCode(uffff);
7290                     } else if (typeof escapee[ch] === 'string') {
7291                         string += escapee[ch];
7292                     } else {
7293                         break;
7294                     }
7295                 } else {
7296                     string += ch;
7297                 }
7298             }
7299         }
7300         error("Bad string");
7301     },
7302
7303     white = function () {
7304
7305 // Skip whitespace.
7306
7307         while (ch && ch <= ' ') {
7308             next();
7309         }
7310     },
7311
7312     word = function () {
7313
7314 // true, false, or null.
7315
7316         switch (ch) {
7317         case 't':
7318             next('t');
7319             next('r');
7320             next('u');
7321             next('e');
7322             return true;
7323         case 'f':
7324             next('f');
7325             next('a');
7326             next('l');
7327             next('s');
7328             next('e');
7329             return false;
7330         case 'n':
7331             next('n');
7332             next('u');
7333             next('l');
7334             next('l');
7335             return null;
7336         }
7337         error("Unexpected '" + ch + "'");
7338     },
7339
7340     value,  // Place holder for the value function.
7341
7342     array = function () {
7343
7344 // Parse an array value.
7345
7346         var array = [];
7347
7348         if (ch === '[') {
7349             next('[');
7350             white();
7351             if (ch === ']') {
7352                 next(']');
7353                 return array;   // empty array
7354             }
7355             while (ch) {
7356                 array.push(value());
7357                 white();
7358                 if (ch === ']') {
7359                     next(']');
7360                     return array;
7361                 }
7362                 next(',');
7363                 white();
7364             }
7365         }
7366         error("Bad array");
7367     },
7368
7369     object = function () {
7370
7371 // Parse an object value.
7372
7373         var key,
7374             object = {};
7375
7376         if (ch === '{') {
7377             next('{');
7378             white();
7379             if (ch === '}') {
7380                 next('}');
7381                 return object;   // empty object
7382             }
7383             while (ch) {
7384                 key = string();
7385                 white();
7386                 next(':');
7387                 if (Object.hasOwnProperty.call(object, key)) {
7388                     error('Duplicate key "' + key + '"');
7389                 }
7390                 object[key] = value();
7391                 white();
7392                 if (ch === '}') {
7393                     next('}');
7394                     return object;
7395                 }
7396                 next(',');
7397                 white();
7398             }
7399         }
7400         error("Bad object");
7401     };
7402
7403 value = function () {
7404
7405 // Parse a JSON value. It could be an object, an array, a string, a number,
7406 // or a word.
7407
7408     white();
7409     switch (ch) {
7410     case '{':
7411         return object();
7412     case '[':
7413         return array();
7414     case '"':
7415         return string();
7416     case '-':
7417         return number();
7418     default:
7419         return ch >= '0' && ch <= '9' ? number() : word();
7420     }
7421 };
7422
7423 // Return the json_parse function. It will have access to all of the above
7424 // functions and variables.
7425
7426 module.exports = function (source, reviver) {
7427     var result;
7428     
7429     text = source;
7430     at = 0;
7431     ch = ' ';
7432     result = value();
7433     white();
7434     if (ch) {
7435         error("Syntax error");
7436     }
7437
7438     // If there is a reviver function, we recursively walk the new structure,
7439     // passing each name/value pair to the reviver function for possible
7440     // transformation, starting with a temporary root object that holds the result
7441     // in an empty key. If there is not a reviver function, we simply return the
7442     // result.
7443
7444     return typeof reviver === 'function' ? (function walk(holder, key) {
7445         var k, v, value = holder[key];
7446         if (value && typeof value === 'object') {
7447             for (k in value) {
7448                 if (Object.prototype.hasOwnProperty.call(value, k)) {
7449                     v = walk(value, k);
7450                     if (v !== undefined) {
7451                         value[k] = v;
7452                     } else {
7453                         delete value[k];
7454                     }
7455                 }
7456             }
7457         }
7458         return reviver.call(holder, key, value);
7459     }({'': result}, '')) : result;
7460 };
7461
7462 },{}],51:[function(require,module,exports){
7463 var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
7464     escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
7465     gap,
7466     indent,
7467     meta = {    // table of character substitutions
7468         '\b': '\\b',
7469         '\t': '\\t',
7470         '\n': '\\n',
7471         '\f': '\\f',
7472         '\r': '\\r',
7473         '"' : '\\"',
7474         '\\': '\\\\'
7475     },
7476     rep;
7477
7478 function quote(string) {
7479     // If the string contains no control characters, no quote characters, and no
7480     // backslash characters, then we can safely slap some quotes around it.
7481     // Otherwise we must also replace the offending characters with safe escape
7482     // sequences.
7483     
7484     escapable.lastIndex = 0;
7485     return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
7486         var c = meta[a];
7487         return typeof c === 'string' ? c :
7488             '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
7489     }) + '"' : '"' + string + '"';
7490 }
7491
7492 function str(key, holder) {
7493     // Produce a string from holder[key].
7494     var i,          // The loop counter.
7495         k,          // The member key.
7496         v,          // The member value.
7497         length,
7498         mind = gap,
7499         partial,
7500         value = holder[key];
7501     
7502     // If the value has a toJSON method, call it to obtain a replacement value.
7503     if (value && typeof value === 'object' &&
7504             typeof value.toJSON === 'function') {
7505         value = value.toJSON(key);
7506     }
7507     
7508     // If we were called with a replacer function, then call the replacer to
7509     // obtain a replacement value.
7510     if (typeof rep === 'function') {
7511         value = rep.call(holder, key, value);
7512     }
7513     
7514     // What happens next depends on the value's type.
7515     switch (typeof value) {
7516         case 'string':
7517             return quote(value);
7518         
7519         case 'number':
7520             // JSON numbers must be finite. Encode non-finite numbers as null.
7521             return isFinite(value) ? String(value) : 'null';
7522         
7523         case 'boolean':
7524         case 'null':
7525             // If the value is a boolean or null, convert it to a string. Note:
7526             // typeof null does not produce 'null'. The case is included here in
7527             // the remote chance that this gets fixed someday.
7528             return String(value);
7529             
7530         case 'object':
7531             if (!value) return 'null';
7532             gap += indent;
7533             partial = [];
7534             
7535             // Array.isArray
7536             if (Object.prototype.toString.apply(value) === '[object Array]') {
7537                 length = value.length;
7538                 for (i = 0; i < length; i += 1) {
7539                     partial[i] = str(i, value) || 'null';
7540                 }
7541                 
7542                 // Join all of the elements together, separated with commas, and
7543                 // wrap them in brackets.
7544                 v = partial.length === 0 ? '[]' : gap ?
7545                     '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
7546                     '[' + partial.join(',') + ']';
7547                 gap = mind;
7548                 return v;
7549             }
7550             
7551             // If the replacer is an array, use it to select the members to be
7552             // stringified.
7553             if (rep && typeof rep === 'object') {
7554                 length = rep.length;
7555                 for (i = 0; i < length; i += 1) {
7556                     k = rep[i];
7557                     if (typeof k === 'string') {
7558                         v = str(k, value);
7559                         if (v) {
7560                             partial.push(quote(k) + (gap ? ': ' : ':') + v);
7561                         }
7562                     }
7563                 }
7564             }
7565             else {
7566                 // Otherwise, iterate through all of the keys in the object.
7567                 for (k in value) {
7568                     if (Object.prototype.hasOwnProperty.call(value, k)) {
7569                         v = str(k, value);
7570                         if (v) {
7571                             partial.push(quote(k) + (gap ? ': ' : ':') + v);
7572                         }
7573                     }
7574                 }
7575             }
7576             
7577         // Join all of the member texts together, separated with commas,
7578         // and wrap them in braces.
7579
7580         v = partial.length === 0 ? '{}' : gap ?
7581             '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
7582             '{' + partial.join(',') + '}';
7583         gap = mind;
7584         return v;
7585     }
7586 }
7587
7588 module.exports = function (value, replacer, space) {
7589     var i;
7590     gap = '';
7591     indent = '';
7592     
7593     // If the space parameter is a number, make an indent string containing that
7594     // many spaces.
7595     if (typeof space === 'number') {
7596         for (i = 0; i < space; i += 1) {
7597             indent += ' ';
7598         }
7599     }
7600     // If the space parameter is a string, it will be used as the indent string.
7601     else if (typeof space === 'string') {
7602         indent = space;
7603     }
7604
7605     // If there is a replacer, it must be a function or an array.
7606     // Otherwise, throw an error.
7607     rep = replacer;
7608     if (replacer && typeof replacer !== 'function'
7609     && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) {
7610         throw new Error('JSON.stringify');
7611     }
7612     
7613     // Make a fake root object containing our value under the key of ''.
7614     // Return the result of stringifying the value.
7615     return str('', {'': value});
7616 };
7617
7618 },{}],"ajv":[function(require,module,exports){
7619 'use strict';
7620
7621 var compileSchema = require('./compile')
7622   , resolve = require('./compile/resolve')
7623   , Cache = require('./cache')
7624   , SchemaObject = require('./compile/schema_obj')
7625   , stableStringify = require('json-stable-stringify')
7626   , formats = require('./compile/formats')
7627   , rules = require('./compile/rules')
7628   , v5 = require('./v5')
7629   , util = require('./compile/util')
7630   , async = require('./async')
7631   , co = require('co');
7632
7633 module.exports = Ajv;
7634
7635 Ajv.prototype.compileAsync = async.compile;
7636
7637 var customKeyword = require('./keyword');
7638 Ajv.prototype.addKeyword = customKeyword.add;
7639 Ajv.prototype.getKeyword = customKeyword.get;
7640 Ajv.prototype.removeKeyword = customKeyword.remove;
7641 Ajv.ValidationError = require('./compile/validation_error');
7642
7643 var META_SCHEMA_ID = 'http://json-schema.org/draft-04/schema';
7644 var SCHEMA_URI_FORMAT = /^(?:(?:[a-z][a-z0-9+-.]*:)?\/\/)?[^\s]*$/i;
7645 function SCHEMA_URI_FORMAT_FUNC(str) {
7646   return SCHEMA_URI_FORMAT.test(str);
7647 }
7648
7649 var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes' ];
7650
7651 /**
7652  * Creates validator instance.
7653  * Usage: `Ajv(opts)`
7654  * @param {Object} opts optional options
7655  * @return {Object} ajv instance
7656  */
7657 function Ajv(opts) {
7658   if (!(this instanceof Ajv)) return new Ajv(opts);
7659   var self = this;
7660
7661   opts = this._opts = util.copy(opts) || {};
7662   this._schemas = {};
7663   this._refs = {};
7664   this._fragments = {};
7665   this._formats = formats(opts.format);
7666   this._cache = opts.cache || new Cache;
7667   this._loadingSchemas = {};
7668   this._compilations = [];
7669   this.RULES = rules();
7670
7671   // this is done on purpose, so that methods are bound to the instance
7672   // (without using bind) so that they can be used without the instance
7673   this.validate = validate;
7674   this.compile = compile;
7675   this.addSchema = addSchema;
7676   this.addMetaSchema = addMetaSchema;
7677   this.validateSchema = validateSchema;
7678   this.getSchema = getSchema;
7679   this.removeSchema = removeSchema;
7680   this.addFormat = addFormat;
7681   this.errorsText = errorsText;
7682
7683   this._addSchema = _addSchema;
7684   this._compile = _compile;
7685
7686   opts.loopRequired = opts.loopRequired || Infinity;
7687   if (opts.async || opts.transpile) async.setup(opts);
7688   if (opts.beautify === true) opts.beautify = { indent_size: 2 };
7689   if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
7690   this._metaOpts = getMetaSchemaOptions();
7691
7692   if (opts.formats) addInitialFormats();
7693   addDraft4MetaSchema();
7694   if (opts.v5) v5.enable(this);
7695   if (typeof opts.meta == 'object') addMetaSchema(opts.meta);
7696   addInitialSchemas();
7697
7698
7699   /**
7700    * Validate data using schema
7701    * Schema will be compiled and cached (using serialized JSON as key. [json-stable-stringify](https://github.com/substack/json-stable-stringify) is used to serialize.
7702    * @param  {String|Object} schemaKeyRef key, ref or schema object
7703    * @param  {Any} data to be validated
7704    * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
7705    */
7706   function validate(schemaKeyRef, data) {
7707     var v;
7708     if (typeof schemaKeyRef == 'string') {
7709       v = getSchema(schemaKeyRef);
7710       if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
7711     } else {
7712       var schemaObj = _addSchema(schemaKeyRef);
7713       v = schemaObj.validate || _compile(schemaObj);
7714     }
7715
7716     var valid = v(data);
7717     if (v.$async === true)
7718       return self._opts.async == '*' ? co(valid) : valid;
7719     self.errors = v.errors;
7720     return valid;
7721   }
7722
7723
7724   /**
7725    * Create validating function for passed schema.
7726    * @param  {Object} schema schema object
7727    * @param  {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
7728    * @return {Function} validating function
7729    */
7730   function compile(schema, _meta) {
7731     var schemaObj = _addSchema(schema, undefined, _meta);
7732     return schemaObj.validate || _compile(schemaObj);
7733   }
7734
7735
7736   /**
7737    * Adds schema to the instance.
7738    * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
7739    * @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`.
7740    * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
7741    * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
7742    */
7743   function addSchema(schema, key, _skipValidation, _meta) {
7744     if (Array.isArray(schema)){
7745       for (var i=0; i<schema.length; i++) addSchema(schema[i], undefined, _skipValidation, _meta);
7746       return;
7747     }
7748     // can key/id have # inside?
7749     key = resolve.normalizeId(key || schema.id);
7750     checkUnique(key);
7751     self._schemas[key] = _addSchema(schema, _skipValidation, _meta, true);
7752   }
7753
7754
7755   /**
7756    * Add schema that will be used to validate other schemas
7757    * options in META_IGNORE_OPTIONS are alway set to false
7758    * @param {Object} schema schema object
7759    * @param {String} key optional schema key
7760    * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
7761    */
7762   function addMetaSchema(schema, key, skipValidation) {
7763     addSchema(schema, key, skipValidation, true);
7764   }
7765
7766
7767   /**
7768    * Validate schema
7769    * @param {Object} schema schema to validate
7770    * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
7771    * @return {Boolean} true if schema is valid
7772    */
7773   function validateSchema(schema, throwOrLogError) {
7774     var $schema = schema.$schema || self._opts.defaultMeta || defaultMeta();
7775     var currentUriFormat = self._formats.uri;
7776     self._formats.uri = typeof currentUriFormat == 'function'
7777                         ? SCHEMA_URI_FORMAT_FUNC
7778                         : SCHEMA_URI_FORMAT;
7779     var valid;
7780     try { valid = validate($schema, schema); }
7781     finally { self._formats.uri = currentUriFormat; }
7782     if (!valid && throwOrLogError) {
7783       var message = 'schema is invalid: ' + errorsText();
7784       if (self._opts.validateSchema == 'log') console.error(message);
7785       else throw new Error(message);
7786     }
7787     return valid;
7788   }
7789
7790
7791   function defaultMeta() {
7792     var meta = self._opts.meta;
7793     self._opts.defaultMeta = typeof meta == 'object'
7794                               ? meta.id || meta
7795                               : self._opts.v5
7796                                 ? v5.META_SCHEMA_ID
7797                                 : META_SCHEMA_ID;
7798     return self._opts.defaultMeta;
7799   }
7800
7801
7802   /**
7803    * Get compiled schema from the instance by `key` or `ref`.
7804    * @param  {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
7805    * @return {Function} schema validating function (with property `schema`).
7806    */
7807   function getSchema(keyRef) {
7808     var schemaObj = _getSchemaObj(keyRef);
7809     switch (typeof schemaObj) {
7810       case 'object': return schemaObj.validate || _compile(schemaObj);
7811       case 'string': return getSchema(schemaObj);
7812       case 'undefined': return _getSchemaFragment(keyRef);
7813     }
7814   }
7815
7816
7817   function _getSchemaFragment(ref) {
7818     var res = resolve.schema.call(self, { schema: {} }, ref);
7819     if (res) {
7820       var schema = res.schema
7821         , root = res.root
7822         , baseId = res.baseId;
7823       var v = compileSchema.call(self, schema, root, undefined, baseId);
7824       self._fragments[ref] = new SchemaObject({
7825         ref: ref,
7826         fragment: true,
7827         schema: schema,
7828         root: root,
7829         baseId: baseId,
7830         validate: v
7831       });
7832       return v;
7833     }
7834   }
7835
7836
7837   function _getSchemaObj(keyRef) {
7838     keyRef = resolve.normalizeId(keyRef);
7839     return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
7840   }
7841
7842
7843   /**
7844    * Remove cached schema(s).
7845    * If no parameter is passed all schemas but meta-schemas are removed.
7846    * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
7847    * Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
7848    * @param  {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
7849    */
7850   function removeSchema(schemaKeyRef) {
7851     if (schemaKeyRef instanceof RegExp) {
7852       _removeAllSchemas(self._schemas, schemaKeyRef);
7853       _removeAllSchemas(self._refs, schemaKeyRef);
7854       return;
7855     }
7856     switch (typeof schemaKeyRef) {
7857       case 'undefined':
7858         _removeAllSchemas(self._schemas);
7859         _removeAllSchemas(self._refs);
7860         self._cache.clear();
7861         return;
7862       case 'string':
7863         var schemaObj = _getSchemaObj(schemaKeyRef);
7864         if (schemaObj) self._cache.del(schemaObj.jsonStr);
7865         delete self._schemas[schemaKeyRef];
7866         delete self._refs[schemaKeyRef];
7867         return;
7868       case 'object':
7869         var jsonStr = stableStringify(schemaKeyRef);
7870         self._cache.del(jsonStr);
7871         var id = schemaKeyRef.id;
7872         if (id) {
7873           id = resolve.normalizeId(id);
7874           delete self._schemas[id];
7875           delete self._refs[id];
7876         }
7877     }
7878   }
7879
7880
7881   function _removeAllSchemas(schemas, regex) {
7882     for (var keyRef in schemas) {
7883       var schemaObj = schemas[keyRef];
7884       if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
7885         self._cache.del(schemaObj.jsonStr);
7886         delete schemas[keyRef];
7887       }
7888     }
7889   }
7890
7891
7892   function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
7893     if (typeof schema != 'object') throw new Error('schema should be object');
7894     var jsonStr = stableStringify(schema);
7895     var cached = self._cache.get(jsonStr);
7896     if (cached) return cached;
7897
7898     shouldAddSchema = shouldAddSchema || self._opts.addUsedSchema !== false;
7899
7900     var id = resolve.normalizeId(schema.id);
7901     if (id && shouldAddSchema) checkUnique(id);
7902
7903     var willValidate = self._opts.validateSchema !== false && !skipValidation;
7904     var recursiveMeta;
7905     if (willValidate && !(recursiveMeta = schema.id && schema.id == schema.$schema))
7906       validateSchema(schema, true);
7907
7908     var localRefs = resolve.ids.call(self, schema);
7909
7910     var schemaObj = new SchemaObject({
7911       id: id,
7912       schema: schema,
7913       localRefs: localRefs,
7914       jsonStr: jsonStr,
7915       meta: meta
7916     });
7917
7918     if (id[0] != '#' && shouldAddSchema) self._refs[id] = schemaObj;
7919     self._cache.put(jsonStr, schemaObj);
7920
7921     if (willValidate && recursiveMeta) validateSchema(schema, true);
7922
7923     return schemaObj;
7924   }
7925
7926
7927   function _compile(schemaObj, root) {
7928     if (schemaObj.compiling) {
7929       schemaObj.validate = callValidate;
7930       callValidate.schema = schemaObj.schema;
7931       callValidate.errors = null;
7932       callValidate.root = root ? root : callValidate;
7933       if (schemaObj.schema.$async === true)
7934         callValidate.$async = true;
7935       return callValidate;
7936     }
7937     schemaObj.compiling = true;
7938
7939     var currentOpts;
7940     if (schemaObj.meta) {
7941       currentOpts = self._opts;
7942       self._opts = self._metaOpts;
7943     }
7944
7945     var v;
7946     try { v = compileSchema.call(self, schemaObj.schema, root, schemaObj.localRefs); }
7947     finally {
7948       schemaObj.compiling = false;
7949       if (schemaObj.meta) self._opts = currentOpts;
7950     }
7951
7952     schemaObj.validate = v;
7953     schemaObj.refs = v.refs;
7954     schemaObj.refVal = v.refVal;
7955     schemaObj.root = v.root;
7956     return v;
7957
7958
7959     function callValidate() {
7960       var _validate = schemaObj.validate;
7961       var result = _validate.apply(null, arguments);
7962       callValidate.errors = _validate.errors;
7963       return result;
7964     }
7965   }
7966
7967
7968   /**
7969    * Convert array of error message objects to string
7970    * @param  {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
7971    * @param  {Object} options optional options with properties `separator` and `dataVar`.
7972    * @return {String} human readable string with all errors descriptions
7973    */
7974   function errorsText(errors, options) {
7975     errors = errors || self.errors;
7976     if (!errors) return 'No errors';
7977     options = options || {};
7978     var separator = options.separator === undefined ? ', ' : options.separator;
7979     var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
7980
7981     var text = '';
7982     for (var i=0; i<errors.length; i++) {
7983       var e = errors[i];
7984       if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
7985     }
7986     return text.slice(0, -separator.length);
7987   }
7988
7989
7990   /**
7991    * Add custom format
7992    * @param {String} name format name
7993    * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
7994    */
7995   function addFormat(name, format) {
7996     if (typeof format == 'string') format = new RegExp(format);
7997     self._formats[name] = format;
7998   }
7999
8000
8001   function addDraft4MetaSchema() {
8002     if (self._opts.meta !== false) {
8003       var metaSchema = require('./refs/json-schema-draft-04.json');
8004       addMetaSchema(metaSchema, META_SCHEMA_ID, true);
8005       self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
8006     }
8007   }
8008
8009
8010   function addInitialSchemas() {
8011     var optsSchemas = self._opts.schemas;
8012     if (!optsSchemas) return;
8013     if (Array.isArray(optsSchemas)) addSchema(optsSchemas);
8014     else for (var key in optsSchemas) addSchema(optsSchemas[key], key);
8015   }
8016
8017
8018   function addInitialFormats() {
8019     for (var name in self._opts.formats) {
8020       var format = self._opts.formats[name];
8021       addFormat(name, format);
8022     }
8023   }
8024
8025
8026   function checkUnique(id) {
8027     if (self._schemas[id] || self._refs[id])
8028       throw new Error('schema with key or id "' + id + '" already exists');
8029   }
8030
8031
8032   function getMetaSchemaOptions() {
8033     var metaOpts = util.copy(self._opts);
8034     for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
8035       delete metaOpts[META_IGNORE_OPTIONS[i]];
8036     return metaOpts;
8037   }
8038 }
8039
8040 },{"./async":1,"./cache":2,"./compile":6,"./compile/formats":5,"./compile/resolve":7,"./compile/rules":8,"./compile/schema_obj":9,"./compile/util":11,"./compile/validation_error":12,"./keyword":37,"./refs/json-schema-draft-04.json":38,"./v5":40,"co":47,"json-stable-stringify":48}]},{},[])("ajv")
8041 });