slnodejs 6.1.143 → 6.1.149

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,7 +11,7 @@ var callback=popCallback(streams);if(Array.isArray(streams[0]))streams=streams[0
11
11
  78:[function(require,module,exports){var MD5=require("md5.js");module.exports=function(buffer){return(new MD5).update(buffer).digest()}},{"md5.js":148}],79:[function(require,module,exports){"use strict";var inherits=require("inherits");var Legacy=require("./legacy");var Base=require("cipher-base");var Buffer=require("safe-buffer").Buffer;var md5=require("create-hash/md5");var RIPEMD160=require("ripemd160");var sha=require("sha.js");var ZEROS=Buffer.alloc(128);function Hmac(alg,key){Base.call(this,"digest");if(typeof key==="string"){key=Buffer.from(key)}var blocksize=alg==="sha512"||alg==="sha384"?128:64;this._alg=alg;this._key=key;if(key.length>blocksize){var hash=alg==="rmd160"?new RIPEMD160:sha(alg);key=hash.update(key).digest()}else if(key.length<blocksize){key=Buffer.concat([key,ZEROS],blocksize)}var ipad=this._ipad=Buffer.allocUnsafe(blocksize);var opad=this._opad=Buffer.allocUnsafe(blocksize);for(var i=0;i<blocksize;i++){ipad[i]=key[i]^54;opad[i]=key[i]^92}this._hash=alg==="rmd160"?new RIPEMD160:sha(alg);this._hash.update(ipad)}inherits(Hmac,Base);Hmac.prototype._update=function(data){this._hash.update(data)};Hmac.prototype._final=function(){var h=this._hash.digest();var hash=this._alg==="rmd160"?new RIPEMD160:sha(this._alg);return hash.update(this._opad).update(h).digest()};module.exports=function createHmac(alg,key){alg=alg.toLowerCase();if(alg==="rmd160"||alg==="ripemd160"){return new Hmac("rmd160",key)}if(alg==="md5"){return new Legacy(md5,key)}return new Hmac(alg,key)}},{"./legacy":80,"cipher-base":73,"create-hash/md5":78,inherits:145,ripemd160:208,"safe-buffer":209,"sha.js":211}],80:[function(require,module,exports){"use strict";var inherits=require("inherits");var Buffer=require("safe-buffer").Buffer;var Base=require("cipher-base");var ZEROS=Buffer.alloc(128);var blocksize=64;function Hmac(alg,key){Base.call(this,"digest");if(typeof key==="string"){key=Buffer.from(key)}this._alg=alg;this._key=key;if(key.length>blocksize){key=alg(key)}else if(key.length<blocksize){key=Buffer.concat([key,ZEROS],blocksize)}var ipad=this._ipad=Buffer.allocUnsafe(blocksize);var opad=this._opad=Buffer.allocUnsafe(blocksize);for(var i=0;i<blocksize;i++){ipad[i]=key[i]^54;opad[i]=key[i]^92}this._hash=[ipad]}inherits(Hmac,Base);Hmac.prototype._update=function(data){this._hash.push(data)};Hmac.prototype._final=function(){var h=this._alg(Buffer.concat(this._hash));return this._alg(Buffer.concat([this._opad,h]))};module.exports=Hmac},{"cipher-base":73,inherits:145,"safe-buffer":209}],81:[function(require,module,exports){"use strict";exports.randomBytes=exports.rng=exports.pseudoRandomBytes=exports.prng=require("randombytes");exports.createHash=exports.Hash=require("create-hash");exports.createHmac=exports.Hmac=require("create-hmac");var algos=require("browserify-sign/algos");var algoKeys=Object.keys(algos);var hashes=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(algoKeys);exports.getHashes=function(){return hashes};var p=require("pbkdf2");exports.pbkdf2=p.pbkdf2;exports.pbkdf2Sync=p.pbkdf2Sync;var aes=require("browserify-cipher");exports.Cipher=aes.Cipher;exports.createCipher=aes.createCipher;exports.Cipheriv=aes.Cipheriv;exports.createCipheriv=aes.createCipheriv;exports.Decipher=aes.Decipher;exports.createDecipher=aes.createDecipher;exports.Decipheriv=aes.Decipheriv;exports.createDecipheriv=aes.createDecipheriv;exports.getCiphers=aes.getCiphers;exports.listCiphers=aes.listCiphers;var dh=require("diffie-hellman");exports.DiffieHellmanGroup=dh.DiffieHellmanGroup;exports.createDiffieHellmanGroup=dh.createDiffieHellmanGroup;exports.getDiffieHellman=dh.getDiffieHellman;exports.createDiffieHellman=dh.createDiffieHellman;exports.DiffieHellman=dh.DiffieHellman;var sign=require("browserify-sign");exports.createSign=sign.createSign;exports.Sign=sign.Sign;exports.createVerify=sign.createVerify;exports.Verify=sign.Verify;exports.createECDH=require("create-ecdh");var publicEncrypt=require("public-encrypt");exports.publicEncrypt=publicEncrypt.publicEncrypt;exports.privateEncrypt=publicEncrypt.privateEncrypt;exports.publicDecrypt=publicEncrypt.publicDecrypt;exports.privateDecrypt=publicEncrypt.privateDecrypt;var rf=require("randomfill");exports.randomFill=rf.randomFill;exports.randomFillSync=rf.randomFillSync;exports.createCredentials=function(){throw new Error(["sorry, createCredentials is not implemented yet","we accept pull requests","https://github.com/crypto-browserify/crypto-browserify"].join("\n"))};exports.constants={DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}},{"browserify-cipher":41,"browserify-sign":48,"browserify-sign/algos":45,"create-ecdh":75,"create-hash":77,"create-hmac":79,"diffie-hellman":88,pbkdf2:172,"public-encrypt":180,randombytes:191,randomfill:192}],82:[function(require,module,exports){"use strict";exports.utils=require("./des/utils");exports.Cipher=require("./des/cipher");exports.DES=require("./des/des");exports.CBC=require("./des/cbc");exports.EDE=require("./des/ede")},{"./des/cbc":83,"./des/cipher":84,"./des/des":85,"./des/ede":86,"./des/utils":87}],83:[function(require,module,exports){"use strict";var assert=require("minimalistic-assert");var inherits=require("inherits");var proto={};function CBCState(iv){assert.equal(iv.length,8,"Invalid IV length");this.iv=new Array(8);for(var i=0;i<this.iv.length;i++)this.iv[i]=iv[i]}function instantiate(Base){function CBC(options){Base.call(this,options);this._cbcInit()}inherits(CBC,Base);var keys=Object.keys(proto);for(var i=0;i<keys.length;i++){var key=keys[i];CBC.prototype[key]=proto[key]}CBC.create=function create(options){return new CBC(options)};return CBC}exports.instantiate=instantiate;proto._cbcInit=function _cbcInit(){var state=new CBCState(this.options.iv);this._cbcState=state};proto._update=function _update(inp,inOff,out,outOff){var state=this._cbcState;var superProto=this.constructor.super_.prototype;var iv=state.iv;if(this.type==="encrypt"){for(var i=0;i<this.blockSize;i++)iv[i]^=inp[inOff+i];superProto._update.call(this,iv,0,out,outOff);for(var i=0;i<this.blockSize;i++)iv[i]=out[outOff+i]}else{superProto._update.call(this,inp,inOff,out,outOff);for(var i=0;i<this.blockSize;i++)out[outOff+i]^=iv[i];for(var i=0;i<this.blockSize;i++)iv[i]=inp[inOff+i]}}},{inherits:145,"minimalistic-assert":151}],84:[function(require,module,exports){"use strict";var assert=require("minimalistic-assert");function Cipher(options){this.options=options;this.type=this.options.type;this.blockSize=8;this._init();this.buffer=new Array(this.blockSize);this.bufferOff=0}module.exports=Cipher;Cipher.prototype._init=function _init(){};Cipher.prototype.update=function update(data){if(data.length===0)return[];if(this.type==="decrypt")return this._updateDecrypt(data);else return this._updateEncrypt(data)};Cipher.prototype._buffer=function _buffer(data,off){var min=Math.min(this.buffer.length-this.bufferOff,data.length-off);for(var i=0;i<min;i++)this.buffer[this.bufferOff+i]=data[off+i];this.bufferOff+=min;return min};Cipher.prototype._flushBuffer=function _flushBuffer(out,off){this._update(this.buffer,0,out,off);this.bufferOff=0;return this.blockSize};Cipher.prototype._updateEncrypt=function _updateEncrypt(data){var inputOff=0;var outputOff=0;var count=(this.bufferOff+data.length)/this.blockSize|0;var out=new Array(count*this.blockSize);if(this.bufferOff!==0){inputOff+=this._buffer(data,inputOff);if(this.bufferOff===this.buffer.length)outputOff+=this._flushBuffer(out,outputOff)}var max=data.length-(data.length-inputOff)%this.blockSize;for(;inputOff<max;inputOff+=this.blockSize){this._update(data,inputOff,out,outputOff);outputOff+=this.blockSize}for(;inputOff<data.length;inputOff++,this.bufferOff++)this.buffer[this.bufferOff]=data[inputOff];return out};Cipher.prototype._updateDecrypt=function _updateDecrypt(data){var inputOff=0;var outputOff=0;var count=Math.ceil((this.bufferOff+data.length)/this.blockSize)-1;var out=new Array(count*this.blockSize);for(;count>0;count--){inputOff+=this._buffer(data,inputOff);outputOff+=this._flushBuffer(out,outputOff)}inputOff+=this._buffer(data,inputOff);return out};Cipher.prototype.final=function final(buffer){var first;if(buffer)first=this.update(buffer);var last;if(this.type==="encrypt")last=this._finalEncrypt();else last=this._finalDecrypt();if(first)return first.concat(last);else return last};Cipher.prototype._pad=function _pad(buffer,off){if(off===0)return false;while(off<buffer.length)buffer[off++]=0;return true};Cipher.prototype._finalEncrypt=function _finalEncrypt(){if(!this._pad(this.buffer,this.bufferOff))return[];var out=new Array(this.blockSize);this._update(this.buffer,0,out,0);return out};Cipher.prototype._unpad=function _unpad(buffer){return buffer};Cipher.prototype._finalDecrypt=function _finalDecrypt(){assert.equal(this.bufferOff,this.blockSize,"Not enough data to decrypt");var out=new Array(this.blockSize);this._flushBuffer(out,0);return this._unpad(out)}},{"minimalistic-assert":151}],85:[function(require,module,exports){"use strict";var assert=require("minimalistic-assert");var inherits=require("inherits");var utils=require("./utils");var Cipher=require("./cipher");function DESState(){this.tmp=new Array(2);this.keys=null}function DES(options){Cipher.call(this,options);var state=new DESState;this._desState=state;this.deriveKeys(state,options.key)}inherits(DES,Cipher);module.exports=DES;DES.create=function create(options){return new DES(options)};var shiftTable=[1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1];DES.prototype.deriveKeys=function deriveKeys(state,key){state.keys=new Array(16*2);assert.equal(key.length,this.blockSize,"Invalid key length");var kL=utils.readUInt32BE(key,0);var kR=utils.readUInt32BE(key,4);utils.pc1(kL,kR,state.tmp,0);kL=state.tmp[0];kR=state.tmp[1];for(var i=0;i<state.keys.length;i+=2){var shift=shiftTable[i>>>1];kL=utils.r28shl(kL,shift);kR=utils.r28shl(kR,shift);utils.pc2(kL,kR,state.keys,i)}};DES.prototype._update=function _update(inp,inOff,out,outOff){var state=this._desState;var l=utils.readUInt32BE(inp,inOff);var r=utils.readUInt32BE(inp,inOff+4);utils.ip(l,r,state.tmp,0);l=state.tmp[0];r=state.tmp[1];if(this.type==="encrypt")this._encrypt(state,l,r,state.tmp,0);else this._decrypt(state,l,r,state.tmp,0);l=state.tmp[0];r=state.tmp[1];utils.writeUInt32BE(out,l,outOff);utils.writeUInt32BE(out,r,outOff+4)};DES.prototype._pad=function _pad(buffer,off){var value=buffer.length-off;for(var i=off;i<buffer.length;i++)buffer[i]=value;return true};DES.prototype._unpad=function _unpad(buffer){var pad=buffer[buffer.length-1];for(var i=buffer.length-pad;i<buffer.length;i++)assert.equal(buffer[i],pad);return buffer.slice(0,buffer.length-pad)};DES.prototype._encrypt=function _encrypt(state,lStart,rStart,out,off){var l=lStart;var r=rStart;for(var i=0;i<state.keys.length;i+=2){var keyL=state.keys[i];var keyR=state.keys[i+1];utils.expand(r,state.tmp,0);keyL^=state.tmp[0];keyR^=state.tmp[1];var s=utils.substitute(keyL,keyR);var f=utils.permute(s);var t=r;r=(l^f)>>>0;l=t}utils.rip(r,l,out,off)};DES.prototype._decrypt=function _decrypt(state,lStart,rStart,out,off){var l=rStart;var r=lStart;for(var i=state.keys.length-2;i>=0;i-=2){var keyL=state.keys[i];var keyR=state.keys[i+1];utils.expand(l,state.tmp,0);keyL^=state.tmp[0];keyR^=state.tmp[1];var s=utils.substitute(keyL,keyR);var f=utils.permute(s);var t=l;l=(r^f)>>>0;r=t}utils.rip(l,r,out,off)}},{"./cipher":84,"./utils":87,inherits:145,"minimalistic-assert":151}],86:[function(require,module,exports){"use strict";var assert=require("minimalistic-assert");var inherits=require("inherits");var Cipher=require("./cipher");var DES=require("./des");function EDEState(type,key){assert.equal(key.length,24,"Invalid key length");var k1=key.slice(0,8);var k2=key.slice(8,16);var k3=key.slice(16,24);if(type==="encrypt"){this.ciphers=[DES.create({type:"encrypt",key:k1}),DES.create({type:"decrypt",key:k2}),DES.create({type:"encrypt",key:k3})]}else{this.ciphers=[DES.create({type:"decrypt",key:k3}),DES.create({type:"encrypt",key:k2}),DES.create({type:"decrypt",key:k1})]}}function EDE(options){Cipher.call(this,options);var state=new EDEState(this.type,this.options.key);this._edeState=state}inherits(EDE,Cipher);module.exports=EDE;EDE.create=function create(options){return new EDE(options)};EDE.prototype._update=function _update(inp,inOff,out,outOff){var state=this._edeState;state.ciphers[0]._update(inp,inOff,out,outOff);state.ciphers[1]._update(out,outOff,out,outOff);state.ciphers[2]._update(out,outOff,out,outOff)};EDE.prototype._pad=DES.prototype._pad;EDE.prototype._unpad=DES.prototype._unpad},{"./cipher":84,"./des":85,inherits:145,"minimalistic-assert":151}],87:[function(require,module,exports){"use strict";exports.readUInt32BE=function readUInt32BE(bytes,off){var res=bytes[0+off]<<24|bytes[1+off]<<16|bytes[2+off]<<8|bytes[3+off];return res>>>0};exports.writeUInt32BE=function writeUInt32BE(bytes,value,off){bytes[0+off]=value>>>24;bytes[1+off]=value>>>16&255;bytes[2+off]=value>>>8&255;bytes[3+off]=value&255};exports.ip=function ip(inL,inR,out,off){var outL=0;var outR=0;for(var i=6;i>=0;i-=2){for(var j=0;j<=24;j+=8){outL<<=1;outL|=inR>>>j+i&1}for(var j=0;j<=24;j+=8){outL<<=1;outL|=inL>>>j+i&1}}for(var i=6;i>=0;i-=2){for(var j=1;j<=25;j+=8){outR<<=1;outR|=inR>>>j+i&1}for(var j=1;j<=25;j+=8){outR<<=1;outR|=inL>>>j+i&1}}out[off+0]=outL>>>0;out[off+1]=outR>>>0};exports.rip=function rip(inL,inR,out,off){var outL=0;var outR=0;for(var i=0;i<4;i++){for(var j=24;j>=0;j-=8){outL<<=1;outL|=inR>>>j+i&1;outL<<=1;outL|=inL>>>j+i&1}}for(var i=4;i<8;i++){for(var j=24;j>=0;j-=8){outR<<=1;outR|=inR>>>j+i&1;outR<<=1;outR|=inL>>>j+i&1}}out[off+0]=outL>>>0;out[off+1]=outR>>>0};exports.pc1=function pc1(inL,inR,out,off){var outL=0;var outR=0;for(var i=7;i>=5;i--){for(var j=0;j<=24;j+=8){outL<<=1;outL|=inR>>j+i&1}for(var j=0;j<=24;j+=8){outL<<=1;outL|=inL>>j+i&1}}for(var j=0;j<=24;j+=8){outL<<=1;outL|=inR>>j+i&1}for(var i=1;i<=3;i++){for(var j=0;j<=24;j+=8){outR<<=1;outR|=inR>>j+i&1}for(var j=0;j<=24;j+=8){outR<<=1;outR|=inL>>j+i&1}}for(var j=0;j<=24;j+=8){outR<<=1;outR|=inL>>j+i&1}out[off+0]=outL>>>0;out[off+1]=outR>>>0};exports.r28shl=function r28shl(num,shift){return num<<shift&268435455|num>>>28-shift};var pc2table=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];exports.pc2=function pc2(inL,inR,out,off){var outL=0;var outR=0;var len=pc2table.length>>>1;for(var i=0;i<len;i++){outL<<=1;outL|=inL>>>pc2table[i]&1}for(var i=len;i<pc2table.length;i++){outR<<=1;outR|=inR>>>pc2table[i]&1}out[off+0]=outL>>>0;out[off+1]=outR>>>0};exports.expand=function expand(r,out,off){var outL=0;var outR=0;outL=(r&1)<<5|r>>>27;for(var i=23;i>=15;i-=4){outL<<=6;outL|=r>>>i&63}for(var i=11;i>=3;i-=4){outR|=r>>>i&63;outR<<=6}outR|=(r&31)<<1|r>>>31;out[off+0]=outL>>>0;out[off+1]=outR>>>0};var sTable=[14,0,4,15,13,7,1,4,2,14,15,2,11,13,8,1,3,10,10,6,6,12,12,11,5,9,9,5,0,3,7,8,4,15,1,12,14,8,8,2,13,4,6,9,2,1,11,7,15,5,12,11,9,3,7,14,3,10,10,0,5,6,0,13,15,3,1,13,8,4,14,7,6,15,11,2,3,8,4,14,9,12,7,0,2,1,13,10,12,6,0,9,5,11,10,5,0,13,14,8,7,10,11,1,10,3,4,15,13,4,1,2,5,11,8,6,12,7,6,12,9,0,3,5,2,14,15,9,10,13,0,7,9,0,14,9,6,3,3,4,15,6,5,10,1,2,13,8,12,5,7,14,11,12,4,11,2,15,8,1,13,1,6,10,4,13,9,0,8,6,15,9,3,8,0,7,11,4,1,15,2,14,12,3,5,11,10,5,14,2,7,12,7,13,13,8,14,11,3,5,0,6,6,15,9,0,10,3,1,4,2,7,8,2,5,12,11,1,12,10,4,14,15,9,10,3,6,15,9,0,0,6,12,10,11,1,7,13,13,8,15,9,1,4,3,5,14,11,5,12,2,7,8,2,4,14,2,14,12,11,4,2,1,12,7,4,10,7,11,13,6,1,8,5,5,0,3,15,15,10,13,3,0,9,14,8,9,6,4,11,2,8,1,12,11,7,10,1,13,14,7,2,8,13,15,6,9,15,12,0,5,9,6,10,3,4,0,5,14,3,12,10,1,15,10,4,15,2,9,7,2,12,6,9,8,5,0,6,13,1,3,13,4,14,14,0,7,11,5,3,11,8,9,4,14,3,15,2,5,12,2,9,8,5,12,15,3,10,7,11,0,14,4,1,10,7,1,6,13,0,11,8,6,13,4,13,11,0,2,11,14,7,15,4,0,9,8,1,13,10,3,14,12,3,9,5,7,12,5,2,10,15,6,8,1,6,1,6,4,11,11,13,13,8,12,1,3,4,7,10,14,7,10,9,15,5,6,0,8,15,0,14,5,2,9,3,2,12,13,1,2,15,8,13,4,8,6,10,15,3,11,7,1,4,10,12,9,5,3,6,14,11,5,0,0,14,12,9,7,2,7,2,11,1,4,14,1,7,9,4,12,10,14,8,2,13,0,15,6,12,10,9,13,0,15,3,3,5,5,6,8,11];exports.substitute=function substitute(inL,inR){var out=0;for(var i=0;i<4;i++){var b=inL>>>18-i*6&63;var sb=sTable[i*64+b];out<<=4;out|=sb}for(var i=0;i<4;i++){var b=inR>>>18-i*6&63;var sb=sTable[4*64+i*64+b];out<<=4;out|=sb}return out>>>0};var permuteTable=[16,25,12,11,3,20,4,15,31,17,9,6,27,14,1,22,30,24,8,18,0,5,29,23,13,19,2,26,10,21,28,7];exports.permute=function permute(num){var out=0;for(var i=0;i<permuteTable.length;i++){out<<=1;out|=num>>>permuteTable[i]&1}return out>>>0};exports.padSplit=function padSplit(num,size,group){var str=num.toString(2);while(str.length<size)str="0"+str;var out=[];for(var i=0;i<size;i+=group)out.push(str.slice(i,i+group));return out.join(" ")}},{}],88:[function(require,module,exports){(function(Buffer){(function(){var generatePrime=require("./lib/generatePrime");var primes=require("./lib/primes.json");var DH=require("./lib/dh");function getDiffieHellman(mod){var prime=new Buffer(primes[mod].prime,"hex");var gen=new Buffer(primes[mod].gen,"hex");return new DH(prime,gen)}var ENCODINGS={binary:true,hex:true,base64:true};function createDiffieHellman(prime,enc,generator,genc){if(Buffer.isBuffer(enc)||ENCODINGS[enc]===undefined){return createDiffieHellman(prime,"binary",enc,generator)}enc=enc||"binary";genc=genc||"binary";generator=generator||new Buffer([2]);if(!Buffer.isBuffer(generator)){generator=new Buffer(generator,genc)}if(typeof prime==="number"){return new DH(generatePrime(prime,generator),generator,true)}if(!Buffer.isBuffer(prime)){prime=new Buffer(prime,enc)}return new DH(prime,generator,true)}exports.DiffieHellmanGroup=exports.createDiffieHellmanGroup=exports.getDiffieHellman=getDiffieHellman;exports.createDiffieHellman=exports.DiffieHellman=createDiffieHellman}).call(this)}).call(this,require("buffer").Buffer)},{"./lib/dh":89,"./lib/generatePrime":90,"./lib/primes.json":91,buffer:71}],89:[function(require,module,exports){(function(Buffer){(function(){var BN=require("bn.js");var MillerRabin=require("miller-rabin");var millerRabin=new MillerRabin;var TWENTYFOUR=new BN(24);var ELEVEN=new BN(11);var TEN=new BN(10);var THREE=new BN(3);var SEVEN=new BN(7);var primes=require("./generatePrime");var randomBytes=require("randombytes");module.exports=DH;function setPublicKey(pub,enc){enc=enc||"utf8";if(!Buffer.isBuffer(pub)){pub=new Buffer(pub,enc)}this._pub=new BN(pub);return this}function setPrivateKey(priv,enc){enc=enc||"utf8";if(!Buffer.isBuffer(priv)){priv=new Buffer(priv,enc)}this._priv=new BN(priv);return this}var primeCache={};function checkPrime(prime,generator){var gen=generator.toString("hex");var hex=[gen,prime.toString(16)].join("_");if(hex in primeCache){return primeCache[hex]}var error=0;if(prime.isEven()||!primes.simpleSieve||!primes.fermatTest(prime)||!millerRabin.test(prime)){error+=1;if(gen==="02"||gen==="05"){error+=8}else{error+=4}primeCache[hex]=error;return error}if(!millerRabin.test(prime.shrn(1))){error+=2}var rem;switch(gen){case"02":if(prime.mod(TWENTYFOUR).cmp(ELEVEN)){error+=8}break;case"05":rem=prime.mod(TEN);if(rem.cmp(THREE)&&rem.cmp(SEVEN)){error+=8}break;default:error+=4}primeCache[hex]=error;return error}function DH(prime,generator,malleable){this.setGenerator(generator);this.__prime=new BN(prime);this._prime=BN.mont(this.__prime);this._primeLen=prime.length;this._pub=undefined;this._priv=undefined;this._primeCode=undefined;if(malleable){this.setPublicKey=setPublicKey;this.setPrivateKey=setPrivateKey}else{this._primeCode=8}}Object.defineProperty(DH.prototype,"verifyError",{enumerable:true,get:function(){if(typeof this._primeCode!=="number"){this._primeCode=checkPrime(this.__prime,this.__gen)}return this._primeCode}});DH.prototype.generateKeys=function(){if(!this._priv){this._priv=new BN(randomBytes(this._primeLen))}this._pub=this._gen.toRed(this._prime).redPow(this._priv).fromRed();return this.getPublicKey()};DH.prototype.computeSecret=function(other){other=new BN(other);other=other.toRed(this._prime);var secret=other.redPow(this._priv).fromRed();var out=new Buffer(secret.toArray());var prime=this.getPrime();if(out.length<prime.length){var front=new Buffer(prime.length-out.length);front.fill(0);out=Buffer.concat([front,out])}return out};DH.prototype.getPublicKey=function getPublicKey(enc){return formatReturnValue(this._pub,enc)};DH.prototype.getPrivateKey=function getPrivateKey(enc){return formatReturnValue(this._priv,enc)};DH.prototype.getPrime=function(enc){return formatReturnValue(this.__prime,enc)};DH.prototype.getGenerator=function(enc){return formatReturnValue(this._gen,enc)};DH.prototype.setGenerator=function(gen,enc){enc=enc||"utf8";if(!Buffer.isBuffer(gen)){gen=new Buffer(gen,enc)}this.__gen=gen;this._gen=new BN(gen);return this};function formatReturnValue(bn,enc){var buf=new Buffer(bn.toArray());if(!enc){return buf}else{return buf.toString(enc)}}}).call(this)}).call(this,require("buffer").Buffer)},{"./generatePrime":90,"bn.js":92,buffer:71,"miller-rabin":149,randombytes:191}],90:[function(require,module,exports){var randomBytes=require("randombytes");module.exports=findPrime;findPrime.simpleSieve=simpleSieve;findPrime.fermatTest=fermatTest;var BN=require("bn.js");var TWENTYFOUR=new BN(24);var MillerRabin=require("miller-rabin");var millerRabin=new MillerRabin;var ONE=new BN(1);var TWO=new BN(2);var FIVE=new BN(5);var SIXTEEN=new BN(16);var EIGHT=new BN(8);var TEN=new BN(10);var THREE=new BN(3);var SEVEN=new BN(7);var ELEVEN=new BN(11);var FOUR=new BN(4);var TWELVE=new BN(12);var primes=null;function _getPrimes(){if(primes!==null)return primes;var limit=1048576;var res=[];res[0]=2;for(var i=1,k=3;k<limit;k+=2){var sqrt=Math.ceil(Math.sqrt(k));for(var j=0;j<i&&res[j]<=sqrt;j++)if(k%res[j]===0)break;if(i!==j&&res[j]<=sqrt)continue;res[i++]=k}primes=res;return res}function simpleSieve(p){var primes=_getPrimes();for(var i=0;i<primes.length;i++)if(p.modn(primes[i])===0){if(p.cmpn(primes[i])===0){return true}else{return false}}return true}function fermatTest(p){var red=BN.mont(p);return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1)===0}function findPrime(bits,gen){if(bits<16){if(gen===2||gen===5){return new BN([140,123])}else{return new BN([140,39])}}gen=new BN(gen);var num,n2;while(true){num=new BN(randomBytes(Math.ceil(bits/8)));while(num.bitLength()>bits){num.ishrn(1)}if(num.isEven()){num.iadd(ONE)}if(!num.testn(1)){num.iadd(TWO)}if(!gen.cmp(TWO)){while(num.mod(TWENTYFOUR).cmp(ELEVEN)){num.iadd(FOUR)}}else if(!gen.cmp(FIVE)){while(num.mod(TEN).cmp(THREE)){num.iadd(FOUR)}}n2=num.shrn(1);if(simpleSieve(n2)&&simpleSieve(num)&&fermatTest(n2)&&fermatTest(num)&&millerRabin.test(n2)&&millerRabin.test(num)){return num}}}},{"bn.js":92,"miller-rabin":149,randombytes:191}],91:[function(require,module,exports){module.exports={modp1:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},modp2:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},modp5:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},modp14:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},modp15:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},modp16:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},modp17:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},modp18:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}},{}],92:[function(require,module,exports){arguments[4][15][0].apply(exports,arguments)},{buffer:23,dup:15}],93:[function(require,module,exports){"use strict";var elliptic=exports;elliptic.version=require("../package.json").version;elliptic.utils=require("./elliptic/utils");elliptic.rand=require("brorand");elliptic.curve=require("./elliptic/curve");elliptic.curves=require("./elliptic/curves");elliptic.ec=require("./elliptic/ec");elliptic.eddsa=require("./elliptic/eddsa")},{"../package.json":109,"./elliptic/curve":96,"./elliptic/curves":99,"./elliptic/ec":100,"./elliptic/eddsa":103,"./elliptic/utils":107,brorand:22}],94:[function(require,module,exports){"use strict";var BN=require("bn.js");var utils=require("../utils");var getNAF=utils.getNAF;var getJSF=utils.getJSF;var assert=utils.assert;function BaseCurve(type,conf){this.type=type;this.p=new BN(conf.p,16);this.red=conf.prime?BN.red(conf.prime):BN.mont(this.p);this.zero=new BN(0).toRed(this.red);this.one=new BN(1).toRed(this.red);this.two=new BN(2).toRed(this.red);this.n=conf.n&&new BN(conf.n,16);this.g=conf.g&&this.pointFromJSON(conf.g,conf.gRed);this._wnafT1=new Array(4);this._wnafT2=new Array(4);this._wnafT3=new Array(4);this._wnafT4=new Array(4);this._bitLength=this.n?this.n.bitLength():0;var adjustCount=this.n&&this.p.div(this.n);if(!adjustCount||adjustCount.cmpn(100)>0){this.redN=null}else{this._maxwellTrick=true;this.redN=this.n.toRed(this.red)}}module.exports=BaseCurve;BaseCurve.prototype.point=function point(){throw new Error("Not implemented")};BaseCurve.prototype.validate=function validate(){throw new Error("Not implemented")};BaseCurve.prototype._fixedNafMul=function _fixedNafMul(p,k){assert(p.precomputed);var doubles=p._getDoubles();var naf=getNAF(k,1,this._bitLength);var I=(1<<doubles.step+1)-(doubles.step%2===0?2:1);I/=3;var repr=[];var j;var nafW;for(j=0;j<naf.length;j+=doubles.step){nafW=0;for(var l=j+doubles.step-1;l>=j;l--)nafW=(nafW<<1)+naf[l];repr.push(nafW)}var a=this.jpoint(null,null,null)
12
12
  ;var b=this.jpoint(null,null,null);for(var i=I;i>0;i--){for(j=0;j<repr.length;j++){nafW=repr[j];if(nafW===i)b=b.mixedAdd(doubles.points[j]);else if(nafW===-i)b=b.mixedAdd(doubles.points[j].neg())}a=a.add(b)}return a.toP()};BaseCurve.prototype._wnafMul=function _wnafMul(p,k){var w=4;var nafPoints=p._getNAFPoints(w);w=nafPoints.wnd;var wnd=nafPoints.points;var naf=getNAF(k,w,this._bitLength);var acc=this.jpoint(null,null,null);for(var i=naf.length-1;i>=0;i--){for(var l=0;i>=0&&naf[i]===0;i--)l++;if(i>=0)l++;acc=acc.dblp(l);if(i<0)break;var z=naf[i];assert(z!==0);if(p.type==="affine"){if(z>0)acc=acc.mixedAdd(wnd[z-1>>1]);else acc=acc.mixedAdd(wnd[-z-1>>1].neg())}else{if(z>0)acc=acc.add(wnd[z-1>>1]);else acc=acc.add(wnd[-z-1>>1].neg())}}return p.type==="affine"?acc.toP():acc};BaseCurve.prototype._wnafMulAdd=function _wnafMulAdd(defW,points,coeffs,len,jacobianResult){var wndWidth=this._wnafT1;var wnd=this._wnafT2;var naf=this._wnafT3;var max=0;var i;var j;var p;for(i=0;i<len;i++){p=points[i];var nafPoints=p._getNAFPoints(defW);wndWidth[i]=nafPoints.wnd;wnd[i]=nafPoints.points}for(i=len-1;i>=1;i-=2){var a=i-1;var b=i;if(wndWidth[a]!==1||wndWidth[b]!==1){naf[a]=getNAF(coeffs[a],wndWidth[a],this._bitLength);naf[b]=getNAF(coeffs[b],wndWidth[b],this._bitLength);max=Math.max(naf[a].length,max);max=Math.max(naf[b].length,max);continue}var comb=[points[a],null,null,points[b]];if(points[a].y.cmp(points[b].y)===0){comb[1]=points[a].add(points[b]);comb[2]=points[a].toJ().mixedAdd(points[b].neg())}else if(points[a].y.cmp(points[b].y.redNeg())===0){comb[1]=points[a].toJ().mixedAdd(points[b]);comb[2]=points[a].add(points[b].neg())}else{comb[1]=points[a].toJ().mixedAdd(points[b]);comb[2]=points[a].toJ().mixedAdd(points[b].neg())}var index=[-3,-1,-5,-7,0,7,5,1,3];var jsf=getJSF(coeffs[a],coeffs[b]);max=Math.max(jsf[0].length,max);naf[a]=new Array(max);naf[b]=new Array(max);for(j=0;j<max;j++){var ja=jsf[0][j]|0;var jb=jsf[1][j]|0;naf[a][j]=index[(ja+1)*3+(jb+1)];naf[b][j]=0;wnd[a]=comb}}var acc=this.jpoint(null,null,null);var tmp=this._wnafT4;for(i=max;i>=0;i--){var k=0;while(i>=0){var zero=true;for(j=0;j<len;j++){tmp[j]=naf[j][i]|0;if(tmp[j]!==0)zero=false}if(!zero)break;k++;i--}if(i>=0)k++;acc=acc.dblp(k);if(i<0)break;for(j=0;j<len;j++){var z=tmp[j];p;if(z===0)continue;else if(z>0)p=wnd[j][z-1>>1];else if(z<0)p=wnd[j][-z-1>>1].neg();if(p.type==="affine")acc=acc.mixedAdd(p);else acc=acc.add(p)}}for(i=0;i<len;i++)wnd[i]=null;if(jacobianResult)return acc;else return acc.toP()};function BasePoint(curve,type){this.curve=curve;this.type=type;this.precomputed=null}BaseCurve.BasePoint=BasePoint;BasePoint.prototype.eq=function eq(){throw new Error("Not implemented")};BasePoint.prototype.validate=function validate(){return this.curve.validate(this)};BaseCurve.prototype.decodePoint=function decodePoint(bytes,enc){bytes=utils.toArray(bytes,enc);var len=this.p.byteLength();if((bytes[0]===4||bytes[0]===6||bytes[0]===7)&&bytes.length-1===2*len){if(bytes[0]===6)assert(bytes[bytes.length-1]%2===0);else if(bytes[0]===7)assert(bytes[bytes.length-1]%2===1);var res=this.point(bytes.slice(1,1+len),bytes.slice(1+len,1+2*len));return res}else if((bytes[0]===2||bytes[0]===3)&&bytes.length-1===len){return this.pointFromX(bytes.slice(1,1+len),bytes[0]===3)}throw new Error("Unknown point format")};BasePoint.prototype.encodeCompressed=function encodeCompressed(enc){return this.encode(enc,true)};BasePoint.prototype._encode=function _encode(compact){var len=this.curve.p.byteLength();var x=this.getX().toArray("be",len);if(compact)return[this.getY().isEven()?2:3].concat(x);return[4].concat(x,this.getY().toArray("be",len))};BasePoint.prototype.encode=function encode(enc,compact){return utils.encode(this._encode(compact),enc)};BasePoint.prototype.precompute=function precompute(power){if(this.precomputed)return this;var precomputed={doubles:null,naf:null,beta:null};precomputed.naf=this._getNAFPoints(8);precomputed.doubles=this._getDoubles(4,power);precomputed.beta=this._getBeta();this.precomputed=precomputed;return this};BasePoint.prototype._hasDoubles=function _hasDoubles(k){if(!this.precomputed)return false;var doubles=this.precomputed.doubles;if(!doubles)return false;return doubles.points.length>=Math.ceil((k.bitLength()+1)/doubles.step)};BasePoint.prototype._getDoubles=function _getDoubles(step,power){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;var doubles=[this];var acc=this;for(var i=0;i<power;i+=step){for(var j=0;j<step;j++)acc=acc.dbl();doubles.push(acc)}return{step:step,points:doubles}};BasePoint.prototype._getNAFPoints=function _getNAFPoints(wnd){if(this.precomputed&&this.precomputed.naf)return this.precomputed.naf;var res=[this];var max=(1<<wnd)-1;var dbl=max===1?null:this.dbl();for(var i=1;i<max;i++)res[i]=res[i-1].add(dbl);return{wnd:wnd,points:res}};BasePoint.prototype._getBeta=function _getBeta(){return null};BasePoint.prototype.dblp=function dblp(k){var r=this;for(var i=0;i<k;i++)r=r.dbl();return r}},{"../utils":107,"bn.js":108}],95:[function(require,module,exports){"use strict";var utils=require("../utils");var BN=require("bn.js");var inherits=require("inherits");var Base=require("./base");var assert=utils.assert;function EdwardsCurve(conf){this.twisted=(conf.a|0)!==1;this.mOneA=this.twisted&&(conf.a|0)===-1;this.extended=this.mOneA;Base.call(this,"edwards",conf);this.a=new BN(conf.a,16).umod(this.red.m);this.a=this.a.toRed(this.red);this.c=new BN(conf.c,16).toRed(this.red);this.c2=this.c.redSqr();this.d=new BN(conf.d,16).toRed(this.red);this.dd=this.d.redAdd(this.d);assert(!this.twisted||this.c.fromRed().cmpn(1)===0);this.oneC=(conf.c|0)===1}inherits(EdwardsCurve,Base);module.exports=EdwardsCurve;EdwardsCurve.prototype._mulA=function _mulA(num){if(this.mOneA)return num.redNeg();else return this.a.redMul(num)};EdwardsCurve.prototype._mulC=function _mulC(num){if(this.oneC)return num;else return this.c.redMul(num)};EdwardsCurve.prototype.jpoint=function jpoint(x,y,z,t){return this.point(x,y,z,t)};EdwardsCurve.prototype.pointFromX=function pointFromX(x,odd){x=new BN(x,16);if(!x.red)x=x.toRed(this.red);var x2=x.redSqr();var rhs=this.c2.redSub(this.a.redMul(x2));var lhs=this.one.redSub(this.c2.redMul(this.d).redMul(x2));var y2=rhs.redMul(lhs.redInvm());var y=y2.redSqrt();if(y.redSqr().redSub(y2).cmp(this.zero)!==0)throw new Error("invalid point");var isOdd=y.fromRed().isOdd();if(odd&&!isOdd||!odd&&isOdd)y=y.redNeg();return this.point(x,y)};EdwardsCurve.prototype.pointFromY=function pointFromY(y,odd){y=new BN(y,16);if(!y.red)y=y.toRed(this.red);var y2=y.redSqr();var lhs=y2.redSub(this.c2);var rhs=y2.redMul(this.d).redMul(this.c2).redSub(this.a);var x2=lhs.redMul(rhs.redInvm());if(x2.cmp(this.zero)===0){if(odd)throw new Error("invalid point");else return this.point(this.zero,y)}var x=x2.redSqrt();if(x.redSqr().redSub(x2).cmp(this.zero)!==0)throw new Error("invalid point");if(x.fromRed().isOdd()!==odd)x=x.redNeg();return this.point(x,y)};EdwardsCurve.prototype.validate=function validate(point){if(point.isInfinity())return true;point.normalize();var x2=point.x.redSqr();var y2=point.y.redSqr();var lhs=x2.redMul(this.a).redAdd(y2);var rhs=this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));return lhs.cmp(rhs)===0};function Point(curve,x,y,z,t){Base.BasePoint.call(this,curve,"projective");if(x===null&&y===null&&z===null){this.x=this.curve.zero;this.y=this.curve.one;this.z=this.curve.one;this.t=this.curve.zero;this.zOne=true}else{this.x=new BN(x,16);this.y=new BN(y,16);this.z=z?new BN(z,16):this.curve.one;this.t=t&&new BN(t,16);if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.y.red)this.y=this.y.toRed(this.curve.red);if(!this.z.red)this.z=this.z.toRed(this.curve.red);if(this.t&&!this.t.red)this.t=this.t.toRed(this.curve.red);this.zOne=this.z===this.curve.one;if(this.curve.extended&&!this.t){this.t=this.x.redMul(this.y);if(!this.zOne)this.t=this.t.redMul(this.z.redInvm())}}}inherits(Point,Base.BasePoint);EdwardsCurve.prototype.pointFromJSON=function pointFromJSON(obj){return Point.fromJSON(this,obj)};EdwardsCurve.prototype.point=function point(x,y,z,t){return new Point(this,x,y,z,t)};Point.fromJSON=function fromJSON(curve,obj){return new Point(curve,obj[0],obj[1],obj[2])};Point.prototype.inspect=function inspect(){if(this.isInfinity())return"<EC Point Infinity>";return"<EC Point x: "+this.x.fromRed().toString(16,2)+" y: "+this.y.fromRed().toString(16,2)+" z: "+this.z.fromRed().toString(16,2)+">"};Point.prototype.isInfinity=function isInfinity(){return this.x.cmpn(0)===0&&(this.y.cmp(this.z)===0||this.zOne&&this.y.cmp(this.curve.c)===0)};Point.prototype._extDbl=function _extDbl(){var a=this.x.redSqr();var b=this.y.redSqr();var c=this.z.redSqr();c=c.redIAdd(c);var d=this.curve._mulA(a);var e=this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);var g=d.redAdd(b);var f=g.redSub(c);var h=d.redSub(b);var nx=e.redMul(f);var ny=g.redMul(h);var nt=e.redMul(h);var nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)};Point.prototype._projDbl=function _projDbl(){var b=this.x.redAdd(this.y).redSqr();var c=this.x.redSqr();var d=this.y.redSqr();var nx;var ny;var nz;var e;var h;var j;if(this.curve.twisted){e=this.curve._mulA(c);var f=e.redAdd(d);if(this.zOne){nx=b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));ny=f.redMul(e.redSub(d));nz=f.redSqr().redSub(f).redSub(f)}else{h=this.z.redSqr();j=f.redSub(h).redISub(h);nx=b.redSub(c).redISub(d).redMul(j);ny=f.redMul(e.redSub(d));nz=f.redMul(j)}}else{e=c.redAdd(d);h=this.curve._mulC(this.z).redSqr();j=e.redSub(h).redSub(h);nx=this.curve._mulC(b.redISub(e)).redMul(j);ny=this.curve._mulC(e).redMul(c.redISub(d));nz=e.redMul(j)}return this.curve.point(nx,ny,nz)};Point.prototype.dbl=function dbl(){if(this.isInfinity())return this;if(this.curve.extended)return this._extDbl();else return this._projDbl()};Point.prototype._extAdd=function _extAdd(p){var a=this.y.redSub(this.x).redMul(p.y.redSub(p.x));var b=this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));var c=this.t.redMul(this.curve.dd).redMul(p.t);var d=this.z.redMul(p.z.redAdd(p.z));var e=b.redSub(a);var f=d.redSub(c);var g=d.redAdd(c);var h=b.redAdd(a);var nx=e.redMul(f);var ny=g.redMul(h);var nt=e.redMul(h);var nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)};Point.prototype._projAdd=function _projAdd(p){var a=this.z.redMul(p.z);var b=a.redSqr();var c=this.x.redMul(p.x);var d=this.y.redMul(p.y);var e=this.curve.d.redMul(c).redMul(d);var f=b.redSub(e);var g=b.redAdd(e);var tmp=this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);var nx=a.redMul(f).redMul(tmp);var ny;var nz;if(this.curve.twisted){ny=a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));nz=f.redMul(g)}else{ny=a.redMul(g).redMul(d.redSub(c));nz=this.curve._mulC(f).redMul(g)}return this.curve.point(nx,ny,nz)};Point.prototype.add=function add(p){if(this.isInfinity())return p;if(p.isInfinity())return this;if(this.curve.extended)return this._extAdd(p);else return this._projAdd(p)};Point.prototype.mul=function mul(k){if(this._hasDoubles(k))return this.curve._fixedNafMul(this,k);else return this.curve._wnafMul(this,k)};Point.prototype.mulAdd=function mulAdd(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,false)};Point.prototype.jmulAdd=function jmulAdd(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,true)};Point.prototype.normalize=function normalize(){if(this.zOne)return this;var zi=this.z.redInvm();this.x=this.x.redMul(zi);this.y=this.y.redMul(zi);if(this.t)this.t=this.t.redMul(zi);this.z=this.curve.one;this.zOne=true;return this};Point.prototype.neg=function neg(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())};Point.prototype.getX=function getX(){this.normalize();return this.x.fromRed()};Point.prototype.getY=function getY(){this.normalize();return this.y.fromRed()};Point.prototype.eq=function eq(other){return this===other||this.getX().cmp(other.getX())===0&&this.getY().cmp(other.getY())===0};Point.prototype.eqXToP=function eqXToP(x){var rx=x.toRed(this.curve.red).redMul(this.z);if(this.x.cmp(rx)===0)return true;var xc=x.clone();var t=this.curve.redN.redMul(this.z);for(;;){xc.iadd(this.curve.n);if(xc.cmp(this.curve.p)>=0)return false;rx.redIAdd(t);if(this.x.cmp(rx)===0)return true}};Point.prototype.toP=Point.prototype.normalize;Point.prototype.mixedAdd=Point.prototype.add},{"../utils":107,"./base":94,"bn.js":108,inherits:145}],96:[function(require,module,exports){"use strict";var curve=exports;curve.base=require("./base");curve.short=require("./short");curve.mont=require("./mont");curve.edwards=require("./edwards")},{"./base":94,"./edwards":95,"./mont":97,"./short":98}],97:[function(require,module,exports){"use strict";var BN=require("bn.js");var inherits=require("inherits");var Base=require("./base");var utils=require("../utils");function MontCurve(conf){Base.call(this,"mont",conf);this.a=new BN(conf.a,16).toRed(this.red);this.b=new BN(conf.b,16).toRed(this.red);this.i4=new BN(4).toRed(this.red).redInvm();this.two=new BN(2).toRed(this.red);this.a24=this.i4.redMul(this.a.redAdd(this.two))}inherits(MontCurve,Base);module.exports=MontCurve;MontCurve.prototype.validate=function validate(point){var x=point.normalize().x;var x2=x.redSqr();var rhs=x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);var y=rhs.redSqrt();return y.redSqr().cmp(rhs)===0};function Point(curve,x,z){Base.BasePoint.call(this,curve,"projective");if(x===null&&z===null){this.x=this.curve.one;this.z=this.curve.zero}else{this.x=new BN(x,16);this.z=new BN(z,16);if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.z.red)this.z=this.z.toRed(this.curve.red)}}inherits(Point,Base.BasePoint);MontCurve.prototype.decodePoint=function decodePoint(bytes,enc){return this.point(utils.toArray(bytes,enc),1)};MontCurve.prototype.point=function point(x,z){return new Point(this,x,z)};MontCurve.prototype.pointFromJSON=function pointFromJSON(obj){return Point.fromJSON(this,obj)};Point.prototype.precompute=function precompute(){};Point.prototype._encode=function _encode(){return this.getX().toArray("be",this.curve.p.byteLength())};Point.fromJSON=function fromJSON(curve,obj){return new Point(curve,obj[0],obj[1]||curve.one)};Point.prototype.inspect=function inspect(){if(this.isInfinity())return"<EC Point Infinity>";return"<EC Point x: "+this.x.fromRed().toString(16,2)+" z: "+this.z.fromRed().toString(16,2)+">"};Point.prototype.isInfinity=function isInfinity(){return this.z.cmpn(0)===0};Point.prototype.dbl=function dbl(){var a=this.x.redAdd(this.z);var aa=a.redSqr();var b=this.x.redSub(this.z);var bb=b.redSqr();var c=aa.redSub(bb);var nx=aa.redMul(bb);var nz=c.redMul(bb.redAdd(this.curve.a24.redMul(c)));return this.curve.point(nx,nz)};Point.prototype.add=function add(){throw new Error("Not supported on Montgomery curve")};Point.prototype.diffAdd=function diffAdd(p,diff){var a=this.x.redAdd(this.z);var b=this.x.redSub(this.z);var c=p.x.redAdd(p.z);var d=p.x.redSub(p.z);var da=d.redMul(a);var cb=c.redMul(b);var nx=diff.z.redMul(da.redAdd(cb).redSqr());var nz=diff.x.redMul(da.redISub(cb).redSqr());return this.curve.point(nx,nz)};Point.prototype.mul=function mul(k){var t=k.clone();var a=this;var b=this.curve.point(null,null);var c=this;for(var bits=[];t.cmpn(0)!==0;t.iushrn(1))bits.push(t.andln(1));for(var i=bits.length-1;i>=0;i--){if(bits[i]===0){a=a.diffAdd(b,c);b=b.dbl()}else{b=a.diffAdd(b,c);a=a.dbl()}}return b};Point.prototype.mulAdd=function mulAdd(){throw new Error("Not supported on Montgomery curve")};Point.prototype.jumlAdd=function jumlAdd(){throw new Error("Not supported on Montgomery curve")};Point.prototype.eq=function eq(other){return this.getX().cmp(other.getX())===0};Point.prototype.normalize=function normalize(){this.x=this.x.redMul(this.z.redInvm());this.z=this.curve.one;return this};Point.prototype.getX=function getX(){this.normalize();return this.x.fromRed()}},{"../utils":107,"./base":94,"bn.js":108,inherits:145}],98:[function(require,module,exports){"use strict";var utils=require("../utils");var BN=require("bn.js");var inherits=require("inherits");var Base=require("./base");var assert=utils.assert;function ShortCurve(conf){Base.call(this,"short",conf);this.a=new BN(conf.a,16).toRed(this.red);this.b=new BN(conf.b,16).toRed(this.red);this.tinv=this.two.redInvm();this.zeroA=this.a.fromRed().cmpn(0)===0;this.threeA=this.a.fromRed().sub(this.p).cmpn(-3)===0;this.endo=this._getEndomorphism(conf);this._endoWnafT1=new Array(4);this._endoWnafT2=new Array(4)}inherits(ShortCurve,Base);module.exports=ShortCurve;ShortCurve.prototype._getEndomorphism=function _getEndomorphism(conf){if(!this.zeroA||!this.g||!this.n||this.p.modn(3)!==1)return;var beta;var lambda;if(conf.beta){beta=new BN(conf.beta,16).toRed(this.red)}else{var betas=this._getEndoRoots(this.p);beta=betas[0].cmp(betas[1])<0?betas[0]:betas[1];beta=beta.toRed(this.red)}if(conf.lambda){lambda=new BN(conf.lambda,16)}else{var lambdas=this._getEndoRoots(this.n);if(this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta))===0){lambda=lambdas[0]}else{lambda=lambdas[1];assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta))===0)}}var basis;if(conf.basis){basis=conf.basis.map(function(vec){return{a:new BN(vec.a,16),b:new BN(vec.b,16)}})}else{basis=this._getEndoBasis(lambda)}return{beta:beta,lambda:lambda,basis:basis}};ShortCurve.prototype._getEndoRoots=function _getEndoRoots(num){var red=num===this.p?this.red:BN.mont(num);var tinv=new BN(2).toRed(red).redInvm();var ntinv=tinv.redNeg();var s=new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);var l1=ntinv.redAdd(s).fromRed();var l2=ntinv.redSub(s).fromRed();return[l1,l2]};ShortCurve.prototype._getEndoBasis=function _getEndoBasis(lambda){var aprxSqrt=this.n.ushrn(Math.floor(this.n.bitLength()/2));var u=lambda;var v=this.n.clone();var x1=new BN(1);var y1=new BN(0);var x2=new BN(0);var y2=new BN(1);var a0;var b0;var a1;var b1;var a2;var b2;var prevR;var i=0;var r;var x;while(u.cmpn(0)!==0){var q=v.div(u);r=v.sub(q.mul(u));x=x2.sub(q.mul(x1));var y=y2.sub(q.mul(y1));if(!a1&&r.cmp(aprxSqrt)<0){a0=prevR.neg();b0=x1;a1=r.neg();b1=x}else if(a1&&++i===2){break}prevR=r;v=u;u=r;x2=x1;x1=x;y2=y1;y1=y}a2=r.neg();b2=x;var len1=a1.sqr().add(b1.sqr());var len2=a2.sqr().add(b2.sqr());if(len2.cmp(len1)>=0){a2=a0;b2=b0}if(a1.negative){a1=a1.neg();b1=b1.neg()}if(a2.negative){a2=a2.neg();b2=b2.neg()}return[{a:a1,b:b1},{a:a2,b:b2}]};ShortCurve.prototype._endoSplit=function _endoSplit(k){var basis=this.endo.basis;var v1=basis[0];var v2=basis[1];var c1=v2.b.mul(k).divRound(this.n);var c2=v1.b.neg().mul(k).divRound(this.n);var p1=c1.mul(v1.a);var p2=c2.mul(v2.a);var q1=c1.mul(v1.b);var q2=c2.mul(v2.b);var k1=k.sub(p1).sub(p2);var k2=q1.add(q2).neg();return{k1:k1,k2:k2}};ShortCurve.prototype.pointFromX=function pointFromX(x,odd){x=new BN(x,16);if(!x.red)x=x.toRed(this.red);var y2=x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);var y=y2.redSqrt();if(y.redSqr().redSub(y2).cmp(this.zero)!==0)throw new Error("invalid point");var isOdd=y.fromRed().isOdd();if(odd&&!isOdd||!odd&&isOdd)y=y.redNeg();return this.point(x,y)};ShortCurve.prototype.validate=function validate(point){if(point.inf)return true;var x=point.x;var y=point.y;var ax=this.a.redMul(x);var rhs=x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);return y.redSqr().redISub(rhs).cmpn(0)===0};ShortCurve.prototype._endoWnafMulAdd=function _endoWnafMulAdd(points,coeffs,jacobianResult){var npoints=this._endoWnafT1;var ncoeffs=this._endoWnafT2;for(var i=0;i<points.length;i++){var split=this._endoSplit(coeffs[i]);var p=points[i];var beta=p._getBeta();if(split.k1.negative){split.k1.ineg();p=p.neg(true)}if(split.k2.negative){split.k2.ineg();beta=beta.neg(true)}npoints[i*2]=p;npoints[i*2+1]=beta;ncoeffs[i*2]=split.k1;ncoeffs[i*2+1]=split.k2}var res=this._wnafMulAdd(1,npoints,ncoeffs,i*2,jacobianResult);for(var j=0;j<i*2;j++){npoints[j]=null;ncoeffs[j]=null}return res};function Point(curve,x,y,isRed){Base.BasePoint.call(this,curve,"affine");if(x===null&&y===null){this.x=null;this.y=null;this.inf=true}else{this.x=new BN(x,16);this.y=new BN(y,16);if(isRed){this.x.forceRed(this.curve.red);this.y.forceRed(this.curve.red)}if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.y.red)this.y=this.y.toRed(this.curve.red);this.inf=false}}inherits(Point,Base.BasePoint);ShortCurve.prototype.point=function point(x,y,isRed){return new Point(this,x,y,isRed)};ShortCurve.prototype.pointFromJSON=function pointFromJSON(obj,red){return Point.fromJSON(this,obj,red)};Point.prototype._getBeta=function _getBeta(){if(!this.curve.endo)return;var pre=this.precomputed;if(pre&&pre.beta)return pre.beta;var beta=this.curve.point(this.x.redMul(this.curve.endo.beta),this.y);if(pre){var curve=this.curve;var endoMul=function(p){return curve.point(p.x.redMul(curve.endo.beta),p.y)};pre.beta=beta;beta.precomputed={beta:null,naf:pre.naf&&{wnd:pre.naf.wnd,points:pre.naf.points.map(endoMul)},doubles:pre.doubles&&{step:pre.doubles.step,points:pre.doubles.points.map(endoMul)}}}return beta};Point.prototype.toJSON=function toJSON(){if(!this.precomputed)return[this.x,this.y];return[this.x,this.y,this.precomputed&&{doubles:this.precomputed.doubles&&{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)},naf:this.precomputed.naf&&{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}}]};Point.fromJSON=function fromJSON(curve,obj,red){if(typeof obj==="string")obj=JSON.parse(obj);var res=curve.point(obj[0],obj[1],red);if(!obj[2])return res;function obj2point(obj){return curve.point(obj[0],obj[1],red)}var pre=obj[2];res.precomputed={beta:null,doubles:pre.doubles&&{step:pre.doubles.step,points:[res].concat(pre.doubles.points.map(obj2point))},naf:pre.naf&&{wnd:pre.naf.wnd,points:[res].concat(pre.naf.points.map(obj2point))}};return res};Point.prototype.inspect=function inspect(){if(this.isInfinity())return"<EC Point Infinity>";return"<EC Point x: "+this.x.fromRed().toString(16,2)+" y: "+this.y.fromRed().toString(16,2)+">"};Point.prototype.isInfinity=function isInfinity(){return this.inf};Point.prototype.add=function add(p){if(this.inf)return p;if(p.inf)return this;if(this.eq(p))return this.dbl();if(this.neg().eq(p))return this.curve.point(null,null);if(this.x.cmp(p.x)===0)return this.curve.point(null,null);var c=this.y.redSub(p.y);if(c.cmpn(0)!==0)c=c.redMul(this.x.redSub(p.x).redInvm());var nx=c.redSqr().redISub(this.x).redISub(p.x);var ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)};Point.prototype.dbl=function dbl(){if(this.inf)return this;var ys1=this.y.redAdd(this.y);if(ys1.cmpn(0)===0)return this.curve.point(null,null);var a=this.curve.a;var x2=this.x.redSqr();var dyinv=ys1.redInvm();var c=x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);var nx=c.redSqr().redISub(this.x.redAdd(this.x));var ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)};Point.prototype.getX=function getX(){return this.x.fromRed()};Point.prototype.getY=function getY(){return this.y.fromRed()};Point.prototype.mul=function mul(k){k=new BN(k,16);if(this.isInfinity())return this;else if(this._hasDoubles(k))return this.curve._fixedNafMul(this,k);else if(this.curve.endo)return this.curve._endoWnafMulAdd([this],[k]);else return this.curve._wnafMul(this,k)};Point.prototype.mulAdd=function mulAdd(k1,p2,k2){var points=[this,p2];var coeffs=[k1,k2];if(this.curve.endo)return this.curve._endoWnafMulAdd(points,coeffs);else return this.curve._wnafMulAdd(1,points,coeffs,2)};Point.prototype.jmulAdd=function jmulAdd(k1,p2,k2){var points=[this,p2];var coeffs=[k1,k2];if(this.curve.endo)return this.curve._endoWnafMulAdd(points,coeffs,true);else return this.curve._wnafMulAdd(1,points,coeffs,2,true)};Point.prototype.eq=function eq(p){return this===p||this.inf===p.inf&&(this.inf||this.x.cmp(p.x)===0&&this.y.cmp(p.y)===0)};Point.prototype.neg=function neg(_precompute){if(this.inf)return this;var res=this.curve.point(this.x,this.y.redNeg());if(_precompute&&this.precomputed){var pre=this.precomputed;var negate=function(p){return p.neg()};res.precomputed={naf:pre.naf&&{wnd:pre.naf.wnd,points:pre.naf.points.map(negate)},doubles:pre.doubles&&{step:pre.doubles.step,points:pre.doubles.points.map(negate)}}}return res};Point.prototype.toJ=function toJ(){if(this.inf)return this.curve.jpoint(null,null,null);var res=this.curve.jpoint(this.x,this.y,this.curve.one);return res};function JPoint(curve,x,y,z){Base.BasePoint.call(this,curve,"jacobian");if(x===null&&y===null&&z===null){this.x=this.curve.one;this.y=this.curve.one;this.z=new BN(0)}else{this.x=new BN(x,16);this.y=new BN(y,16);this.z=new BN(z,16)}if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.y.red)this.y=this.y.toRed(this.curve.red);if(!this.z.red)this.z=this.z.toRed(this.curve.red);this.zOne=this.z===this.curve.one}inherits(JPoint,Base.BasePoint);ShortCurve.prototype.jpoint=function jpoint(x,y,z){return new JPoint(this,x,y,z)};JPoint.prototype.toP=function toP(){if(this.isInfinity())return this.curve.point(null,null);var zinv=this.z.redInvm();var zinv2=zinv.redSqr();var ax=this.x.redMul(zinv2);var ay=this.y.redMul(zinv2).redMul(zinv);return this.curve.point(ax,ay)};JPoint.prototype.neg=function neg(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)};JPoint.prototype.add=function add(p){if(this.isInfinity())return p;if(p.isInfinity())return this;var pz2=p.z.redSqr();var z2=this.z.redSqr();var u1=this.x.redMul(pz2);var u2=p.x.redMul(z2);var s1=this.y.redMul(pz2.redMul(p.z));var s2=p.y.redMul(z2.redMul(this.z));var h=u1.redSub(u2);var r=s1.redSub(s2);if(h.cmpn(0)===0){if(r.cmpn(0)!==0)return this.curve.jpoint(null,null,null);else return this.dbl()}var h2=h.redSqr();var h3=h2.redMul(h);var v=u1.redMul(h2);var nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v);var ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));var nz=this.z.redMul(p.z).redMul(h);return this.curve.jpoint(nx,ny,nz)};JPoint.prototype.mixedAdd=function mixedAdd(p){if(this.isInfinity())return p.toJ();if(p.isInfinity())return this;var z2=this.z.redSqr();var u1=this.x;var u2=p.x.redMul(z2);var s1=this.y;var s2=p.y.redMul(z2).redMul(this.z);var h=u1.redSub(u2);var r=s1.redSub(s2);if(h.cmpn(0)===0){if(r.cmpn(0)!==0)return this.curve.jpoint(null,null,null);else return this.dbl()}var h2=h.redSqr();var h3=h2.redMul(h);var v=u1.redMul(h2);var nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v);var ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));var nz=this.z.redMul(h);return this.curve.jpoint(nx,ny,nz)};JPoint.prototype.dblp=function dblp(pow){if(pow===0)return this;if(this.isInfinity())return this;if(!pow)return this.dbl();var i;if(this.curve.zeroA||this.curve.threeA){var r=this;for(i=0;i<pow;i++)r=r.dbl();return r}var a=this.curve.a;var tinv=this.curve.tinv;var jx=this.x;var jy=this.y;var jz=this.z;var jz4=jz.redSqr().redSqr();var jyd=jy.redAdd(jy);for(i=0;i<pow;i++){var jx2=jx.redSqr();var jyd2=jyd.redSqr();var jyd4=jyd2.redSqr();var c=jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));var t1=jx.redMul(jyd2);var nx=c.redSqr().redISub(t1.redAdd(t1));var t2=t1.redISub(nx);var dny=c.redMul(t2);dny=dny.redIAdd(dny).redISub(jyd4);var nz=jyd.redMul(jz);if(i+1<pow)jz4=jz4.redMul(jyd4);jx=nx;jz=nz;jyd=dny}return this.curve.jpoint(jx,jyd.redMul(tinv),jz)};JPoint.prototype.dbl=function dbl(){if(this.isInfinity())return this;if(this.curve.zeroA)return this._zeroDbl();else if(this.curve.threeA)return this._threeDbl();else return this._dbl()};JPoint.prototype._zeroDbl=function _zeroDbl(){var nx;var ny;var nz;if(this.zOne){var xx=this.x.redSqr();var yy=this.y.redSqr();var yyyy=yy.redSqr();var s=this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);s=s.redIAdd(s);var m=xx.redAdd(xx).redIAdd(xx);var t=m.redSqr().redISub(s).redISub(s);var yyyy8=yyyy.redIAdd(yyyy);yyyy8=yyyy8.redIAdd(yyyy8);yyyy8=yyyy8.redIAdd(yyyy8);nx=t;ny=m.redMul(s.redISub(t)).redISub(yyyy8);nz=this.y.redAdd(this.y)}else{var a=this.x.redSqr();var b=this.y.redSqr();var c=b.redSqr();var d=this.x.redAdd(b).redSqr().redISub(a).redISub(c);d=d.redIAdd(d);var e=a.redAdd(a).redIAdd(a);var f=e.redSqr();var c8=c.redIAdd(c);c8=c8.redIAdd(c8);c8=c8.redIAdd(c8);nx=f.redISub(d).redISub(d);ny=e.redMul(d.redISub(nx)).redISub(c8);nz=this.y.redMul(this.z);nz=nz.redIAdd(nz)}return this.curve.jpoint(nx,ny,nz)};JPoint.prototype._threeDbl=function _threeDbl(){var nx;var ny;var nz;if(this.zOne){var xx=this.x.redSqr();var yy=this.y.redSqr();var yyyy=yy.redSqr();var s=this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);s=s.redIAdd(s);var m=xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);var t=m.redSqr().redISub(s).redISub(s);nx=t;var yyyy8=yyyy.redIAdd(yyyy);yyyy8=yyyy8.redIAdd(yyyy8);yyyy8=yyyy8.redIAdd(yyyy8);ny=m.redMul(s.redISub(t)).redISub(yyyy8);nz=this.y.redAdd(this.y)}else{var delta=this.z.redSqr();var gamma=this.y.redSqr();var beta=this.x.redMul(gamma);var alpha=this.x.redSub(delta).redMul(this.x.redAdd(delta));alpha=alpha.redAdd(alpha).redIAdd(alpha);var beta4=beta.redIAdd(beta);beta4=beta4.redIAdd(beta4);var beta8=beta4.redAdd(beta4);nx=alpha.redSqr().redISub(beta8);nz=this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);var ggamma8=gamma.redSqr();ggamma8=ggamma8.redIAdd(ggamma8);ggamma8=ggamma8.redIAdd(ggamma8);ggamma8=ggamma8.redIAdd(ggamma8);ny=alpha.redMul(beta4.redISub(nx)).redISub(ggamma8)}return this.curve.jpoint(nx,ny,nz)};JPoint.prototype._dbl=function _dbl(){var a=this.curve.a;var jx=this.x;var jy=this.y;var jz=this.z;var jz4=jz.redSqr().redSqr();var jx2=jx.redSqr();var jy2=jy.redSqr();var c=jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));var jxd4=jx.redAdd(jx);jxd4=jxd4.redIAdd(jxd4);var t1=jxd4.redMul(jy2);var nx=c.redSqr().redISub(t1.redAdd(t1));var t2=t1.redISub(nx);var jyd8=jy2.redSqr();jyd8=jyd8.redIAdd(jyd8);jyd8=jyd8.redIAdd(jyd8);jyd8=jyd8.redIAdd(jyd8);var ny=c.redMul(t2).redISub(jyd8);var nz=jy.redAdd(jy).redMul(jz);return this.curve.jpoint(nx,ny,nz)};JPoint.prototype.trpl=function trpl(){if(!this.curve.zeroA)return this.dbl().add(this);var xx=this.x.redSqr();var yy=this.y.redSqr();var zz=this.z.redSqr();var yyyy=yy.redSqr();var m=xx.redAdd(xx).redIAdd(xx);var mm=m.redSqr();var e=this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);e=e.redIAdd(e);e=e.redAdd(e).redIAdd(e);e=e.redISub(mm);var ee=e.redSqr();var t=yyyy.redIAdd(yyyy);t=t.redIAdd(t);t=t.redIAdd(t);t=t.redIAdd(t);var u=m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);var yyu4=yy.redMul(u);yyu4=yyu4.redIAdd(yyu4);yyu4=yyu4.redIAdd(yyu4);var nx=this.x.redMul(ee).redISub(yyu4);nx=nx.redIAdd(nx);nx=nx.redIAdd(nx);var ny=this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));ny=ny.redIAdd(ny);ny=ny.redIAdd(ny);ny=ny.redIAdd(ny);var nz=this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);return this.curve.jpoint(nx,ny,nz)};JPoint.prototype.mul=function mul(k,kbase){k=new BN(k,kbase);return this.curve._wnafMul(this,k)};JPoint.prototype.eq=function eq(p){if(p.type==="affine")return this.eq(p.toJ());if(this===p)return true;var z2=this.z.redSqr();var pz2=p.z.redSqr();if(this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0)!==0)return false;var z3=z2.redMul(this.z);var pz3=pz2.redMul(p.z);return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0)===0};JPoint.prototype.eqXToP=function eqXToP(x){var zs=this.z.redSqr();var rx=x.toRed(this.curve.red).redMul(zs);if(this.x.cmp(rx)===0)return true;var xc=x.clone();var t=this.curve.redN.redMul(zs);for(;;){xc.iadd(this.curve.n);if(xc.cmp(this.curve.p)>=0)return false;rx.redIAdd(t);if(this.x.cmp(rx)===0)return true}};JPoint.prototype.inspect=function inspect(){if(this.isInfinity())return"<EC JPoint Infinity>";return"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"};JPoint.prototype.isInfinity=function isInfinity(){return this.z.cmpn(0)===0}},{"../utils":107,"./base":94,"bn.js":108,inherits:145}],99:[function(require,module,exports){"use strict";var curves=exports;var hash=require("hash.js");var curve=require("./curve");var utils=require("./utils");var assert=utils.assert;function PresetCurve(options){
13
13
  if(options.type==="short")this.curve=new curve.short(options);else if(options.type==="edwards")this.curve=new curve.edwards(options);else this.curve=new curve.mont(options);this.g=this.curve.g;this.n=this.curve.n;this.hash=options.hash;assert(this.g.validate(),"Invalid curve");assert(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}curves.PresetCurve=PresetCurve;function defineCurve(name,options){Object.defineProperty(curves,name,{configurable:true,enumerable:true,get:function(){var curve=new PresetCurve(options);Object.defineProperty(curves,name,{configurable:true,enumerable:true,value:curve});return curve}})}defineCurve("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:hash.sha256,gRed:false,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]});defineCurve("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:hash.sha256,gRed:false,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]});defineCurve("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:hash.sha256,gRed:false,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]});defineCurve("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f "+"5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 "+"f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:hash.sha384,gRed:false,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 "+"5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 "+"0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]});defineCurve("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b "+"99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd "+"3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff "+"ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 "+"f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:hash.sha512,gRed:false,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 "+"053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 "+"a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 "+"579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 "+"3fad0761 353c7086 a272c240 88be9476 9fd16650"]});defineCurve("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash.sha256,gRed:false,g:["9"]});defineCurve("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash.sha256,gRed:false,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var pre;try{pre=require("./precomputed/secp256k1")}catch(e){pre=undefined}defineCurve("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:hash.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:false,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",pre]})},{"./curve":96,"./precomputed/secp256k1":106,"./utils":107,"hash.js":129}],100:[function(require,module,exports){"use strict";var BN=require("bn.js");var HmacDRBG=require("hmac-drbg");var utils=require("../utils");var curves=require("../curves");var rand=require("brorand");var assert=utils.assert;var KeyPair=require("./key");var Signature=require("./signature");function EC(options){if(!(this instanceof EC))return new EC(options);if(typeof options==="string"){assert(Object.prototype.hasOwnProperty.call(curves,options),"Unknown curve "+options);options=curves[options]}if(options instanceof curves.PresetCurve)options={curve:options};this.curve=options.curve.curve;this.n=this.curve.n;this.nh=this.n.ushrn(1);this.g=this.curve.g;this.g=options.curve.g;this.g.precompute(options.curve.n.bitLength()+1);this.hash=options.hash||options.curve.hash}module.exports=EC;EC.prototype.keyPair=function keyPair(options){return new KeyPair(this,options)};EC.prototype.keyFromPrivate=function keyFromPrivate(priv,enc){return KeyPair.fromPrivate(this,priv,enc)};EC.prototype.keyFromPublic=function keyFromPublic(pub,enc){return KeyPair.fromPublic(this,pub,enc)};EC.prototype.genKeyPair=function genKeyPair(options){if(!options)options={};var drbg=new HmacDRBG({hash:this.hash,pers:options.pers,persEnc:options.persEnc||"utf8",entropy:options.entropy||rand(this.hash.hmacStrength),entropyEnc:options.entropy&&options.entropyEnc||"utf8",nonce:this.n.toArray()});var bytes=this.n.byteLength();var ns2=this.n.sub(new BN(2));for(;;){var priv=new BN(drbg.generate(bytes));if(priv.cmp(ns2)>0)continue;priv.iaddn(1);return this.keyFromPrivate(priv)}};EC.prototype._truncateToN=function _truncateToN(msg,truncOnly){var delta=msg.byteLength()*8-this.n.bitLength();if(delta>0)msg=msg.ushrn(delta);if(!truncOnly&&msg.cmp(this.n)>=0)return msg.sub(this.n);else return msg};EC.prototype.sign=function sign(msg,key,enc,options){if(typeof enc==="object"){options=enc;enc=null}if(!options)options={};key=this.keyFromPrivate(key,enc);msg=this._truncateToN(new BN(msg,16));var bytes=this.n.byteLength();var bkey=key.getPrivate().toArray("be",bytes);var nonce=msg.toArray("be",bytes);var drbg=new HmacDRBG({hash:this.hash,entropy:bkey,nonce:nonce,pers:options.pers,persEnc:options.persEnc||"utf8"});var ns1=this.n.sub(new BN(1));for(var iter=0;;iter++){var k=options.k?options.k(iter):new BN(drbg.generate(this.n.byteLength()));k=this._truncateToN(k,true);if(k.cmpn(1)<=0||k.cmp(ns1)>=0)continue;var kp=this.g.mul(k);if(kp.isInfinity())continue;var kpX=kp.getX();var r=kpX.umod(this.n);if(r.cmpn(0)===0)continue;var s=k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));s=s.umod(this.n);if(s.cmpn(0)===0)continue;var recoveryParam=(kp.getY().isOdd()?1:0)|(kpX.cmp(r)!==0?2:0);if(options.canonical&&s.cmp(this.nh)>0){s=this.n.sub(s);recoveryParam^=1}return new Signature({r:r,s:s,recoveryParam:recoveryParam})}};EC.prototype.verify=function verify(msg,signature,key,enc){msg=this._truncateToN(new BN(msg,16));key=this.keyFromPublic(key,enc);signature=new Signature(signature,"hex");var r=signature.r;var s=signature.s;if(r.cmpn(1)<0||r.cmp(this.n)>=0)return false;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return false;var sinv=s.invm(this.n);var u1=sinv.mul(msg).umod(this.n);var u2=sinv.mul(r).umod(this.n);var p;if(!this.curve._maxwellTrick){p=this.g.mulAdd(u1,key.getPublic(),u2);if(p.isInfinity())return false;return p.getX().umod(this.n).cmp(r)===0}p=this.g.jmulAdd(u1,key.getPublic(),u2);if(p.isInfinity())return false;return p.eqXToP(r)};EC.prototype.recoverPubKey=function(msg,signature,j,enc){assert((3&j)===j,"The recovery param is more than two bits");signature=new Signature(signature,enc);var n=this.n;var e=new BN(msg);var r=signature.r;var s=signature.s;var isYOdd=j&1;var isSecondKey=j>>1;if(r.cmp(this.curve.p.umod(this.curve.n))>=0&&isSecondKey)throw new Error("Unable to find sencond key candinate");if(isSecondKey)r=this.curve.pointFromX(r.add(this.curve.n),isYOdd);else r=this.curve.pointFromX(r,isYOdd);var rInv=signature.r.invm(n);var s1=n.sub(e).mul(rInv).umod(n);var s2=s.mul(rInv).umod(n);return this.g.mulAdd(s1,r,s2)};EC.prototype.getKeyRecoveryParam=function(e,signature,Q,enc){signature=new Signature(signature,enc);if(signature.recoveryParam!==null)return signature.recoveryParam;for(var i=0;i<4;i++){var Qprime;try{Qprime=this.recoverPubKey(e,signature,i)}catch(e){continue}if(Qprime.eq(Q))return i}throw new Error("Unable to find valid recovery factor")}},{"../curves":99,"../utils":107,"./key":101,"./signature":102,"bn.js":108,brorand:22,"hmac-drbg":141}],101:[function(require,module,exports){"use strict";var BN=require("bn.js");var utils=require("../utils");var assert=utils.assert;function KeyPair(ec,options){this.ec=ec;this.priv=null;this.pub=null;if(options.priv)this._importPrivate(options.priv,options.privEnc);if(options.pub)this._importPublic(options.pub,options.pubEnc)}module.exports=KeyPair;KeyPair.fromPublic=function fromPublic(ec,pub,enc){if(pub instanceof KeyPair)return pub;return new KeyPair(ec,{pub:pub,pubEnc:enc})};KeyPair.fromPrivate=function fromPrivate(ec,priv,enc){if(priv instanceof KeyPair)return priv;return new KeyPair(ec,{priv:priv,privEnc:enc})};KeyPair.prototype.validate=function validate(){var pub=this.getPublic();if(pub.isInfinity())return{result:false,reason:"Invalid public key"};if(!pub.validate())return{result:false,reason:"Public key is not a point"};if(!pub.mul(this.ec.curve.n).isInfinity())return{result:false,reason:"Public key * N != O"};return{result:true,reason:null}};KeyPair.prototype.getPublic=function getPublic(compact,enc){if(typeof compact==="string"){enc=compact;compact=null}if(!this.pub)this.pub=this.ec.g.mul(this.priv);if(!enc)return this.pub;return this.pub.encode(enc,compact)};KeyPair.prototype.getPrivate=function getPrivate(enc){if(enc==="hex")return this.priv.toString(16,2);else return this.priv};KeyPair.prototype._importPrivate=function _importPrivate(key,enc){this.priv=new BN(key,enc||16);this.priv=this.priv.umod(this.ec.curve.n)};KeyPair.prototype._importPublic=function _importPublic(key,enc){if(key.x||key.y){if(this.ec.curve.type==="mont"){assert(key.x,"Need x coordinate")}else if(this.ec.curve.type==="short"||this.ec.curve.type==="edwards"){assert(key.x&&key.y,"Need both x and y coordinate")}this.pub=this.ec.curve.point(key.x,key.y);return}this.pub=this.ec.curve.decodePoint(key,enc)};KeyPair.prototype.derive=function derive(pub){if(!pub.validate()){assert(pub.validate(),"public point not validated")}return pub.mul(this.priv).getX()};KeyPair.prototype.sign=function sign(msg,enc,options){return this.ec.sign(msg,this,enc,options)};KeyPair.prototype.verify=function verify(msg,signature){return this.ec.verify(msg,signature,this)};KeyPair.prototype.inspect=function inspect(){return"<Key priv: "+(this.priv&&this.priv.toString(16,2))+" pub: "+(this.pub&&this.pub.inspect())+" >"}},{"../utils":107,"bn.js":108}],102:[function(require,module,exports){"use strict";var BN=require("bn.js");var utils=require("../utils");var assert=utils.assert;function Signature(options,enc){if(options instanceof Signature)return options;if(this._importDER(options,enc))return;assert(options.r&&options.s,"Signature without r or s");this.r=new BN(options.r,16);this.s=new BN(options.s,16);if(options.recoveryParam===undefined)this.recoveryParam=null;else this.recoveryParam=options.recoveryParam}module.exports=Signature;function Position(){this.place=0}function getLength(buf,p){var initial=buf[p.place++];if(!(initial&128)){return initial}var octetLen=initial&15;if(octetLen===0||octetLen>4){return false}var val=0;for(var i=0,off=p.place;i<octetLen;i++,off++){val<<=8;val|=buf[off];val>>>=0}if(val<=127){return false}p.place=off;return val}function rmPadding(buf){var i=0;var len=buf.length-1;while(!buf[i]&&!(buf[i+1]&128)&&i<len){i++}if(i===0){return buf}return buf.slice(i)}Signature.prototype._importDER=function _importDER(data,enc){data=utils.toArray(data,enc);var p=new Position;if(data[p.place++]!==48){return false}var len=getLength(data,p);if(len===false){return false}if(len+p.place!==data.length){return false}if(data[p.place++]!==2){return false}var rlen=getLength(data,p);if(rlen===false){return false}var r=data.slice(p.place,rlen+p.place);p.place+=rlen;if(data[p.place++]!==2){return false}var slen=getLength(data,p);if(slen===false){return false}if(data.length!==slen+p.place){return false}var s=data.slice(p.place,slen+p.place);if(r[0]===0){if(r[1]&128){r=r.slice(1)}else{return false}}if(s[0]===0){if(s[1]&128){s=s.slice(1)}else{return false}}this.r=new BN(r);this.s=new BN(s);this.recoveryParam=null;return true};function constructLength(arr,len){if(len<128){arr.push(len);return}var octets=1+(Math.log(len)/Math.LN2>>>3);arr.push(octets|128);while(--octets){arr.push(len>>>(octets<<3)&255)}arr.push(len)}Signature.prototype.toDER=function toDER(enc){var r=this.r.toArray();var s=this.s.toArray();if(r[0]&128)r=[0].concat(r);if(s[0]&128)s=[0].concat(s);r=rmPadding(r);s=rmPadding(s);while(!s[0]&&!(s[1]&128)){s=s.slice(1)}var arr=[2];constructLength(arr,r.length);arr=arr.concat(r);arr.push(2);constructLength(arr,s.length);var backHalf=arr.concat(s);var res=[48];constructLength(res,backHalf.length);res=res.concat(backHalf);return utils.encode(res,enc)}},{"../utils":107,"bn.js":108}],103:[function(require,module,exports){"use strict";var hash=require("hash.js");var curves=require("../curves");var utils=require("../utils");var assert=utils.assert;var parseBytes=utils.parseBytes;var KeyPair=require("./key");var Signature=require("./signature");function EDDSA(curve){assert(curve==="ed25519","only tested with ed25519 so far");if(!(this instanceof EDDSA))return new EDDSA(curve);curve=curves[curve].curve;this.curve=curve;this.g=curve.g;this.g.precompute(curve.n.bitLength()+1);this.pointClass=curve.point().constructor;this.encodingLength=Math.ceil(curve.n.bitLength()/8);this.hash=hash.sha512}module.exports=EDDSA;EDDSA.prototype.sign=function sign(message,secret){message=parseBytes(message);var key=this.keyFromSecret(secret);var r=this.hashInt(key.messagePrefix(),message);var R=this.g.mul(r);var Rencoded=this.encodePoint(R);var s_=this.hashInt(Rencoded,key.pubBytes(),message).mul(key.priv());var S=r.add(s_).umod(this.curve.n);return this.makeSignature({R:R,S:S,Rencoded:Rencoded})};EDDSA.prototype.verify=function verify(message,sig,pub){message=parseBytes(message);sig=this.makeSignature(sig);var key=this.keyFromPublic(pub);var h=this.hashInt(sig.Rencoded(),key.pubBytes(),message);var SG=this.g.mul(sig.S());var RplusAh=sig.R().add(key.pub().mul(h));return RplusAh.eq(SG)};EDDSA.prototype.hashInt=function hashInt(){var hash=this.hash();for(var i=0;i<arguments.length;i++)hash.update(arguments[i]);return utils.intFromLE(hash.digest()).umod(this.curve.n)};EDDSA.prototype.keyFromPublic=function keyFromPublic(pub){return KeyPair.fromPublic(this,pub)};EDDSA.prototype.keyFromSecret=function keyFromSecret(secret){return KeyPair.fromSecret(this,secret)};EDDSA.prototype.makeSignature=function makeSignature(sig){if(sig instanceof Signature)return sig;return new Signature(this,sig)};EDDSA.prototype.encodePoint=function encodePoint(point){var enc=point.getY().toArray("le",this.encodingLength);enc[this.encodingLength-1]|=point.getX().isOdd()?128:0;return enc};EDDSA.prototype.decodePoint=function decodePoint(bytes){bytes=utils.parseBytes(bytes);var lastIx=bytes.length-1;var normed=bytes.slice(0,lastIx).concat(bytes[lastIx]&~128);var xIsOdd=(bytes[lastIx]&128)!==0;var y=utils.intFromLE(normed);return this.curve.pointFromY(y,xIsOdd)};EDDSA.prototype.encodeInt=function encodeInt(num){return num.toArray("le",this.encodingLength)};EDDSA.prototype.decodeInt=function decodeInt(bytes){return utils.intFromLE(bytes)};EDDSA.prototype.isPoint=function isPoint(val){return val instanceof this.pointClass}},{"../curves":99,"../utils":107,"./key":104,"./signature":105,"hash.js":129}],104:[function(require,module,exports){"use strict";var utils=require("../utils");var assert=utils.assert;var parseBytes=utils.parseBytes;var cachedProperty=utils.cachedProperty;function KeyPair(eddsa,params){this.eddsa=eddsa;this._secret=parseBytes(params.secret);if(eddsa.isPoint(params.pub))this._pub=params.pub;else this._pubBytes=parseBytes(params.pub)}KeyPair.fromPublic=function fromPublic(eddsa,pub){if(pub instanceof KeyPair)return pub;return new KeyPair(eddsa,{pub:pub})};KeyPair.fromSecret=function fromSecret(eddsa,secret){if(secret instanceof KeyPair)return secret;return new KeyPair(eddsa,{secret:secret})};KeyPair.prototype.secret=function secret(){return this._secret};cachedProperty(KeyPair,"pubBytes",function pubBytes(){return this.eddsa.encodePoint(this.pub())});cachedProperty(KeyPair,"pub",function pub(){if(this._pubBytes)return this.eddsa.decodePoint(this._pubBytes);return this.eddsa.g.mul(this.priv())});cachedProperty(KeyPair,"privBytes",function privBytes(){var eddsa=this.eddsa;var hash=this.hash();var lastIx=eddsa.encodingLength-1;var a=hash.slice(0,eddsa.encodingLength);a[0]&=248;a[lastIx]&=127;a[lastIx]|=64;return a});cachedProperty(KeyPair,"priv",function priv(){return this.eddsa.decodeInt(this.privBytes())});cachedProperty(KeyPair,"hash",function hash(){return this.eddsa.hash().update(this.secret()).digest()});cachedProperty(KeyPair,"messagePrefix",function messagePrefix(){return this.hash().slice(this.eddsa.encodingLength)});KeyPair.prototype.sign=function sign(message){assert(this._secret,"KeyPair can only verify");return this.eddsa.sign(message,this)};KeyPair.prototype.verify=function verify(message,sig){return this.eddsa.verify(message,sig,this)};KeyPair.prototype.getSecret=function getSecret(enc){assert(this._secret,"KeyPair is public only");return utils.encode(this.secret(),enc)};KeyPair.prototype.getPublic=function getPublic(enc){return utils.encode(this.pubBytes(),enc)};module.exports=KeyPair},{"../utils":107}],105:[function(require,module,exports){"use strict";var BN=require("bn.js");var utils=require("../utils");var assert=utils.assert;var cachedProperty=utils.cachedProperty;var parseBytes=utils.parseBytes;function Signature(eddsa,sig){this.eddsa=eddsa;if(typeof sig!=="object")sig=parseBytes(sig);if(Array.isArray(sig)){sig={R:sig.slice(0,eddsa.encodingLength),S:sig.slice(eddsa.encodingLength)}}assert(sig.R&&sig.S,"Signature without R or S");if(eddsa.isPoint(sig.R))this._R=sig.R;if(sig.S instanceof BN)this._S=sig.S;this._Rencoded=Array.isArray(sig.R)?sig.R:sig.Rencoded;this._Sencoded=Array.isArray(sig.S)?sig.S:sig.Sencoded}cachedProperty(Signature,"S",function S(){return this.eddsa.decodeInt(this.Sencoded())});cachedProperty(Signature,"R",function R(){return this.eddsa.decodePoint(this.Rencoded())});cachedProperty(Signature,"Rencoded",function Rencoded(){return this.eddsa.encodePoint(this.R())});cachedProperty(Signature,"Sencoded",function Sencoded(){return this.eddsa.encodeInt(this.S())});Signature.prototype.toBytes=function toBytes(){return this.Rencoded().concat(this.Sencoded())};Signature.prototype.toHex=function toHex(){return utils.encode(this.toBytes(),"hex").toUpperCase()};module.exports=Signature},{"../utils":107,"bn.js":108}],106:[function(require,module,exports){module.exports={doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,
14
- points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}},{}],107:[function(require,module,exports){"use strict";var utils=exports;var BN=require("bn.js");var minAssert=require("minimalistic-assert");var minUtils=require("minimalistic-crypto-utils");utils.assert=minAssert;utils.toArray=minUtils.toArray;utils.zero2=minUtils.zero2;utils.toHex=minUtils.toHex;utils.encode=minUtils.encode;function getNAF(num,w,bits){var naf=new Array(Math.max(num.bitLength(),bits)+1);naf.fill(0);var ws=1<<w+1;var k=num.clone();for(var i=0;i<naf.length;i++){var z;var mod=k.andln(ws-1);if(k.isOdd()){if(mod>(ws>>1)-1)z=(ws>>1)-mod;else z=mod;k.isubn(z)}else{z=0}naf[i]=z;k.iushrn(1)}return naf}utils.getNAF=getNAF;function getJSF(k1,k2){var jsf=[[],[]];k1=k1.clone();k2=k2.clone();var d1=0;var d2=0;var m8;while(k1.cmpn(-d1)>0||k2.cmpn(-d2)>0){var m14=k1.andln(3)+d1&3;var m24=k2.andln(3)+d2&3;if(m14===3)m14=-1;if(m24===3)m24=-1;var u1;if((m14&1)===0){u1=0}else{m8=k1.andln(7)+d1&7;if((m8===3||m8===5)&&m24===2)u1=-m14;else u1=m14}jsf[0].push(u1);var u2;if((m24&1)===0){u2=0}else{m8=k2.andln(7)+d2&7;if((m8===3||m8===5)&&m14===2)u2=-m24;else u2=m24}jsf[1].push(u2);if(2*d1===u1+1)d1=1-d1;if(2*d2===u2+1)d2=1-d2;k1.iushrn(1);k2.iushrn(1)}return jsf}utils.getJSF=getJSF;function cachedProperty(obj,name,computer){var key="_"+name;obj.prototype[name]=function cachedProperty(){return this[key]!==undefined?this[key]:this[key]=computer.call(this)}}utils.cachedProperty=cachedProperty;function parseBytes(bytes){return typeof bytes==="string"?utils.toArray(bytes,"hex"):bytes}utils.parseBytes=parseBytes;function intFromLE(bytes){return new BN(bytes,"hex","le")}utils.intFromLE=intFromLE},{"bn.js":108,"minimalistic-assert":151,"minimalistic-crypto-utils":152}],108:[function(require,module,exports){arguments[4][15][0].apply(exports,arguments)},{buffer:23,dup:15}],109:[function(require,module,exports){module.exports={_from:"elliptic@^6.5.3",_id:"elliptic@6.5.4",_inBundle:false,_integrity:"sha512-iLhC6ULemrljPZb+QutR5TQGB+pdW6KGD5RSegS+8sorOZT+rdQFbsQFJgvN3eRqNALqJer4oQ16YvJHlU8hzQ==",_location:"/elliptic",_phantomChildren:{},_requested:{type:"range",registry:true,raw:"elliptic@^6.5.3",name:"elliptic",escapedName:"elliptic",rawSpec:"^6.5.3",saveSpec:null,fetchSpec:"^6.5.3"},_requiredBy:["/browserify-sign","/create-ecdh"],_resolved:"https://registry.npmjs.org/elliptic/-/elliptic-6.5.4.tgz",_shasum:"da37cebd31e79a1367e941b592ed1fbebd58abbb",_spec:"elliptic@^6.5.3",_where:"/var/lib/jenkins/workspace/.OnPremise.Agent.JavaScript_main/browser-agent/node_modules/browserify-sign",author:{name:"Fedor Indutny",email:"fedor@indutny.com"},bugs:{url:"https://github.com/indutny/elliptic/issues"},bundleDependencies:false,dependencies:{"bn.js":"^4.11.9",brorand:"^1.1.0","hash.js":"^1.0.0","hmac-drbg":"^1.0.1",inherits:"^2.0.4","minimalistic-assert":"^1.0.1","minimalistic-crypto-utils":"^1.0.1"},deprecated:false,description:"EC cryptography",devDependencies:{brfs:"^2.0.2",coveralls:"^3.1.0",eslint:"^7.6.0",grunt:"^1.2.1","grunt-browserify":"^5.3.0","grunt-cli":"^1.3.2","grunt-contrib-connect":"^3.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^5.0.0","grunt-mocha-istanbul":"^5.0.2","grunt-saucelabs":"^9.0.1",istanbul:"^0.4.5",mocha:"^8.0.1"},files:["lib"],homepage:"https://github.com/indutny/elliptic",keywords:["EC","Elliptic","curve","Cryptography"],license:"MIT",main:"lib/elliptic.js",name:"elliptic",repository:{type:"git",url:"git+ssh://git@github.com/indutny/elliptic.git"},scripts:{lint:"eslint lib test","lint:fix":"npm run lint -- --fix",test:"npm run lint && npm run unit",unit:"istanbul test _mocha --reporter=spec test/index.js",version:"grunt dist && git add dist/"},version:"6.5.4"}},{}],110:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{var err=new Error('Uncaught, unspecified "error" event. ('+er+")");err.context=er;throw err}}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1);handler.apply(this,args)}}else if(isObject(handler)){args=Array.prototype.slice.call(arguments,1);listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],111:[function(require,module,exports){var Buffer=require("safe-buffer").Buffer;var MD5=require("md5.js");function EVP_BytesToKey(password,salt,keyBits,ivLen){if(!Buffer.isBuffer(password))password=Buffer.from(password,"binary");if(salt){if(!Buffer.isBuffer(salt))salt=Buffer.from(salt,"binary");if(salt.length!==8)throw new RangeError("salt should be Buffer with 8 byte length")}var keyLen=keyBits/8;var key=Buffer.alloc(keyLen);var iv=Buffer.alloc(ivLen||0);var tmp=Buffer.alloc(0);while(keyLen>0||ivLen>0){var hash=new MD5;hash.update(tmp);hash.update(password);if(salt)hash.update(salt);tmp=hash.digest();var used=0;if(keyLen>0){var keyStart=key.length-keyLen;used=Math.min(keyLen,tmp.length);tmp.copy(key,keyStart,0,used);keyLen-=used}if(used<tmp.length&&ivLen>0){var ivStart=iv.length-ivLen;var length=Math.min(ivLen,tmp.length-used);tmp.copy(iv,ivStart,used,used+length);ivLen-=length}}tmp.fill(0);return{key:key,iv:iv}}module.exports=EVP_BytesToKey},{"md5.js":148,"safe-buffer":209}],112:[function(require,module,exports){"use strict";var Buffer=require("safe-buffer").Buffer;var Transform=require("readable-stream").Transform;var inherits=require("inherits");function throwIfNotStringOrBuffer(val,prefix){if(!Buffer.isBuffer(val)&&typeof val!=="string"){throw new TypeError(prefix+" must be a string or a buffer")}}function HashBase(blockSize){Transform.call(this);this._block=Buffer.allocUnsafe(blockSize);this._blockSize=blockSize;this._blockOffset=0;this._length=[0,0,0,0];this._finalized=false}inherits(HashBase,Transform);HashBase.prototype._transform=function(chunk,encoding,callback){var error=null;try{this.update(chunk,encoding)}catch(err){error=err}callback(error)};HashBase.prototype._flush=function(callback){var error=null;try{this.push(this.digest())}catch(err){error=err}callback(error)};HashBase.prototype.update=function(data,encoding){throwIfNotStringOrBuffer(data,"Data");if(this._finalized)throw new Error("Digest already called");if(!Buffer.isBuffer(data))data=Buffer.from(data,encoding);var block=this._block;var offset=0;while(this._blockOffset+data.length-offset>=this._blockSize){for(var i=this._blockOffset;i<this._blockSize;)block[i++]=data[offset++];this._update();this._blockOffset=0}while(offset<data.length)block[this._blockOffset++]=data[offset++];for(var j=0,carry=data.length*8;carry>0;++j){this._length[j]+=carry;carry=this._length[j]/4294967296|0;if(carry>0)this._length[j]-=4294967296*carry}return this};HashBase.prototype._update=function(){throw new Error("_update is not implemented")};HashBase.prototype.digest=function(encoding){if(this._finalized)throw new Error("Digest already called");this._finalized=true;var digest=this._digest();if(encoding!==undefined)digest=digest.toString(encoding);this._block.fill(0);this._blockOffset=0;for(var i=0;i<4;++i)this._length[i]=0;return digest};HashBase.prototype._digest=function(){throw new Error("_digest is not implemented")};module.exports=HashBase},{inherits:145,"readable-stream":127,"safe-buffer":209}],113:[function(require,module,exports){arguments[4][51][0].apply(exports,arguments)},{dup:51}],114:[function(require,module,exports){arguments[4][52][0].apply(exports,arguments)},{"./_stream_readable":116,"./_stream_writable":118,_process:179,dup:52,inherits:145}],115:[function(require,module,exports){arguments[4][53][0].apply(exports,arguments)},{"./_stream_transform":117,dup:53,inherits:145}],116:[function(require,module,exports){arguments[4][54][0].apply(exports,arguments)},{"../errors":113,"./_stream_duplex":114,"./internal/streams/async_iterator":119,"./internal/streams/buffer_list":120,"./internal/streams/destroy":121,"./internal/streams/from":123,"./internal/streams/state":125,"./internal/streams/stream":126,_process:179,buffer:71,dup:54,events:110,inherits:145,"string_decoder/":128,util:23}],117:[function(require,module,exports){arguments[4][55][0].apply(exports,arguments)},{"../errors":113,"./_stream_duplex":114,dup:55,inherits:145}],118:[function(require,module,exports){arguments[4][56][0].apply(exports,arguments)},{"../errors":113,"./_stream_duplex":114,"./internal/streams/destroy":121,"./internal/streams/state":125,"./internal/streams/stream":126,_process:179,buffer:71,dup:56,inherits:145,"util-deprecate":240}],119:[function(require,module,exports){arguments[4][57][0].apply(exports,arguments)},{"./end-of-stream":122,_process:179,dup:57}],120:[function(require,module,exports){arguments[4][58][0].apply(exports,arguments)},{buffer:71,dup:58,util:23}],121:[function(require,module,exports){arguments[4][59][0].apply(exports,arguments)},{_process:179,dup:59}],122:[function(require,module,exports){arguments[4][60][0].apply(exports,arguments)},{"../../../errors":113,dup:60}],123:[function(require,module,exports){arguments[4][61][0].apply(exports,arguments)},{dup:61}],124:[function(require,module,exports){arguments[4][62][0].apply(exports,arguments)},{"../../../errors":113,"./end-of-stream":122,dup:62}],125:[function(require,module,exports){arguments[4][63][0].apply(exports,arguments)},{"../../../errors":113,dup:63}],126:[function(require,module,exports){arguments[4][64][0].apply(exports,arguments)},{dup:64,events:110}],127:[function(require,module,exports){arguments[4][65][0].apply(exports,arguments)},{"./lib/_stream_duplex.js":114,"./lib/_stream_passthrough.js":115,"./lib/_stream_readable.js":116,"./lib/_stream_transform.js":117,"./lib/_stream_writable.js":118,"./lib/internal/streams/end-of-stream.js":122,"./lib/internal/streams/pipeline.js":124,dup:65}],128:[function(require,module,exports){arguments[4][66][0].apply(exports,arguments)},{dup:66,"safe-buffer":209}],129:[function(require,module,exports){var hash=exports;hash.utils=require("./hash/utils");hash.common=require("./hash/common");hash.sha=require("./hash/sha");hash.ripemd=require("./hash/ripemd");hash.hmac=require("./hash/hmac");hash.sha1=hash.sha.sha1;hash.sha256=hash.sha.sha256;hash.sha224=hash.sha.sha224;hash.sha384=hash.sha.sha384;hash.sha512=hash.sha.sha512;hash.ripemd160=hash.ripemd.ripemd160},{"./hash/common":130,"./hash/hmac":131,"./hash/ripemd":132,"./hash/sha":133,"./hash/utils":140}],130:[function(require,module,exports){"use strict";var utils=require("./utils");var assert=require("minimalistic-assert");function BlockHash(){this.pending=null;this.pendingTotal=0
14
+ points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}},{}],107:[function(require,module,exports){"use strict";var utils=exports;var BN=require("bn.js");var minAssert=require("minimalistic-assert");var minUtils=require("minimalistic-crypto-utils");utils.assert=minAssert;utils.toArray=minUtils.toArray;utils.zero2=minUtils.zero2;utils.toHex=minUtils.toHex;utils.encode=minUtils.encode;function getNAF(num,w,bits){var naf=new Array(Math.max(num.bitLength(),bits)+1);naf.fill(0);var ws=1<<w+1;var k=num.clone();for(var i=0;i<naf.length;i++){var z;var mod=k.andln(ws-1);if(k.isOdd()){if(mod>(ws>>1)-1)z=(ws>>1)-mod;else z=mod;k.isubn(z)}else{z=0}naf[i]=z;k.iushrn(1)}return naf}utils.getNAF=getNAF;function getJSF(k1,k2){var jsf=[[],[]];k1=k1.clone();k2=k2.clone();var d1=0;var d2=0;var m8;while(k1.cmpn(-d1)>0||k2.cmpn(-d2)>0){var m14=k1.andln(3)+d1&3;var m24=k2.andln(3)+d2&3;if(m14===3)m14=-1;if(m24===3)m24=-1;var u1;if((m14&1)===0){u1=0}else{m8=k1.andln(7)+d1&7;if((m8===3||m8===5)&&m24===2)u1=-m14;else u1=m14}jsf[0].push(u1);var u2;if((m24&1)===0){u2=0}else{m8=k2.andln(7)+d2&7;if((m8===3||m8===5)&&m14===2)u2=-m24;else u2=m24}jsf[1].push(u2);if(2*d1===u1+1)d1=1-d1;if(2*d2===u2+1)d2=1-d2;k1.iushrn(1);k2.iushrn(1)}return jsf}utils.getJSF=getJSF;function cachedProperty(obj,name,computer){var key="_"+name;obj.prototype[name]=function cachedProperty(){return this[key]!==undefined?this[key]:this[key]=computer.call(this)}}utils.cachedProperty=cachedProperty;function parseBytes(bytes){return typeof bytes==="string"?utils.toArray(bytes,"hex"):bytes}utils.parseBytes=parseBytes;function intFromLE(bytes){return new BN(bytes,"hex","le")}utils.intFromLE=intFromLE},{"bn.js":108,"minimalistic-assert":151,"minimalistic-crypto-utils":152}],108:[function(require,module,exports){arguments[4][15][0].apply(exports,arguments)},{buffer:23,dup:15}],109:[function(require,module,exports){module.exports={_from:"elliptic@^6.5.3",_id:"elliptic@6.5.4",_inBundle:false,_integrity:"sha512-iLhC6ULemrljPZb+QutR5TQGB+pdW6KGD5RSegS+8sorOZT+rdQFbsQFJgvN3eRqNALqJer4oQ16YvJHlU8hzQ==",_location:"/elliptic",_phantomChildren:{},_requested:{type:"range",registry:true,raw:"elliptic@^6.5.3",name:"elliptic",escapedName:"elliptic",rawSpec:"^6.5.3",saveSpec:null,fetchSpec:"^6.5.3"},_requiredBy:["/browserify-sign","/create-ecdh"],_resolved:"https://registry.npmjs.org/elliptic/-/elliptic-6.5.4.tgz",_shasum:"da37cebd31e79a1367e941b592ed1fbebd58abbb",_spec:"elliptic@^6.5.3",_where:"/var/lib/jenkins/workspace/.OnPremise.Agent.JavaScript_main@2/browser-agent/node_modules/browserify-sign",author:{name:"Fedor Indutny",email:"fedor@indutny.com"},bugs:{url:"https://github.com/indutny/elliptic/issues"},bundleDependencies:false,dependencies:{"bn.js":"^4.11.9",brorand:"^1.1.0","hash.js":"^1.0.0","hmac-drbg":"^1.0.1",inherits:"^2.0.4","minimalistic-assert":"^1.0.1","minimalistic-crypto-utils":"^1.0.1"},deprecated:false,description:"EC cryptography",devDependencies:{brfs:"^2.0.2",coveralls:"^3.1.0",eslint:"^7.6.0",grunt:"^1.2.1","grunt-browserify":"^5.3.0","grunt-cli":"^1.3.2","grunt-contrib-connect":"^3.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^5.0.0","grunt-mocha-istanbul":"^5.0.2","grunt-saucelabs":"^9.0.1",istanbul:"^0.4.5",mocha:"^8.0.1"},files:["lib"],homepage:"https://github.com/indutny/elliptic",keywords:["EC","Elliptic","curve","Cryptography"],license:"MIT",main:"lib/elliptic.js",name:"elliptic",repository:{type:"git",url:"git+ssh://git@github.com/indutny/elliptic.git"},scripts:{lint:"eslint lib test","lint:fix":"npm run lint -- --fix",test:"npm run lint && npm run unit",unit:"istanbul test _mocha --reporter=spec test/index.js",version:"grunt dist && git add dist/"},version:"6.5.4"}},{}],110:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{var err=new Error('Uncaught, unspecified "error" event. ('+er+")");err.context=er;throw err}}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1);handler.apply(this,args)}}else if(isObject(handler)){args=Array.prototype.slice.call(arguments,1);listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],111:[function(require,module,exports){var Buffer=require("safe-buffer").Buffer;var MD5=require("md5.js");function EVP_BytesToKey(password,salt,keyBits,ivLen){if(!Buffer.isBuffer(password))password=Buffer.from(password,"binary");if(salt){if(!Buffer.isBuffer(salt))salt=Buffer.from(salt,"binary");if(salt.length!==8)throw new RangeError("salt should be Buffer with 8 byte length")}var keyLen=keyBits/8;var key=Buffer.alloc(keyLen);var iv=Buffer.alloc(ivLen||0);var tmp=Buffer.alloc(0);while(keyLen>0||ivLen>0){var hash=new MD5;hash.update(tmp);hash.update(password);if(salt)hash.update(salt);tmp=hash.digest();var used=0;if(keyLen>0){var keyStart=key.length-keyLen;used=Math.min(keyLen,tmp.length);tmp.copy(key,keyStart,0,used);keyLen-=used}if(used<tmp.length&&ivLen>0){var ivStart=iv.length-ivLen;var length=Math.min(ivLen,tmp.length-used);tmp.copy(iv,ivStart,used,used+length);ivLen-=length}}tmp.fill(0);return{key:key,iv:iv}}module.exports=EVP_BytesToKey},{"md5.js":148,"safe-buffer":209}],112:[function(require,module,exports){"use strict";var Buffer=require("safe-buffer").Buffer;var Transform=require("readable-stream").Transform;var inherits=require("inherits");function throwIfNotStringOrBuffer(val,prefix){if(!Buffer.isBuffer(val)&&typeof val!=="string"){throw new TypeError(prefix+" must be a string or a buffer")}}function HashBase(blockSize){Transform.call(this);this._block=Buffer.allocUnsafe(blockSize);this._blockSize=blockSize;this._blockOffset=0;this._length=[0,0,0,0];this._finalized=false}inherits(HashBase,Transform);HashBase.prototype._transform=function(chunk,encoding,callback){var error=null;try{this.update(chunk,encoding)}catch(err){error=err}callback(error)};HashBase.prototype._flush=function(callback){var error=null;try{this.push(this.digest())}catch(err){error=err}callback(error)};HashBase.prototype.update=function(data,encoding){throwIfNotStringOrBuffer(data,"Data");if(this._finalized)throw new Error("Digest already called");if(!Buffer.isBuffer(data))data=Buffer.from(data,encoding);var block=this._block;var offset=0;while(this._blockOffset+data.length-offset>=this._blockSize){for(var i=this._blockOffset;i<this._blockSize;)block[i++]=data[offset++];this._update();this._blockOffset=0}while(offset<data.length)block[this._blockOffset++]=data[offset++];for(var j=0,carry=data.length*8;carry>0;++j){this._length[j]+=carry;carry=this._length[j]/4294967296|0;if(carry>0)this._length[j]-=4294967296*carry}return this};HashBase.prototype._update=function(){throw new Error("_update is not implemented")};HashBase.prototype.digest=function(encoding){if(this._finalized)throw new Error("Digest already called");this._finalized=true;var digest=this._digest();if(encoding!==undefined)digest=digest.toString(encoding);this._block.fill(0);this._blockOffset=0;for(var i=0;i<4;++i)this._length[i]=0;return digest};HashBase.prototype._digest=function(){throw new Error("_digest is not implemented")};module.exports=HashBase},{inherits:145,"readable-stream":127,"safe-buffer":209}],113:[function(require,module,exports){arguments[4][51][0].apply(exports,arguments)},{dup:51}],114:[function(require,module,exports){arguments[4][52][0].apply(exports,arguments)},{"./_stream_readable":116,"./_stream_writable":118,_process:179,dup:52,inherits:145}],115:[function(require,module,exports){arguments[4][53][0].apply(exports,arguments)},{"./_stream_transform":117,dup:53,inherits:145}],116:[function(require,module,exports){arguments[4][54][0].apply(exports,arguments)},{"../errors":113,"./_stream_duplex":114,"./internal/streams/async_iterator":119,"./internal/streams/buffer_list":120,"./internal/streams/destroy":121,"./internal/streams/from":123,"./internal/streams/state":125,"./internal/streams/stream":126,_process:179,buffer:71,dup:54,events:110,inherits:145,"string_decoder/":128,util:23}],117:[function(require,module,exports){arguments[4][55][0].apply(exports,arguments)},{"../errors":113,"./_stream_duplex":114,dup:55,inherits:145}],118:[function(require,module,exports){arguments[4][56][0].apply(exports,arguments)},{"../errors":113,"./_stream_duplex":114,"./internal/streams/destroy":121,"./internal/streams/state":125,"./internal/streams/stream":126,_process:179,buffer:71,dup:56,inherits:145,"util-deprecate":240}],119:[function(require,module,exports){arguments[4][57][0].apply(exports,arguments)},{"./end-of-stream":122,_process:179,dup:57}],120:[function(require,module,exports){arguments[4][58][0].apply(exports,arguments)},{buffer:71,dup:58,util:23}],121:[function(require,module,exports){arguments[4][59][0].apply(exports,arguments)},{_process:179,dup:59}],122:[function(require,module,exports){arguments[4][60][0].apply(exports,arguments)},{"../../../errors":113,dup:60}],123:[function(require,module,exports){arguments[4][61][0].apply(exports,arguments)},{dup:61}],124:[function(require,module,exports){arguments[4][62][0].apply(exports,arguments)},{"../../../errors":113,"./end-of-stream":122,dup:62}],125:[function(require,module,exports){arguments[4][63][0].apply(exports,arguments)},{"../../../errors":113,dup:63}],126:[function(require,module,exports){arguments[4][64][0].apply(exports,arguments)},{dup:64,events:110}],127:[function(require,module,exports){arguments[4][65][0].apply(exports,arguments)},{"./lib/_stream_duplex.js":114,"./lib/_stream_passthrough.js":115,"./lib/_stream_readable.js":116,"./lib/_stream_transform.js":117,"./lib/_stream_writable.js":118,"./lib/internal/streams/end-of-stream.js":122,"./lib/internal/streams/pipeline.js":124,dup:65}],128:[function(require,module,exports){arguments[4][66][0].apply(exports,arguments)},{dup:66,"safe-buffer":209}],129:[function(require,module,exports){var hash=exports;hash.utils=require("./hash/utils");hash.common=require("./hash/common");hash.sha=require("./hash/sha");hash.ripemd=require("./hash/ripemd");hash.hmac=require("./hash/hmac");hash.sha1=hash.sha.sha1;hash.sha256=hash.sha.sha256;hash.sha224=hash.sha.sha224;hash.sha384=hash.sha.sha384;hash.sha512=hash.sha.sha512;hash.ripemd160=hash.ripemd.ripemd160},{"./hash/common":130,"./hash/hmac":131,"./hash/ripemd":132,"./hash/sha":133,"./hash/utils":140}],130:[function(require,module,exports){"use strict";var utils=require("./utils");var assert=require("minimalistic-assert");function BlockHash(){this.pending=null;this.pendingTotal=0
15
15
  ;this.blockSize=this.constructor.blockSize;this.outSize=this.constructor.outSize;this.hmacStrength=this.constructor.hmacStrength;this.padLength=this.constructor.padLength/8;this.endian="big";this._delta8=this.blockSize/8;this._delta32=this.blockSize/32}exports.BlockHash=BlockHash;BlockHash.prototype.update=function update(msg,enc){msg=utils.toArray(msg,enc);if(!this.pending)this.pending=msg;else this.pending=this.pending.concat(msg);this.pendingTotal+=msg.length;if(this.pending.length>=this._delta8){msg=this.pending;var r=msg.length%this._delta8;this.pending=msg.slice(msg.length-r,msg.length);if(this.pending.length===0)this.pending=null;msg=utils.join32(msg,0,msg.length-r,this.endian);for(var i=0;i<msg.length;i+=this._delta32)this._update(msg,i,i+this._delta32)}return this};BlockHash.prototype.digest=function digest(enc){this.update(this._pad());assert(this.pending===null);return this._digest(enc)};BlockHash.prototype._pad=function pad(){var len=this.pendingTotal;var bytes=this._delta8;var k=bytes-(len+this.padLength)%bytes;var res=new Array(k+this.padLength);res[0]=128;for(var i=1;i<k;i++)res[i]=0;len<<=3;if(this.endian==="big"){for(var t=8;t<this.padLength;t++)res[i++]=0;res[i++]=0;res[i++]=0;res[i++]=0;res[i++]=0;res[i++]=len>>>24&255;res[i++]=len>>>16&255;res[i++]=len>>>8&255;res[i++]=len&255}else{res[i++]=len&255;res[i++]=len>>>8&255;res[i++]=len>>>16&255;res[i++]=len>>>24&255;res[i++]=0;res[i++]=0;res[i++]=0;res[i++]=0;for(t=8;t<this.padLength;t++)res[i++]=0}return res}},{"./utils":140,"minimalistic-assert":151}],131:[function(require,module,exports){"use strict";var utils=require("./utils");var assert=require("minimalistic-assert");function Hmac(hash,key,enc){if(!(this instanceof Hmac))return new Hmac(hash,key,enc);this.Hash=hash;this.blockSize=hash.blockSize/8;this.outSize=hash.outSize/8;this.inner=null;this.outer=null;this._init(utils.toArray(key,enc))}module.exports=Hmac;Hmac.prototype._init=function init(key){if(key.length>this.blockSize)key=(new this.Hash).update(key).digest();assert(key.length<=this.blockSize);for(var i=key.length;i<this.blockSize;i++)key.push(0);for(i=0;i<key.length;i++)key[i]^=54;this.inner=(new this.Hash).update(key);for(i=0;i<key.length;i++)key[i]^=106;this.outer=(new this.Hash).update(key)};Hmac.prototype.update=function update(msg,enc){this.inner.update(msg,enc);return this};Hmac.prototype.digest=function digest(enc){this.outer.update(this.inner.digest());return this.outer.digest(enc)}},{"./utils":140,"minimalistic-assert":151}],132:[function(require,module,exports){"use strict";var utils=require("./utils");var common=require("./common");var rotl32=utils.rotl32;var sum32=utils.sum32;var sum32_3=utils.sum32_3;var sum32_4=utils.sum32_4;var BlockHash=common.BlockHash;function RIPEMD160(){if(!(this instanceof RIPEMD160))return new RIPEMD160;BlockHash.call(this);this.h=[1732584193,4023233417,2562383102,271733878,3285377520];this.endian="little"}utils.inherits(RIPEMD160,BlockHash);exports.ripemd160=RIPEMD160;RIPEMD160.blockSize=512;RIPEMD160.outSize=160;RIPEMD160.hmacStrength=192;RIPEMD160.padLength=64;RIPEMD160.prototype._update=function update(msg,start){var A=this.h[0];var B=this.h[1];var C=this.h[2];var D=this.h[3];var E=this.h[4];var Ah=A;var Bh=B;var Ch=C;var Dh=D;var Eh=E;for(var j=0;j<80;j++){var T=sum32(rotl32(sum32_4(A,f(j,B,C,D),msg[r[j]+start],K(j)),s[j]),E);A=E;E=D;D=rotl32(C,10);C=B;B=T;T=sum32(rotl32(sum32_4(Ah,f(79-j,Bh,Ch,Dh),msg[rh[j]+start],Kh(j)),sh[j]),Eh);Ah=Eh;Eh=Dh;Dh=rotl32(Ch,10);Ch=Bh;Bh=T}T=sum32_3(this.h[1],C,Dh);this.h[1]=sum32_3(this.h[2],D,Eh);this.h[2]=sum32_3(this.h[3],E,Ah);this.h[3]=sum32_3(this.h[4],A,Bh);this.h[4]=sum32_3(this.h[0],B,Ch);this.h[0]=T};RIPEMD160.prototype._digest=function digest(enc){if(enc==="hex")return utils.toHex32(this.h,"little");else return utils.split32(this.h,"little")};function f(j,x,y,z){if(j<=15)return x^y^z;else if(j<=31)return x&y|~x&z;else if(j<=47)return(x|~y)^z;else if(j<=63)return x&z|y&~z;else return x^(y|~z)}function K(j){if(j<=15)return 0;else if(j<=31)return 1518500249;else if(j<=47)return 1859775393;else if(j<=63)return 2400959708;else return 2840853838}function Kh(j){if(j<=15)return 1352829926;else if(j<=31)return 1548603684;else if(j<=47)return 1836072691;else if(j<=63)return 2053994217;else return 0}var r=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13];var rh=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11];var s=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6];var sh=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]},{"./common":130,"./utils":140}],133:[function(require,module,exports){"use strict";exports.sha1=require("./sha/1");exports.sha224=require("./sha/224");exports.sha256=require("./sha/256");exports.sha384=require("./sha/384");exports.sha512=require("./sha/512")},{"./sha/1":134,"./sha/224":135,"./sha/256":136,"./sha/384":137,"./sha/512":138}],134:[function(require,module,exports){"use strict";var utils=require("../utils");var common=require("../common");var shaCommon=require("./common");var rotl32=utils.rotl32;var sum32=utils.sum32;var sum32_5=utils.sum32_5;var ft_1=shaCommon.ft_1;var BlockHash=common.BlockHash;var sha1_K=[1518500249,1859775393,2400959708,3395469782];function SHA1(){if(!(this instanceof SHA1))return new SHA1;BlockHash.call(this);this.h=[1732584193,4023233417,2562383102,271733878,3285377520];this.W=new Array(80)}utils.inherits(SHA1,BlockHash);module.exports=SHA1;SHA1.blockSize=512;SHA1.outSize=160;SHA1.hmacStrength=80;SHA1.padLength=64;SHA1.prototype._update=function _update(msg,start){var W=this.W;for(var i=0;i<16;i++)W[i]=msg[start+i];for(;i<W.length;i++)W[i]=rotl32(W[i-3]^W[i-8]^W[i-14]^W[i-16],1);var a=this.h[0];var b=this.h[1];var c=this.h[2];var d=this.h[3];var e=this.h[4];for(i=0;i<W.length;i++){var s=~~(i/20);var t=sum32_5(rotl32(a,5),ft_1(s,b,c,d),e,W[i],sha1_K[s]);e=d;d=c;c=rotl32(b,30);b=a;a=t}this.h[0]=sum32(this.h[0],a);this.h[1]=sum32(this.h[1],b);this.h[2]=sum32(this.h[2],c);this.h[3]=sum32(this.h[3],d);this.h[4]=sum32(this.h[4],e)};SHA1.prototype._digest=function digest(enc){if(enc==="hex")return utils.toHex32(this.h,"big");else return utils.split32(this.h,"big")}},{"../common":130,"../utils":140,"./common":139}],135:[function(require,module,exports){"use strict";var utils=require("../utils");var SHA256=require("./256");function SHA224(){if(!(this instanceof SHA224))return new SHA224;SHA256.call(this);this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}utils.inherits(SHA224,SHA256);module.exports=SHA224;SHA224.blockSize=512;SHA224.outSize=224;SHA224.hmacStrength=192;SHA224.padLength=64;SHA224.prototype._digest=function digest(enc){if(enc==="hex")return utils.toHex32(this.h.slice(0,7),"big");else return utils.split32(this.h.slice(0,7),"big")}},{"../utils":140,"./256":136}],136:[function(require,module,exports){"use strict";var utils=require("../utils");var common=require("../common");var shaCommon=require("./common");var assert=require("minimalistic-assert");var sum32=utils.sum32;var sum32_4=utils.sum32_4;var sum32_5=utils.sum32_5;var ch32=shaCommon.ch32;var maj32=shaCommon.maj32;var s0_256=shaCommon.s0_256;var s1_256=shaCommon.s1_256;var g0_256=shaCommon.g0_256;var g1_256=shaCommon.g1_256;var BlockHash=common.BlockHash;var sha256_K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function SHA256(){if(!(this instanceof SHA256))return new SHA256;BlockHash.call(this);this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];this.k=sha256_K;this.W=new Array(64)}utils.inherits(SHA256,BlockHash);module.exports=SHA256;SHA256.blockSize=512;SHA256.outSize=256;SHA256.hmacStrength=192;SHA256.padLength=64;SHA256.prototype._update=function _update(msg,start){var W=this.W;for(var i=0;i<16;i++)W[i]=msg[start+i];for(;i<W.length;i++)W[i]=sum32_4(g1_256(W[i-2]),W[i-7],g0_256(W[i-15]),W[i-16]);var a=this.h[0];var b=this.h[1];var c=this.h[2];var d=this.h[3];var e=this.h[4];var f=this.h[5];var g=this.h[6];var h=this.h[7];assert(this.k.length===W.length);for(i=0;i<W.length;i++){var T1=sum32_5(h,s1_256(e),ch32(e,f,g),this.k[i],W[i]);var T2=sum32(s0_256(a),maj32(a,b,c));h=g;g=f;f=e;e=sum32(d,T1);d=c;c=b;b=a;a=sum32(T1,T2)}this.h[0]=sum32(this.h[0],a);this.h[1]=sum32(this.h[1],b);this.h[2]=sum32(this.h[2],c);this.h[3]=sum32(this.h[3],d);this.h[4]=sum32(this.h[4],e);this.h[5]=sum32(this.h[5],f);this.h[6]=sum32(this.h[6],g);this.h[7]=sum32(this.h[7],h)};SHA256.prototype._digest=function digest(enc){if(enc==="hex")return utils.toHex32(this.h,"big");else return utils.split32(this.h,"big")}},{"../common":130,"../utils":140,"./common":139,"minimalistic-assert":151}],137:[function(require,module,exports){"use strict";var utils=require("../utils");var SHA512=require("./512");function SHA384(){if(!(this instanceof SHA384))return new SHA384;SHA512.call(this);this.h=[3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]}utils.inherits(SHA384,SHA512);module.exports=SHA384;SHA384.blockSize=1024;SHA384.outSize=384;SHA384.hmacStrength=192;SHA384.padLength=128;SHA384.prototype._digest=function digest(enc){if(enc==="hex")return utils.toHex32(this.h.slice(0,12),"big");else return utils.split32(this.h.slice(0,12),"big")}},{"../utils":140,"./512":138}],138:[function(require,module,exports){"use strict";var utils=require("../utils");var common=require("../common");var assert=require("minimalistic-assert");var rotr64_hi=utils.rotr64_hi;var rotr64_lo=utils.rotr64_lo;var shr64_hi=utils.shr64_hi;var shr64_lo=utils.shr64_lo;var sum64=utils.sum64;var sum64_hi=utils.sum64_hi;var sum64_lo=utils.sum64_lo;var sum64_4_hi=utils.sum64_4_hi;var sum64_4_lo=utils.sum64_4_lo;var sum64_5_hi=utils.sum64_5_hi;var sum64_5_lo=utils.sum64_5_lo;var BlockHash=common.BlockHash;var sha512_K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function SHA512(){if(!(this instanceof SHA512))return new SHA512;BlockHash.call(this);this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209];this.k=sha512_K;this.W=new Array(160)}utils.inherits(SHA512,BlockHash);module.exports=SHA512;SHA512.blockSize=1024;SHA512.outSize=512;SHA512.hmacStrength=192;SHA512.padLength=128;SHA512.prototype._prepareBlock=function _prepareBlock(msg,start){var W=this.W;for(var i=0;i<32;i++)W[i]=msg[start+i];for(;i<W.length;i+=2){var c0_hi=g1_512_hi(W[i-4],W[i-3]);var c0_lo=g1_512_lo(W[i-4],W[i-3]);var c1_hi=W[i-14];var c1_lo=W[i-13];var c2_hi=g0_512_hi(W[i-30],W[i-29]);var c2_lo=g0_512_lo(W[i-30],W[i-29]);var c3_hi=W[i-32];var c3_lo=W[i-31];W[i]=sum64_4_hi(c0_hi,c0_lo,c1_hi,c1_lo,c2_hi,c2_lo,c3_hi,c3_lo);W[i+1]=sum64_4_lo(c0_hi,c0_lo,c1_hi,c1_lo,c2_hi,c2_lo,c3_hi,c3_lo)}};SHA512.prototype._update=function _update(msg,start){this._prepareBlock(msg,start);var W=this.W;var ah=this.h[0];var al=this.h[1];var bh=this.h[2];var bl=this.h[3];var ch=this.h[4];var cl=this.h[5];var dh=this.h[6];var dl=this.h[7];var eh=this.h[8];var el=this.h[9];var fh=this.h[10];var fl=this.h[11];var gh=this.h[12];var gl=this.h[13];var hh=this.h[14];var hl=this.h[15];assert(this.k.length===W.length);for(var i=0;i<W.length;i+=2){var c0_hi=hh;var c0_lo=hl;var c1_hi=s1_512_hi(eh,el);var c1_lo=s1_512_lo(eh,el);var c2_hi=ch64_hi(eh,el,fh,fl,gh,gl);var c2_lo=ch64_lo(eh,el,fh,fl,gh,gl);var c3_hi=this.k[i];var c3_lo=this.k[i+1];var c4_hi=W[i];var c4_lo=W[i+1];var T1_hi=sum64_5_hi(c0_hi,c0_lo,c1_hi,c1_lo,c2_hi,c2_lo,c3_hi,c3_lo,c4_hi,c4_lo);var T1_lo=sum64_5_lo(c0_hi,c0_lo,c1_hi,c1_lo,c2_hi,c2_lo,c3_hi,c3_lo,c4_hi,c4_lo);c0_hi=s0_512_hi(ah,al);c0_lo=s0_512_lo(ah,al);c1_hi=maj64_hi(ah,al,bh,bl,ch,cl);c1_lo=maj64_lo(ah,al,bh,bl,ch,cl);var T2_hi=sum64_hi(c0_hi,c0_lo,c1_hi,c1_lo);var T2_lo=sum64_lo(c0_hi,c0_lo,c1_hi,c1_lo);hh=gh;hl=gl;gh=fh;gl=fl;fh=eh;fl=el;eh=sum64_hi(dh,dl,T1_hi,T1_lo);el=sum64_lo(dl,dl,T1_hi,T1_lo);dh=ch;dl=cl;ch=bh;cl=bl;bh=ah;bl=al;ah=sum64_hi(T1_hi,T1_lo,T2_hi,T2_lo);al=sum64_lo(T1_hi,T1_lo,T2_hi,T2_lo)}sum64(this.h,0,ah,al);sum64(this.h,2,bh,bl);sum64(this.h,4,ch,cl);sum64(this.h,6,dh,dl);sum64(this.h,8,eh,el);sum64(this.h,10,fh,fl);sum64(this.h,12,gh,gl);sum64(this.h,14,hh,hl)};SHA512.prototype._digest=function digest(enc){if(enc==="hex")return utils.toHex32(this.h,"big");else return utils.split32(this.h,"big")};function ch64_hi(xh,xl,yh,yl,zh){var r=xh&yh^~xh&zh;if(r<0)r+=4294967296;return r}function ch64_lo(xh,xl,yh,yl,zh,zl){var r=xl&yl^~xl&zl;if(r<0)r+=4294967296;return r}function maj64_hi(xh,xl,yh,yl,zh){var r=xh&yh^xh&zh^yh&zh;if(r<0)r+=4294967296;return r}function maj64_lo(xh,xl,yh,yl,zh,zl){var r=xl&yl^xl&zl^yl&zl;if(r<0)r+=4294967296;return r}function s0_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,28);var c1_hi=rotr64_hi(xl,xh,2);var c2_hi=rotr64_hi(xl,xh,7);var r=c0_hi^c1_hi^c2_hi;if(r<0)r+=4294967296;return r}function s0_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,28);var c1_lo=rotr64_lo(xl,xh,2);var c2_lo=rotr64_lo(xl,xh,7);var r=c0_lo^c1_lo^c2_lo;if(r<0)r+=4294967296;return r}function s1_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,14);var c1_hi=rotr64_hi(xh,xl,18);var c2_hi=rotr64_hi(xl,xh,9);var r=c0_hi^c1_hi^c2_hi;if(r<0)r+=4294967296;return r}function s1_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,14);var c1_lo=rotr64_lo(xh,xl,18);var c2_lo=rotr64_lo(xl,xh,9);var r=c0_lo^c1_lo^c2_lo;if(r<0)r+=4294967296;return r}function g0_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,1);var c1_hi=rotr64_hi(xh,xl,8);var c2_hi=shr64_hi(xh,xl,7);var r=c0_hi^c1_hi^c2_hi;if(r<0)r+=4294967296;return r}function g0_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,1);var c1_lo=rotr64_lo(xh,xl,8);var c2_lo=shr64_lo(xh,xl,7);var r=c0_lo^c1_lo^c2_lo;if(r<0)r+=4294967296;return r}function g1_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,19);var c1_hi=rotr64_hi(xl,xh,29);var c2_hi=shr64_hi(xh,xl,6);var r=c0_hi^c1_hi^c2_hi;if(r<0)r+=4294967296;return r}function g1_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,19);var c1_lo=rotr64_lo(xl,xh,29);var c2_lo=shr64_lo(xh,xl,6);var r=c0_lo^c1_lo^c2_lo;if(r<0)r+=4294967296;return r}},{"../common":130,"../utils":140,"minimalistic-assert":151}],139:[function(require,module,exports){"use strict";var utils=require("../utils");var rotr32=utils.rotr32;function ft_1(s,x,y,z){if(s===0)return ch32(x,y,z);if(s===1||s===3)return p32(x,y,z);if(s===2)return maj32(x,y,z)}exports.ft_1=ft_1;function ch32(x,y,z){return x&y^~x&z}exports.ch32=ch32;function maj32(x,y,z){return x&y^x&z^y&z}exports.maj32=maj32;function p32(x,y,z){return x^y^z}exports.p32=p32;function s0_256(x){return rotr32(x,2)^rotr32(x,13)^rotr32(x,22)}exports.s0_256=s0_256;function s1_256(x){return rotr32(x,6)^rotr32(x,11)^rotr32(x,25)}exports.s1_256=s1_256;function g0_256(x){return rotr32(x,7)^rotr32(x,18)^x>>>3}exports.g0_256=g0_256;function g1_256(x){return rotr32(x,17)^rotr32(x,19)^x>>>10}exports.g1_256=g1_256},{"../utils":140}],140:[function(require,module,exports){"use strict";var assert=require("minimalistic-assert");var inherits=require("inherits");exports.inherits=inherits;function isSurrogatePair(msg,i){if((msg.charCodeAt(i)&64512)!==55296){return false}if(i<0||i+1>=msg.length){return false}return(msg.charCodeAt(i+1)&64512)===56320}function toArray(msg,enc){if(Array.isArray(msg))return msg.slice();if(!msg)return[];var res=[];if(typeof msg==="string"){if(!enc){var p=0;for(var i=0;i<msg.length;i++){var c=msg.charCodeAt(i);if(c<128){res[p++]=c}else if(c<2048){res[p++]=c>>6|192;res[p++]=c&63|128}else if(isSurrogatePair(msg,i)){c=65536+((c&1023)<<10)+(msg.charCodeAt(++i)&1023);res[p++]=c>>18|240;res[p++]=c>>12&63|128;res[p++]=c>>6&63|128;res[p++]=c&63|128}else{res[p++]=c>>12|224;res[p++]=c>>6&63|128;res[p++]=c&63|128}}}else if(enc==="hex"){msg=msg.replace(/[^a-z0-9]+/gi,"");if(msg.length%2!==0)msg="0"+msg;for(i=0;i<msg.length;i+=2)res.push(parseInt(msg[i]+msg[i+1],16))}}else{for(i=0;i<msg.length;i++)res[i]=msg[i]|0}return res}exports.toArray=toArray;function toHex(msg){var res="";for(var i=0;i<msg.length;i++)res+=zero2(msg[i].toString(16));return res}exports.toHex=toHex;function htonl(w){var res=w>>>24|w>>>8&65280|w<<8&16711680|(w&255)<<24;return res>>>0}exports.htonl=htonl;function toHex32(msg,endian){var res="";for(var i=0;i<msg.length;i++){var w=msg[i];if(endian==="little")w=htonl(w);res+=zero8(w.toString(16))}return res}exports.toHex32=toHex32;function zero2(word){if(word.length===1)return"0"+word;else return word}exports.zero2=zero2;function zero8(word){if(word.length===7)return"0"+word;else if(word.length===6)return"00"+word;else if(word.length===5)return"000"+word;else if(word.length===4)return"0000"+word;else if(word.length===3)return"00000"+word;else if(word.length===2)return"000000"+word;else if(word.length===1)return"0000000"+word;else return word}exports.zero8=zero8;function join32(msg,start,end,endian){var len=end-start;assert(len%4===0);var res=new Array(len/4);for(var i=0,k=start;i<res.length;i++,k+=4){var w;if(endian==="big")w=msg[k]<<24|msg[k+1]<<16|msg[k+2]<<8|msg[k+3];else w=msg[k+3]<<24|msg[k+2]<<16|msg[k+1]<<8|msg[k];res[i]=w>>>0}return res}exports.join32=join32;function split32(msg,endian){var res=new Array(msg.length*4);for(var i=0,k=0;i<msg.length;i++,k+=4){var m=msg[i];if(endian==="big"){res[k]=m>>>24;res[k+1]=m>>>16&255;res[k+2]=m>>>8&255;res[k+3]=m&255}else{res[k+3]=m>>>24;res[k+2]=m>>>16&255;res[k+1]=m>>>8&255;res[k]=m&255}}return res}exports.split32=split32;function rotr32(w,b){return w>>>b|w<<32-b}exports.rotr32=rotr32;function rotl32(w,b){return w<<b|w>>>32-b}exports.rotl32=rotl32;function sum32(a,b){return a+b>>>0}exports.sum32=sum32;function sum32_3(a,b,c){return a+b+c>>>0}exports.sum32_3=sum32_3;function sum32_4(a,b,c,d){return a+b+c+d>>>0}exports.sum32_4=sum32_4;function sum32_5(a,b,c,d,e){return a+b+c+d+e>>>0}exports.sum32_5=sum32_5;function sum64(buf,pos,ah,al){var bh=buf[pos];var bl=buf[pos+1];var lo=al+bl>>>0;var hi=(lo<al?1:0)+ah+bh;buf[pos]=hi>>>0;buf[pos+1]=lo}exports.sum64=sum64;function sum64_hi(ah,al,bh,bl){var lo=al+bl>>>0;var hi=(lo<al?1:0)+ah+bh;return hi>>>0}exports.sum64_hi=sum64_hi;function sum64_lo(ah,al,bh,bl){var lo=al+bl;return lo>>>0}exports.sum64_lo=sum64_lo;function sum64_4_hi(ah,al,bh,bl,ch,cl,dh,dl){var carry=0;var lo=al;lo=lo+bl>>>0;carry+=lo<al?1:0;lo=lo+cl>>>0;carry+=lo<cl?1:0;lo=lo+dl>>>0;carry+=lo<dl?1:0;var hi=ah+bh+ch+dh+carry;return hi>>>0}exports.sum64_4_hi=sum64_4_hi;function sum64_4_lo(ah,al,bh,bl,ch,cl,dh,dl){var lo=al+bl+cl+dl;return lo>>>0}exports.sum64_4_lo=sum64_4_lo;function sum64_5_hi(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var carry=0;var lo=al;lo=lo+bl>>>0;carry+=lo<al?1:0;lo=lo+cl>>>0;carry+=lo<cl?1:0;lo=lo+dl>>>0;carry+=lo<dl?1:0;lo=lo+el>>>0;carry+=lo<el?1:0;var hi=ah+bh+ch+dh+eh+carry;return hi>>>0}exports.sum64_5_hi=sum64_5_hi;function sum64_5_lo(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var lo=al+bl+cl+dl+el;return lo>>>0}exports.sum64_5_lo=sum64_5_lo;function rotr64_hi(ah,al,num){var r=al<<32-num|ah>>>num;return r>>>0}exports.rotr64_hi=rotr64_hi;function rotr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}exports.rotr64_lo=rotr64_lo;function shr64_hi(ah,al,num){return ah>>>num}exports.shr64_hi=shr64_hi;function shr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}exports.shr64_lo=shr64_lo},{inherits:145,"minimalistic-assert":151}],141:[function(require,module,exports){"use strict";var hash=require("hash.js");var utils=require("minimalistic-crypto-utils");var assert=require("minimalistic-assert");function HmacDRBG(options){if(!(this instanceof HmacDRBG))return new HmacDRBG(options);this.hash=options.hash;this.predResist=!!options.predResist;this.outLen=this.hash.outSize;this.minEntropy=options.minEntropy||this.hash.hmacStrength;this._reseed=null;this.reseedInterval=null;this.K=null;this.V=null;var entropy=utils.toArray(options.entropy,options.entropyEnc||"hex");var nonce=utils.toArray(options.nonce,options.nonceEnc||"hex");var pers=utils.toArray(options.pers,options.persEnc||"hex");assert(entropy.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits");this._init(entropy,nonce,pers)}module.exports=HmacDRBG;HmacDRBG.prototype._init=function init(entropy,nonce,pers){var seed=entropy.concat(nonce).concat(pers);this.K=new Array(this.outLen/8);this.V=new Array(this.outLen/8);for(var i=0;i<this.V.length;i++){this.K[i]=0;this.V[i]=1}this._update(seed);this._reseed=1;this.reseedInterval=281474976710656};HmacDRBG.prototype._hmac=function hmac(){return new hash.hmac(this.hash,this.K)};HmacDRBG.prototype._update=function update(seed){var kmac=this._hmac().update(this.V).update([0]);if(seed)kmac=kmac.update(seed);this.K=kmac.digest();this.V=this._hmac().update(this.V).digest();if(!seed)return;this.K=this._hmac().update(this.V).update([1]).update(seed).digest();this.V=this._hmac().update(this.V).digest()};HmacDRBG.prototype.reseed=function reseed(entropy,entropyEnc,add,addEnc){if(typeof entropyEnc!=="string"){addEnc=add;add=entropyEnc;entropyEnc=null}entropy=utils.toArray(entropy,entropyEnc);add=utils.toArray(add,addEnc);assert(entropy.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits");this._update(entropy.concat(add||[]));this._reseed=1};HmacDRBG.prototype.generate=function generate(len,enc,add,addEnc){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");if(typeof enc!=="string"){addEnc=add;add=enc;enc=null}if(add){add=utils.toArray(add,addEnc||"hex");this._update(add)}var temp=[];while(temp.length<len){this.V=this._hmac().update(this.V).digest();temp=temp.concat(this.V)}var res=temp.slice(0,len);this._update(add);this._reseed++;return utils.encode(res,enc)}},{"hash.js":129,"minimalistic-assert":151,"minimalistic-crypto-utils":152}],142:[function(require,module,exports){var http=require("http");var url=require("url");var https=module.exports;for(var key in http){if(http.hasOwnProperty(key))https[key]=http[key]}https.request=function(params,cb){params=validateParams(params);return http.request.call(this,params,cb)};https.get=function(params,cb){params=validateParams(params);return http.get.call(this,params,cb)};function validateParams(params){if(typeof params==="string"){params=url.parse(params)}if(!params.protocol){params.protocol="https:"}if(params.protocol!=="https:"){throw new Error('Protocol "'+params.protocol+'" not supported. Expected "https:"')}return params}},{http:230,url:238}],143:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],144:[function(require,module,exports){var indexOf=[].indexOf;module.exports=function(arr,obj){if(indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}},{}],145:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}}else{module.exports=function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}}},{}],146:[function(require,module,exports){module.exports=function(obj){return obj!=null&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)};function isBuffer(obj){return!!obj.constructor&&typeof obj.constructor.isBuffer==="function"&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return typeof obj.readFloatLE==="function"&&typeof obj.slice==="function"&&isBuffer(obj.slice(0,0))}},{}],147:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],148:[function(require,module,exports){"use strict";var inherits=require("inherits");var HashBase=require("hash-base");var Buffer=require("safe-buffer").Buffer;var ARRAY16=new Array(16);function MD5(){HashBase.call(this,64);this._a=1732584193;this._b=4023233417;this._c=2562383102;this._d=271733878}inherits(MD5,HashBase);MD5.prototype._update=function(){var M=ARRAY16;for(var i=0;i<16;++i)M[i]=this._block.readInt32LE(i*4);var a=this._a;var b=this._b;var c=this._c;var d=this._d;a=fnF(a,b,c,d,M[0],3614090360,7);d=fnF(d,a,b,c,M[1],3905402710,12);c=fnF(c,d,a,b,M[2],606105819,17);b=fnF(b,c,d,a,M[3],3250441966,22);a=fnF(a,b,c,d,M[4],4118548399,7);d=fnF(d,a,b,c,M[5],1200080426,12);c=fnF(c,d,a,b,M[6],2821735955,17);b=fnF(b,c,d,a,M[7],4249261313,22);a=fnF(a,b,c,d,M[8],1770035416,7);d=fnF(d,a,b,c,M[9],2336552879,12);c=fnF(c,d,a,b,M[10],4294925233,17);b=fnF(b,c,d,a,M[11],2304563134,22);a=fnF(a,b,c,d,M[12],1804603682,7);d=fnF(d,a,b,c,M[13],4254626195,12);c=fnF(c,d,a,b,M[14],2792965006,17);b=fnF(b,c,d,a,M[15],1236535329,22);a=fnG(a,b,c,d,M[1],4129170786,5);d=fnG(d,a,b,c,M[6],3225465664,9);c=fnG(c,d,a,b,M[11],643717713,14);b=fnG(b,c,d,a,M[0],3921069994,20);a=fnG(a,b,c,d,M[5],3593408605,5);d=fnG(d,a,b,c,M[10],38016083,9);c=fnG(c,d,a,b,M[15],3634488961,14);b=fnG(b,c,d,a,M[4],3889429448,20);a=fnG(a,b,c,d,M[9],568446438,5);d=fnG(d,a,b,c,M[14],3275163606,9);c=fnG(c,d,a,b,M[3],4107603335,14);b=fnG(b,c,d,a,M[8],1163531501,20);a=fnG(a,b,c,d,M[13],2850285829,5);d=fnG(d,a,b,c,M[2],4243563512,9);c=fnG(c,d,a,b,M[7],1735328473,14);b=fnG(b,c,d,a,M[12],2368359562,20);a=fnH(a,b,c,d,M[5],4294588738,4);d=fnH(d,a,b,c,M[8],2272392833,11);c=fnH(c,d,a,b,M[11],1839030562,16);b=fnH(b,c,d,a,M[14],4259657740,23);a=fnH(a,b,c,d,M[1],2763975236,4);d=fnH(d,a,b,c,M[4],1272893353,11);c=fnH(c,d,a,b,M[7],4139469664,16);b=fnH(b,c,d,a,M[10],3200236656,23);a=fnH(a,b,c,d,M[13],681279174,4);d=fnH(d,a,b,c,M[0],3936430074,11);c=fnH(c,d,a,b,M[3],3572445317,16);b=fnH(b,c,d,a,M[6],76029189,23);a=fnH(a,b,c,d,M[9],3654602809,4);d=fnH(d,a,b,c,M[12],3873151461,11);c=fnH(c,d,a,b,M[15],530742520,16);b=fnH(b,c,d,a,M[2],3299628645,23);a=fnI(a,b,c,d,M[0],4096336452,6);d=fnI(d,a,b,c,M[7],1126891415,10);c=fnI(c,d,a,b,M[14],2878612391,15);b=fnI(b,c,d,a,M[5],4237533241,21);a=fnI(a,b,c,d,M[12],1700485571,6);d=fnI(d,a,b,c,M[3],2399980690,10);c=fnI(c,d,a,b,M[10],4293915773,15);b=fnI(b,c,d,a,M[1],2240044497,21);a=fnI(a,b,c,d,M[8],1873313359,6);d=fnI(d,a,b,c,M[15],4264355552,10);c=fnI(c,d,a,b,M[6],2734768916,15);b=fnI(b,c,d,a,M[13],1309151649,21);a=fnI(a,b,c,d,M[4],4149444226,6);d=fnI(d,a,b,c,M[11],3174756917,10);c=fnI(c,d,a,b,M[2],718787259,15);b=fnI(b,c,d,a,M[9],3951481745,21);this._a=this._a+a|0;this._b=this._b+b|0;this._c=this._c+c|0;this._d=this._d+d|0};MD5.prototype._digest=function(){this._block[this._blockOffset++]=128;if(this._blockOffset>56){this._block.fill(0,this._blockOffset,64);this._update();this._blockOffset=0}this._block.fill(0,this._blockOffset,56);this._block.writeUInt32LE(this._length[0],56);this._block.writeUInt32LE(this._length[1],60);this._update();var buffer=Buffer.allocUnsafe(16);buffer.writeInt32LE(this._a,0);buffer.writeInt32LE(this._b,4);buffer.writeInt32LE(this._c,8);buffer.writeInt32LE(this._d,12);return buffer};function rotl(x,n){return x<<n|x>>>32-n}function fnF(a,b,c,d,m,k,s){return rotl(a+(b&c|~b&d)+m+k|0,s)+b|0}function fnG(a,b,c,d,m,k,s){return rotl(a+(b&d|c&~d)+m+k|0,s)+b|0}function fnH(a,b,c,d,m,k,s){return rotl(a+(b^c^d)+m+k|0,s)+b|0}function fnI(a,b,c,d,m,k,s){return rotl(a+(c^(b|~d))+m+k|0,s)+b|0}module.exports=MD5},{"hash-base":112,inherits:145,"safe-buffer":209}],149:[function(require,module,exports){var bn=require("bn.js");var brorand=require("brorand");function MillerRabin(rand){this.rand=rand||new brorand.Rand}module.exports=MillerRabin;MillerRabin.create=function create(rand){return new MillerRabin(rand)};MillerRabin.prototype._randbelow=function _randbelow(n){var len=n.bitLength();var min_bytes=Math.ceil(len/8);do{var a=new bn(this.rand.generate(min_bytes))}while(a.cmp(n)>=0);return a}
16
16
  ;MillerRabin.prototype._randrange=function _randrange(start,stop){var size=stop.sub(start);return start.add(this._randbelow(size))};MillerRabin.prototype.test=function test(n,k,cb){var len=n.bitLength();var red=bn.mont(n);var rone=new bn(1).toRed(red);if(!k)k=Math.max(1,len/48|0);var n1=n.subn(1);for(var s=0;!n1.testn(s);s++){}var d=n.shrn(s);var rn1=n1.toRed(red);var prime=true;for(;k>0;k--){var a=this._randrange(new bn(2),n1);if(cb)cb(a);var x=a.toRed(red).redPow(d);if(x.cmp(rone)===0||x.cmp(rn1)===0)continue;for(var i=1;i<s;i++){x=x.redSqr();if(x.cmp(rone)===0)return false;if(x.cmp(rn1)===0)break}if(i===s)return false}return prime};MillerRabin.prototype.getDivisor=function getDivisor(n,k){var len=n.bitLength();var red=bn.mont(n);var rone=new bn(1).toRed(red);if(!k)k=Math.max(1,len/48|0);var n1=n.subn(1);for(var s=0;!n1.testn(s);s++){}var d=n.shrn(s);var rn1=n1.toRed(red);for(;k>0;k--){var a=this._randrange(new bn(2),n1);var g=n.gcd(a);if(g.cmpn(1)!==0)return g;var x=a.toRed(red).redPow(d);if(x.cmp(rone)===0||x.cmp(rn1)===0)continue;for(var i=1;i<s;i++){x=x.redSqr();if(x.cmp(rone)===0)return x.fromRed().subn(1).gcd(n);if(x.cmp(rn1)===0)break}if(i===s){x=x.redSqr();return x.fromRed().subn(1).gcd(n)}}return false}},{"bn.js":150,brorand:22}],150:[function(require,module,exports){arguments[4][15][0].apply(exports,arguments)},{buffer:23,dup:15}],151:[function(require,module,exports){module.exports=assert;function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}assert.equal=function assertEqual(l,r,msg){if(l!=r)throw new Error(msg||"Assertion failed: "+l+" != "+r)}},{}],152:[function(require,module,exports){"use strict";var utils=exports;function toArray(msg,enc){if(Array.isArray(msg))return msg.slice();if(!msg)return[];var res=[];if(typeof msg!=="string"){for(var i=0;i<msg.length;i++)res[i]=msg[i]|0;return res}if(enc==="hex"){msg=msg.replace(/[^a-z0-9]+/gi,"");if(msg.length%2!==0)msg="0"+msg;for(var i=0;i<msg.length;i+=2)res.push(parseInt(msg[i]+msg[i+1],16))}else{for(var i=0;i<msg.length;i++){var c=msg.charCodeAt(i);var hi=c>>8;var lo=c&255;if(hi)res.push(hi,lo);else res.push(lo)}}return res}utils.toArray=toArray;function zero2(word){if(word.length===1)return"0"+word;else return word}utils.zero2=zero2;function toHex(msg){var res="";for(var i=0;i<msg.length;i++)res+=zero2(msg[i].toString(16));return res}utils.toHex=toHex;utils.encode=function encode(arr,enc){if(enc==="hex")return toHex(arr);else return arr}},{}],153:[function(require,module,exports){"use strict";var getOwnPropertySymbols=Object.getOwnPropertySymbols;var hasOwnProperty=Object.prototype.hasOwnProperty;var propIsEnumerable=Object.prototype.propertyIsEnumerable;function toObject(val){if(val===null||val===undefined){throw new TypeError("Object.assign cannot be called with null or undefined")}return Object(val)}function shouldUseNative(){try{if(!Object.assign){return false}var test1=new String("abc");test1[5]="de";if(Object.getOwnPropertyNames(test1)[0]==="5"){return false}var test2={};for(var i=0;i<10;i++){test2["_"+String.fromCharCode(i)]=i}var order2=Object.getOwnPropertyNames(test2).map(function(n){return test2[n]});if(order2.join("")!=="0123456789"){return false}var test3={};"abcdefghijklmnopqrst".split("").forEach(function(letter){test3[letter]=letter});if(Object.keys(Object.assign({},test3)).join("")!=="abcdefghijklmnopqrst"){return false}return true}catch(err){return false}}module.exports=shouldUseNative()?Object.assign:function(target,source){var from;var to=toObject(target);var symbols;for(var s=1;s<arguments.length;s++){from=Object(arguments[s]);for(var key in from){if(hasOwnProperty.call(from,key)){to[key]=from[key]}}if(getOwnPropertySymbols){symbols=getOwnPropertySymbols(from);for(var i=0;i<symbols.length;i++){if(propIsEnumerable.call(from,symbols[i])){to[symbols[i]]=from[symbols[i]]}}}}return to}},{}],154:[function(require,module,exports){exports.endianness=function(){return"LE"};exports.hostname=function(){if(typeof location!=="undefined"){return location.hostname}else return""};exports.loadavg=function(){return[]};exports.uptime=function(){return 0};exports.freemem=function(){return Number.MAX_VALUE};exports.totalmem=function(){return Number.MAX_VALUE};exports.cpus=function(){return[]};exports.type=function(){return"Browser"};exports.release=function(){if(typeof navigator!=="undefined"){return navigator.appVersion}return""};exports.networkInterfaces=exports.getNetworkInterfaces=function(){return{}};exports.arch=function(){return"javascript"};exports.platform=function(){return"browser"};exports.tmpdir=exports.tmpDir=function(){return"/tmp"};exports.EOL="\n"},{}],155:[function(require,module,exports){"use strict";var TYPED_OK=typeof Uint8Array!=="undefined"&&typeof Uint16Array!=="undefined"&&typeof Int32Array!=="undefined";exports.assign=function(obj){var sources=Array.prototype.slice.call(arguments,1);while(sources.length){var source=sources.shift();if(!source){continue}if(typeof source!=="object"){throw new TypeError(source+"must be non-object")}for(var p in source){if(source.hasOwnProperty(p)){obj[p]=source[p]}}}return obj};exports.shrinkBuf=function(buf,size){if(buf.length===size){return buf}if(buf.subarray){return buf.subarray(0,size)}buf.length=size;return buf};var fnTyped={arraySet:function(dest,src,src_offs,len,dest_offs){if(src.subarray&&dest.subarray){dest.set(src.subarray(src_offs,src_offs+len),dest_offs);return}for(var i=0;i<len;i++){dest[dest_offs+i]=src[src_offs+i]}},flattenChunks:function(chunks){var i,l,len,pos,chunk,result;len=0;for(i=0,l=chunks.length;i<l;i++){len+=chunks[i].length}result=new Uint8Array(len);pos=0;for(i=0,l=chunks.length;i<l;i++){chunk=chunks[i];result.set(chunk,pos);pos+=chunk.length}return result}};var fnUntyped={arraySet:function(dest,src,src_offs,len,dest_offs){for(var i=0;i<len;i++){dest[dest_offs+i]=src[src_offs+i]}},flattenChunks:function(chunks){return[].concat.apply([],chunks)}};exports.setTyped=function(on){if(on){exports.Buf8=Uint8Array;exports.Buf16=Uint16Array;exports.Buf32=Int32Array;exports.assign(exports,fnTyped)}else{exports.Buf8=Array;exports.Buf16=Array;exports.Buf32=Array;exports.assign(exports,fnUntyped)}};exports.setTyped(TYPED_OK)},{}],156:[function(require,module,exports){"use strict";function adler32(adler,buf,len,pos){var s1=adler&65535|0,s2=adler>>>16&65535|0,n=0;while(len!==0){n=len>2e3?2e3:len;len-=n;do{s1=s1+buf[pos++]|0;s2=s2+s1|0}while(--n);s1%=65521;s2%=65521}return s1|s2<<16|0}module.exports=adler32},{}],157:[function(require,module,exports){"use strict";module.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],158:[function(require,module,exports){"use strict";function makeTable(){var c,table=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++){c=c&1?3988292384^c>>>1:c>>>1}table[n]=c}return table}var crcTable=makeTable();function crc32(crc,buf,len,pos){var t=crcTable,end=pos+len;crc^=-1;for(var i=pos;i<end;i++){crc=crc>>>8^t[(crc^buf[i])&255]}return crc^-1}module.exports=crc32},{}],159:[function(require,module,exports){"use strict";var utils=require("../utils/common");var trees=require("./trees");var adler32=require("./adler32");var crc32=require("./crc32");var msg=require("./messages");var Z_NO_FLUSH=0;var Z_PARTIAL_FLUSH=1;var Z_FULL_FLUSH=3;var Z_FINISH=4;var Z_BLOCK=5;var Z_OK=0;var Z_STREAM_END=1;var Z_STREAM_ERROR=-2;var Z_DATA_ERROR=-3;var Z_BUF_ERROR=-5;var Z_DEFAULT_COMPRESSION=-1;var Z_FILTERED=1;var Z_HUFFMAN_ONLY=2;var Z_RLE=3;var Z_FIXED=4;var Z_DEFAULT_STRATEGY=0;var Z_UNKNOWN=2;var Z_DEFLATED=8;var MAX_MEM_LEVEL=9;var MAX_WBITS=15;var DEF_MEM_LEVEL=8;var LENGTH_CODES=29;var LITERALS=256;var L_CODES=LITERALS+1+LENGTH_CODES;var D_CODES=30;var BL_CODES=19;var HEAP_SIZE=2*L_CODES+1;var MAX_BITS=15;var MIN_MATCH=3;var MAX_MATCH=258;var MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1;var PRESET_DICT=32;var INIT_STATE=42;var EXTRA_STATE=69;var NAME_STATE=73;var COMMENT_STATE=91;var HCRC_STATE=103;var BUSY_STATE=113;var FINISH_STATE=666;var BS_NEED_MORE=1;var BS_BLOCK_DONE=2;var BS_FINISH_STARTED=3;var BS_FINISH_DONE=4;var OS_CODE=3;function err(strm,errorCode){strm.msg=msg[errorCode];return errorCode}function rank(f){return(f<<1)-(f>4?9:0)}function zero(buf){var len=buf.length;while(--len>=0){buf[len]=0}}function flush_pending(strm){var s=strm.state;var len=s.pending;if(len>strm.avail_out){len=strm.avail_out}if(len===0){return}utils.arraySet(strm.output,s.pending_buf,s.pending_out,len,strm.next_out);strm.next_out+=len;s.pending_out+=len;strm.total_out+=len;strm.avail_out-=len;s.pending-=len;if(s.pending===0){s.pending_out=0}}function flush_block_only(s,last){trees._tr_flush_block(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,last);s.block_start=s.strstart;flush_pending(s.strm)}function put_byte(s,b){s.pending_buf[s.pending++]=b}function putShortMSB(s,b){s.pending_buf[s.pending++]=b>>>8&255;s.pending_buf[s.pending++]=b&255}function read_buf(strm,buf,start,size){var len=strm.avail_in;if(len>size){len=size}if(len===0){return 0}strm.avail_in-=len;utils.arraySet(buf,strm.input,strm.next_in,len,start);if(strm.state.wrap===1){strm.adler=adler32(strm.adler,buf,len,start)}else if(strm.state.wrap===2){strm.adler=crc32(strm.adler,buf,len,start)}strm.next_in+=len;strm.total_in+=len;return len}function longest_match(s,cur_match){var chain_length=s.max_chain_length;var scan=s.strstart;var match;var len;var best_len=s.prev_length;var nice_match=s.nice_match;var limit=s.strstart>s.w_size-MIN_LOOKAHEAD?s.strstart-(s.w_size-MIN_LOOKAHEAD):0;var _win=s.window;var wmask=s.w_mask;var prev=s.prev;var strend=s.strstart+MAX_MATCH;var scan_end1=_win[scan+best_len-1];var scan_end=_win[scan+best_len];if(s.prev_length>=s.good_match){chain_length>>=2}if(nice_match>s.lookahead){nice_match=s.lookahead}do{match=cur_match;if(_win[match+best_len]!==scan_end||_win[match+best_len-1]!==scan_end1||_win[match]!==_win[scan]||_win[++match]!==_win[scan+1]){continue}scan+=2;match++;do{}while(_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&scan<strend);len=MAX_MATCH-(strend-scan);scan=strend-MAX_MATCH;if(len>best_len){s.match_start=cur_match;best_len=len;if(len>=nice_match){break}scan_end1=_win[scan+best_len-1];scan_end=_win[scan+best_len]}}while((cur_match=prev[cur_match&wmask])>limit&&--chain_length!==0);if(best_len<=s.lookahead){return best_len}return s.lookahead}function fill_window(s){var _w_size=s.w_size;var p,n,m,more,str;do{more=s.window_size-s.lookahead-s.strstart;if(s.strstart>=_w_size+(_w_size-MIN_LOOKAHEAD)){utils.arraySet(s.window,s.window,_w_size,_w_size,0);s.match_start-=_w_size;s.strstart-=_w_size;s.block_start-=_w_size;n=s.hash_size;p=n;do{m=s.head[--p];s.head[p]=m>=_w_size?m-_w_size:0}while(--n);n=_w_size;p=n;do{m=s.prev[--p];s.prev[p]=m>=_w_size?m-_w_size:0}while(--n);more+=_w_size}if(s.strm.avail_in===0){break}n=read_buf(s.strm,s.window,s.strstart+s.lookahead,more);s.lookahead+=n;if(s.lookahead+s.insert>=MIN_MATCH){str=s.strstart-s.insert;s.ins_h=s.window[str];s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+1])&s.hash_mask;while(s.insert){s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+MIN_MATCH-1])&s.hash_mask;s.prev[str&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=str;str++;s.insert--;if(s.lookahead+s.insert<MIN_MATCH){break}}}}while(s.lookahead<MIN_LOOKAHEAD&&s.strm.avail_in!==0)}function deflate_stored(s,flush){var max_block_size=65535;if(max_block_size>s.pending_buf_size-5){max_block_size=s.pending_buf_size-5}for(;;){if(s.lookahead<=1){fill_window(s);if(s.lookahead===0&&flush===Z_NO_FLUSH){return BS_NEED_MORE}if(s.lookahead===0){break}}s.strstart+=s.lookahead;s.lookahead=0;var max_start=s.block_start+max_block_size;if(s.strstart===0||s.strstart>=max_start){s.lookahead=s.strstart-max_start;s.strstart=max_start;flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}if(s.strstart-s.block_start>=s.w_size-MIN_LOOKAHEAD){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}s.insert=0;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.strstart>s.block_start){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_NEED_MORE}function deflate_fast(s,flush){var hash_head;var bflush;for(;;){if(s.lookahead<MIN_LOOKAHEAD){fill_window(s);if(s.lookahead<MIN_LOOKAHEAD&&flush===Z_NO_FLUSH){return BS_NEED_MORE}if(s.lookahead===0){break}}hash_head=0;if(s.lookahead>=MIN_MATCH){s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+MIN_MATCH-1])&s.hash_mask;hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart}if(hash_head!==0&&s.strstart-hash_head<=s.w_size-MIN_LOOKAHEAD){s.match_length=longest_match(s,hash_head)}if(s.match_length>=MIN_MATCH){bflush=trees._tr_tally(s,s.strstart-s.match_start,s.match_length-MIN_MATCH);s.lookahead-=s.match_length;if(s.match_length<=s.max_lazy_match&&s.lookahead>=MIN_MATCH){s.match_length--;do{s.strstart++;s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+MIN_MATCH-1])&s.hash_mask;hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart}while(--s.match_length!==0);s.strstart++}else{s.strstart+=s.match_length;s.match_length=0;s.ins_h=s.window[s.strstart];s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+1])&s.hash_mask}}else{bflush=trees._tr_tally(s,0,s.window[s.strstart]);s.lookahead--;s.strstart++}if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}s.insert=s.strstart<MIN_MATCH-1?s.strstart:MIN_MATCH-1;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE}function deflate_slow(s,flush){var hash_head;var bflush;var max_insert;for(;;){if(s.lookahead<MIN_LOOKAHEAD){fill_window(s);if(s.lookahead<MIN_LOOKAHEAD&&flush===Z_NO_FLUSH){return BS_NEED_MORE}if(s.lookahead===0){break}}hash_head=0;if(s.lookahead>=MIN_MATCH){s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+MIN_MATCH-1])&s.hash_mask;hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart}s.prev_length=s.match_length;s.prev_match=s.match_start;s.match_length=MIN_MATCH-1;if(hash_head!==0&&s.prev_length<s.max_lazy_match&&s.strstart-hash_head<=s.w_size-MIN_LOOKAHEAD){s.match_length=longest_match(s,hash_head);if(s.match_length<=5&&(s.strategy===Z_FILTERED||s.match_length===MIN_MATCH&&s.strstart-s.match_start>4096)){s.match_length=MIN_MATCH-1}}if(s.prev_length>=MIN_MATCH&&s.match_length<=s.prev_length){max_insert=s.strstart+s.lookahead-MIN_MATCH;bflush=trees._tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-MIN_MATCH);s.lookahead-=s.prev_length-1;s.prev_length-=2;do{if(++s.strstart<=max_insert){s.ins_h=(s.ins_h<<s.hash_shift^s.window[s.strstart+MIN_MATCH-1])&s.hash_mask;hash_head=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=s.strstart}}while(--s.prev_length!==0);s.match_available=0;s.match_length=MIN_MATCH-1;s.strstart++;if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}else if(s.match_available){bflush=trees._tr_tally(s,0,s.window[s.strstart-1]);if(bflush){flush_block_only(s,false)}s.strstart++;s.lookahead--;if(s.strm.avail_out===0){return BS_NEED_MORE}}else{s.match_available=1;s.strstart++;s.lookahead--}}if(s.match_available){bflush=trees._tr_tally(s,0,s.window[s.strstart-1]);s.match_available=0}s.insert=s.strstart<MIN_MATCH-1?s.strstart:MIN_MATCH-1;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE}function deflate_rle(s,flush){var bflush;var prev;var scan,strend;var _win=s.window;for(;;){if(s.lookahead<=MAX_MATCH){fill_window(s);if(s.lookahead<=MAX_MATCH&&flush===Z_NO_FLUSH){return BS_NEED_MORE}if(s.lookahead===0){break}}s.match_length=0;if(s.lookahead>=MIN_MATCH&&s.strstart>0){scan=s.strstart-1;prev=_win[scan];if(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]){strend=s.strstart+MAX_MATCH;do{}while(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&scan<strend);s.match_length=MAX_MATCH-(strend-scan);if(s.match_length>s.lookahead){s.match_length=s.lookahead}}}if(s.match_length>=MIN_MATCH){bflush=trees._tr_tally(s,1,s.match_length-MIN_MATCH);s.lookahead-=s.match_length;s.strstart+=s.match_length;s.match_length=0}else{bflush=trees._tr_tally(s,0,s.window[s.strstart]);s.lookahead--;s.strstart++}if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}s.insert=0;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE}function deflate_huff(s,flush){var bflush;for(;;){if(s.lookahead===0){fill_window(s);if(s.lookahead===0){if(flush===Z_NO_FLUSH){return BS_NEED_MORE}break}}s.match_length=0;bflush=trees._tr_tally(s,0,s.window[s.strstart]);s.lookahead--;s.strstart++;if(bflush){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}}s.insert=0;if(flush===Z_FINISH){flush_block_only(s,true);if(s.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s.last_lit){flush_block_only(s,false);if(s.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE}function Config(good_length,max_lazy,nice_length,max_chain,func){this.good_length=good_length;this.max_lazy=max_lazy;this.nice_length=nice_length;this.max_chain=max_chain;this.func=func}var configuration_table;configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)];function lm_init(s){s.window_size=2*s.w_size;zero(s.head);s.max_lazy_match=configuration_table[s.level].max_lazy;s.good_match=configuration_table[s.level].good_length;s.nice_match=configuration_table[s.level].nice_length;s.max_chain_length=configuration_table[s.level].max_chain;s.strstart=0;s.block_start=0;s.lookahead=0;s.insert=0;s.match_length=s.prev_length=MIN_MATCH-1;s.match_available=0;s.ins_h=0}function DeflateState(){this.strm=null;this.status=0;this.pending_buf=null;this.pending_buf_size=0;this.pending_out=0;this.pending=0;this.wrap=0;this.gzhead=null;this.gzindex=0;this.method=Z_DEFLATED;this.last_flush=-1;this.w_size=0;this.w_bits=0;this.w_mask=0;this.window=null;this.window_size=0;this.prev=null;this.head=null;this.ins_h=0;this.hash_size=0;this.hash_bits=0;this.hash_mask=0;this.hash_shift=0;this.block_start=0;this.match_length=0;this.prev_match=0;this.match_available=0;this.strstart=0;this.match_start=0;this.lookahead=0;this.prev_length=0;this.max_chain_length=0;this.max_lazy_match=0;this.level=0;this.strategy=0;this.good_match=0;this.nice_match=0;this.dyn_ltree=new utils.Buf16(HEAP_SIZE*2);this.dyn_dtree=new utils.Buf16((2*D_CODES+1)*2);this.bl_tree=new utils.Buf16((2*BL_CODES+1)*2);zero(this.dyn_ltree);zero(this.dyn_dtree);zero(this.bl_tree);this.l_desc=null;this.d_desc=null;this.bl_desc=null;this.bl_count=new utils.Buf16(MAX_BITS+1);this.heap=new utils.Buf16(2*L_CODES+1);zero(this.heap);this.heap_len=0;this.heap_max=0;this.depth=new utils.Buf16(2*L_CODES+1);zero(this.depth);this.l_buf=0;this.lit_bufsize=0;this.last_lit=0;this.d_buf=0;this.opt_len=0;this.static_len=0;this.matches=0;this.insert=0;this.bi_buf=0;this.bi_valid=0}function deflateResetKeep(strm){var s;if(!strm||!strm.state){return err(strm,Z_STREAM_ERROR)}strm.total_in=strm.total_out=0;strm.data_type=Z_UNKNOWN;s=strm.state;s.pending=0;s.pending_out=0;if(s.wrap<0){s.wrap=-s.wrap}s.status=s.wrap?INIT_STATE:BUSY_STATE;strm.adler=s.wrap===2?0:1;s.last_flush=Z_NO_FLUSH;trees._tr_init(s);return Z_OK}function deflateReset(strm){var ret=deflateResetKeep(strm);if(ret===Z_OK){lm_init(strm.state)}return ret}function deflateSetHeader(strm,head){if(!strm||!strm.state){return Z_STREAM_ERROR}if(strm.state.wrap!==2){return Z_STREAM_ERROR}strm.state.gzhead=head;return Z_OK}function deflateInit2(strm,level,method,windowBits,memLevel,strategy){if(!strm){return Z_STREAM_ERROR}var wrap=1;if(level===Z_DEFAULT_COMPRESSION){level=6}if(windowBits<0){wrap=0;windowBits=-windowBits}else if(windowBits>15){wrap=2;windowBits-=16}if(memLevel<1||memLevel>MAX_MEM_LEVEL||method!==Z_DEFLATED||windowBits<8||windowBits>15||level<0||level>9||strategy<0||strategy>Z_FIXED){return err(strm,Z_STREAM_ERROR)}if(windowBits===8){windowBits=9}var s=new DeflateState;strm.state=s;s.strm=strm;s.wrap=wrap;s.gzhead=null;s.w_bits=windowBits;s.w_size=1<<s.w_bits;s.w_mask=s.w_size-1;s.hash_bits=memLevel+7;s.hash_size=1<<s.hash_bits;s.hash_mask=s.hash_size-1;s.hash_shift=~~((s.hash_bits+MIN_MATCH-1)/MIN_MATCH);s.window=new utils.Buf8(s.w_size*2);s.head=new utils.Buf16(s.hash_size);s.prev=new utils.Buf16(s.w_size);s.lit_bufsize=1<<memLevel+6;s.pending_buf_size=s.lit_bufsize*4;s.pending_buf=new utils.Buf8(s.pending_buf_size);s.d_buf=1*s.lit_bufsize;s.l_buf=(1+2)*s.lit_bufsize;s.level=level;s.strategy=strategy;s.method=method;return deflateReset(strm)}function deflateInit(strm,level){return deflateInit2(strm,level,Z_DEFLATED,MAX_WBITS,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY)}function deflate(strm,flush){var old_flush,s;var beg,val;if(!strm||!strm.state||flush>Z_BLOCK||flush<0){return strm?err(strm,Z_STREAM_ERROR):Z_STREAM_ERROR}s=strm.state;if(!strm.output||!strm.input&&strm.avail_in!==0||s.status===FINISH_STATE&&flush!==Z_FINISH){return err(strm,strm.avail_out===0?Z_BUF_ERROR:Z_STREAM_ERROR)}s.strm=strm;old_flush=s.last_flush;s.last_flush=flush;if(s.status===INIT_STATE){if(s.wrap===2){strm.adler=0;put_byte(s,31);put_byte(s,139);put_byte(s,8);if(!s.gzhead){put_byte(s,0);put_byte(s,0);put_byte(s,0);put_byte(s,0);put_byte(s,0);put_byte(s,s.level===9?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2?4:0);put_byte(s,OS_CODE);s.status=BUSY_STATE}else{put_byte(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(!s.gzhead.extra?0:4)+(!s.gzhead.name?0:8)+(!s.gzhead.comment?0:16));put_byte(s,s.gzhead.time&255);put_byte(s,s.gzhead.time>>8&255);put_byte(s,s.gzhead.time>>16&255);put_byte(s,s.gzhead.time>>24&255);put_byte(s,s.level===9?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2?4:0);put_byte(s,s.gzhead.os&255);if(s.gzhead.extra&&s.gzhead.extra.length){put_byte(s,s.gzhead.extra.length&255);put_byte(s,s.gzhead.extra.length>>8&255)}if(s.gzhead.hcrc){strm.adler=crc32(strm.adler,s.pending_buf,s.pending,0)}s.gzindex=0;s.status=EXTRA_STATE}}else{var header=Z_DEFLATED+(s.w_bits-8<<4)<<8;var level_flags=-1;if(s.strategy>=Z_HUFFMAN_ONLY||s.level<2){level_flags=0}else if(s.level<6){level_flags=1}else if(s.level===6){level_flags=2}else{level_flags=3}header|=level_flags<<6;if(s.strstart!==0){header|=PRESET_DICT}header+=31-header%31;s.status=BUSY_STATE;putShortMSB(s,header);if(s.strstart!==0){putShortMSB(s,strm.adler>>>16);putShortMSB(s,strm.adler&65535)}strm.adler=1}}if(s.status===EXTRA_STATE){if(s.gzhead.extra){beg=s.pending;while(s.gzindex<(s.gzhead.extra.length&65535)){if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}flush_pending(strm);beg=s.pending;if(s.pending===s.pending_buf_size){break}}put_byte(s,s.gzhead.extra[s.gzindex]&255);s.gzindex++}if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}if(s.gzindex===s.gzhead.extra.length){s.gzindex=0;s.status=NAME_STATE}}else{s.status=NAME_STATE}}if(s.status===NAME_STATE){if(s.gzhead.name){beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}flush_pending(strm);beg=s.pending;if(s.pending===s.pending_buf_size){val=1;break}}if(s.gzindex<s.gzhead.name.length){val=s.gzhead.name.charCodeAt(s.gzindex++)&255}else{val=0}put_byte(s,val)}while(val!==0);if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}if(val===0){s.gzindex=0;s.status=COMMENT_STATE}}else{s.status=COMMENT_STATE}}if(s.status===COMMENT_STATE){if(s.gzhead.comment){beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}flush_pending(strm);beg=s.pending;if(s.pending===s.pending_buf_size){val=1;break}}if(s.gzindex<s.gzhead.comment.length){val=s.gzhead.comment.charCodeAt(s.gzindex++)&255}else{val=0}put_byte(s,val)}while(val!==0);if(s.gzhead.hcrc&&s.pending>beg){strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg)}if(val===0){s.status=HCRC_STATE}}else{s.status=HCRC_STATE}}if(s.status===HCRC_STATE){if(s.gzhead.hcrc){if(s.pending+2>s.pending_buf_size){flush_pending(strm)}if(s.pending+2<=s.pending_buf_size){put_byte(s,strm.adler&255);put_byte(s,strm.adler>>8&255);strm.adler=0;s.status=BUSY_STATE}}else{s.status=BUSY_STATE}}if(s.pending!==0){flush_pending(strm);if(strm.avail_out===0){s.last_flush=-1;return Z_OK}}else if(strm.avail_in===0&&rank(flush)<=rank(old_flush)&&flush!==Z_FINISH){return err(strm,Z_BUF_ERROR)}if(s.status===FINISH_STATE&&strm.avail_in!==0){return err(strm,Z_BUF_ERROR)}if(strm.avail_in!==0||s.lookahead!==0||flush!==Z_NO_FLUSH&&s.status!==FINISH_STATE){var bstate=s.strategy===Z_HUFFMAN_ONLY?deflate_huff(s,flush):s.strategy===Z_RLE?deflate_rle(s,flush):configuration_table[s.level].func(s,flush);if(bstate===BS_FINISH_STARTED||bstate===BS_FINISH_DONE){s.status=FINISH_STATE}if(bstate===BS_NEED_MORE||bstate===BS_FINISH_STARTED){if(strm.avail_out===0){s.last_flush=-1}return Z_OK}if(bstate===BS_BLOCK_DONE){if(flush===Z_PARTIAL_FLUSH){trees._tr_align(s)}else if(flush!==Z_BLOCK){trees._tr_stored_block(s,0,0,false);if(flush===Z_FULL_FLUSH){zero(s.head);if(s.lookahead===0){s.strstart=0;s.block_start=0;s.insert=0}}}flush_pending(strm);if(strm.avail_out===0){s.last_flush=-1;return Z_OK}}}if(flush!==Z_FINISH){return Z_OK}if(s.wrap<=0){return Z_STREAM_END}if(s.wrap===2){put_byte(s,strm.adler&255);put_byte(s,strm.adler>>8&255);put_byte(s,strm.adler>>16&255);put_byte(s,strm.adler>>24&255);put_byte(s,strm.total_in&255);put_byte(s,strm.total_in>>8&255);put_byte(s,strm.total_in>>16&255);put_byte(s,strm.total_in>>24&255)}else{putShortMSB(s,strm.adler>>>16);putShortMSB(s,strm.adler&65535)}flush_pending(strm);if(s.wrap>0){s.wrap=-s.wrap}return s.pending!==0?Z_OK:Z_STREAM_END}function deflateEnd(strm){var status;if(!strm||!strm.state){return Z_STREAM_ERROR}status=strm.state.status;if(status!==INIT_STATE&&status!==EXTRA_STATE&&status!==NAME_STATE&&status!==COMMENT_STATE&&status!==HCRC_STATE&&status!==BUSY_STATE&&status!==FINISH_STATE){return err(strm,Z_STREAM_ERROR)}strm.state=null;return status===BUSY_STATE?err(strm,Z_DATA_ERROR):Z_OK}function deflateSetDictionary(strm,dictionary){var dictLength=dictionary.length;var s;var str,n;var wrap;var avail;var next;var input;var tmpDict;if(!strm||!strm.state){return Z_STREAM_ERROR}s=strm.state;wrap=s.wrap;if(wrap===2||wrap===1&&s.status!==INIT_STATE||s.lookahead){return Z_STREAM_ERROR}if(wrap===1){strm.adler=adler32(strm.adler,dictionary,dictLength,0)}s.wrap=0;if(dictLength>=s.w_size){if(wrap===0){zero(s.head);s.strstart=0;s.block_start=0;s.insert=0}tmpDict=new utils.Buf8(s.w_size);utils.arraySet(tmpDict,dictionary,dictLength-s.w_size,s.w_size,0);dictionary=tmpDict;dictLength=s.w_size}avail=strm.avail_in;next=strm.next_in;input=strm.input;strm.avail_in=dictLength;strm.next_in=0;strm.input=dictionary;fill_window(s);while(s.lookahead>=MIN_MATCH){str=s.strstart;n=s.lookahead-(MIN_MATCH-1);do{s.ins_h=(s.ins_h<<s.hash_shift^s.window[str+MIN_MATCH-1])&s.hash_mask;s.prev[str&s.w_mask]=s.head[s.ins_h];s.head[s.ins_h]=str;str++}while(--n);s.strstart=str;s.lookahead=MIN_MATCH-1;fill_window(s)}s.strstart+=s.lookahead;s.block_start=s.strstart;s.insert=s.lookahead;s.lookahead=0;s.match_length=s.prev_length=MIN_MATCH-1;s.match_available=0;strm.next_in=next;strm.input=input;strm.avail_in=avail;s.wrap=wrap;return Z_OK}exports.deflateInit=deflateInit;exports.deflateInit2=deflateInit2;exports.deflateReset=deflateReset;exports.deflateResetKeep=deflateResetKeep;exports.deflateSetHeader=deflateSetHeader;exports.deflate=deflate;exports.deflateEnd=deflateEnd;exports.deflateSetDictionary=deflateSetDictionary;exports.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":155,"./adler32":156,"./crc32":158,"./messages":163,"./trees":164}],160:[function(require,module,exports){"use strict";var BAD=30;var TYPE=12;module.exports=function inflate_fast(strm,start){var state;var _in;var last;var _out;var beg;var end;var dmax;var wsize;var whave;var wnext;var s_window;var hold;var bits;var lcode;var dcode;var lmask;var dmask;var here;var op;var len;var dist;var from;var from_source;var input,output;state=strm.state;_in=strm.next_in;input=strm.input;last=_in+(strm.avail_in-5);_out=strm.next_out;output=strm.output;beg=_out-(start-strm.avail_out);end=_out+(strm.avail_out-257);dmax=state.dmax;wsize=state.wsize;whave=state.whave;wnext=state.wnext;s_window=state.window;hold=state.hold;bits=state.bits;lcode=state.lencode;dcode=state.distcode;lmask=(1<<state.lenbits)-1;dmask=(1<<state.distbits)-1;top:do{if(bits<15){hold+=input[_in++]<<bits;bits+=8;hold+=input[_in++]<<bits;bits+=8}here=lcode[hold&lmask];dolen:for(;;){op=here>>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op===0){output[_out++]=here&65535}else if(op&16){len=here&65535;op&=15;if(op){if(bits<op){hold+=input[_in++]<<bits;bits+=8}len+=hold&(1<<op)-1;hold>>>=op;bits-=op}if(bits<15){hold+=input[_in++]<<bits;bits+=8;hold+=input[_in++]<<bits;bits+=8}here=dcode[hold&dmask];dodist:for(;;){op=here>>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op&16){dist=here&65535;op&=15;if(bits<op){hold+=input[_in++]<<bits;bits+=8;if(bits<op){hold+=input[_in++]<<bits;bits+=8}}dist+=hold&(1<<op)-1;if(dist>dmax){strm.msg="invalid distance too far back";state.mode=BAD;break top}hold>>>=op;bits-=op;op=_out-beg;if(dist>op){op=dist-op;if(op>whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break top}}from=0;from_source=s_window;if(wnext===0){from+=wsize-op;if(op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist;from_source=output}}else if(wnext<op){from+=wsize+wnext-op;op-=wnext;if(op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);from=0;if(wnext<len){op=wnext;len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist;from_source=output}}}else{from+=wnext-op;if(op<len){len-=op;do{output[_out++]=s_window[from++]}while(--op);from=_out-dist;from_source=output}}while(len>2){output[_out++]=from_source[from++];output[_out++]=from_source[from++];output[_out++]=from_source[from++];len-=3}if(len){output[_out++]=from_source[from++];if(len>1){output[_out++]=from_source[from++]}}}else{from=_out-dist;do{output[_out++]=output[from++];output[_out++]=output[from++];output[_out++]=output[from++];len-=3}while(len>2);if(len){output[_out++]=output[from++];if(len>1){output[_out++]=output[from++]}}}}else if((op&64)===0){here=dcode[(here&65535)+(hold&(1<<op)-1)];continue dodist}else{strm.msg="invalid distance code";state.mode=BAD;break top}break}}else if((op&64)===0){here=lcode[(here&65535)+(hold&(1<<op)-1)];continue dolen}else if(op&32){state.mode=TYPE
17
17
  ;break top}else{strm.msg="invalid literal/length code";state.mode=BAD;break top}break}}while(_in<last&&_out<end);len=bits>>3;_in-=len;bits-=len<<3;hold&=(1<<bits)-1;strm.next_in=_in;strm.next_out=_out;strm.avail_in=_in<last?5+(last-_in):5-(_in-last);strm.avail_out=_out<end?257+(end-_out):257-(_out-end);state.hold=hold;state.bits=bits;return}},{}],161:[function(require,module,exports){"use strict";var utils=require("../utils/common");var adler32=require("./adler32");var crc32=require("./crc32");var inflate_fast=require("./inffast");var inflate_table=require("./inftrees");var CODES=0;var LENS=1;var DISTS=2;var Z_FINISH=4;var Z_BLOCK=5;var Z_TREES=6;var Z_OK=0;var Z_STREAM_END=1;var Z_NEED_DICT=2;var Z_STREAM_ERROR=-2;var Z_DATA_ERROR=-3;var Z_MEM_ERROR=-4;var Z_BUF_ERROR=-5;var Z_DEFLATED=8;var HEAD=1;var FLAGS=2;var TIME=3;var OS=4;var EXLEN=5;var EXTRA=6;var NAME=7;var COMMENT=8;var HCRC=9;var DICTID=10;var DICT=11;var TYPE=12;var TYPEDO=13;var STORED=14;var COPY_=15;var COPY=16;var TABLE=17;var LENLENS=18;var CODELENS=19;var LEN_=20;var LEN=21;var LENEXT=22;var DIST=23;var DISTEXT=24;var MATCH=25;var LIT=26;var CHECK=27;var LENGTH=28;var DONE=29;var BAD=30;var MEM=31;var SYNC=32;var ENOUGH_LENS=852;var ENOUGH_DISTS=592;var MAX_WBITS=15;var DEF_WBITS=MAX_WBITS;function zswap32(q){return(q>>>24&255)+(q>>>8&65280)+((q&65280)<<8)+((q&255)<<24)}function InflateState(){this.mode=0;this.last=false;this.wrap=0;this.havedict=false;this.flags=0;this.dmax=0;this.check=0;this.total=0;this.head=null;this.wbits=0;this.wsize=0;this.whave=0;this.wnext=0;this.window=null;this.hold=0;this.bits=0;this.length=0;this.offset=0;this.extra=0;this.lencode=null;this.distcode=null;this.lenbits=0;this.distbits=0;this.ncode=0;this.nlen=0;this.ndist=0;this.have=0;this.next=null;this.lens=new utils.Buf16(320);this.work=new utils.Buf16(288);this.lendyn=null;this.distdyn=null;this.sane=0;this.back=0;this.was=0}function inflateResetKeep(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;strm.total_in=strm.total_out=state.total=0;strm.msg="";if(state.wrap){strm.adler=state.wrap&1}state.mode=HEAD;state.last=0;state.havedict=0;state.dmax=32768;state.head=null;state.hold=0;state.bits=0;state.lencode=state.lendyn=new utils.Buf32(ENOUGH_LENS);state.distcode=state.distdyn=new utils.Buf32(ENOUGH_DISTS);state.sane=1;state.back=-1;return Z_OK}function inflateReset(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;state.wsize=0;state.whave=0;state.wnext=0;return inflateResetKeep(strm)}function inflateReset2(strm,windowBits){var wrap;var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;if(windowBits<0){wrap=0;windowBits=-windowBits}else{wrap=(windowBits>>4)+1;if(windowBits<48){windowBits&=15}}if(windowBits&&(windowBits<8||windowBits>15)){return Z_STREAM_ERROR}if(state.window!==null&&state.wbits!==windowBits){state.window=null}state.wrap=wrap;state.wbits=windowBits;return inflateReset(strm)}function inflateInit2(strm,windowBits){var ret;var state;if(!strm){return Z_STREAM_ERROR}state=new InflateState;strm.state=state;state.window=null;ret=inflateReset2(strm,windowBits);if(ret!==Z_OK){strm.state=null}return ret}function inflateInit(strm){return inflateInit2(strm,DEF_WBITS)}var virgin=true;var lenfix,distfix;function fixedtables(state){if(virgin){var sym;lenfix=new utils.Buf32(512);distfix=new utils.Buf32(32);sym=0;while(sym<144){state.lens[sym++]=8}while(sym<256){state.lens[sym++]=9}while(sym<280){state.lens[sym++]=7}while(sym<288){state.lens[sym++]=8}inflate_table(LENS,state.lens,0,288,lenfix,0,state.work,{bits:9});sym=0;while(sym<32){state.lens[sym++]=5}inflate_table(DISTS,state.lens,0,32,distfix,0,state.work,{bits:5});virgin=false}state.lencode=lenfix;state.lenbits=9;state.distcode=distfix;state.distbits=5}function updatewindow(strm,src,end,copy){var dist;var state=strm.state;if(state.window===null){state.wsize=1<<state.wbits;state.wnext=0;state.whave=0;state.window=new utils.Buf8(state.wsize)}if(copy>=state.wsize){utils.arraySet(state.window,src,end-state.wsize,state.wsize,0);state.wnext=0;state.whave=state.wsize}else{dist=state.wsize-state.wnext;if(dist>copy){dist=copy}utils.arraySet(state.window,src,end-copy,dist,state.wnext);copy-=dist;if(copy){utils.arraySet(state.window,src,end-copy,copy,0);state.wnext=copy;state.whave=state.wsize}else{state.wnext+=dist;if(state.wnext===state.wsize){state.wnext=0}if(state.whave<state.wsize){state.whave+=dist}}}return 0}function inflate(strm,flush){var state;var input,output;var next;var put;var have,left;var hold;var bits;var _in,_out;var copy;var from;var from_source;var here=0;var here_bits,here_op,here_val;var last_bits,last_op,last_val;var len;var ret;var hbuf=new utils.Buf8(4);var opts;var n;var order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!strm||!strm.state||!strm.output||!strm.input&&strm.avail_in!==0){return Z_STREAM_ERROR}state=strm.state;if(state.mode===TYPE){state.mode=TYPEDO}put=strm.next_out;output=strm.output;left=strm.avail_out;next=strm.next_in;input=strm.input;have=strm.avail_in;hold=state.hold;bits=state.bits;_in=have;_out=left;ret=Z_OK;inf_leave:for(;;){switch(state.mode){case HEAD:if(state.wrap===0){state.mode=TYPEDO;break}while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(state.wrap&2&&hold===35615){state.check=0;hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0);hold=0;bits=0;state.mode=FLAGS;break}state.flags=0;if(state.head){state.head.done=false}if(!(state.wrap&1)||(((hold&255)<<8)+(hold>>8))%31){strm.msg="incorrect header check";state.mode=BAD;break}if((hold&15)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break}hold>>>=4;bits-=4;len=(hold&15)+8;if(state.wbits===0){state.wbits=len}else if(len>state.wbits){strm.msg="invalid window size";state.mode=BAD;break}state.dmax=1<<len;strm.adler=state.check=1;state.mode=hold&512?DICTID:TYPE;hold=0;bits=0;break;case FLAGS:while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.flags=hold;if((state.flags&255)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break}if(state.flags&57344){strm.msg="unknown header flags set";state.mode=BAD;break}if(state.head){state.head.text=hold>>8&1}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=TIME;case TIME:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(state.head){state.head.time=hold}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;hbuf[2]=hold>>>16&255;hbuf[3]=hold>>>24&255;state.check=crc32(state.check,hbuf,4,0)}hold=0;bits=0;state.mode=OS;case OS:while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(state.head){state.head.xflags=hold&255;state.head.os=hold>>8}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=EXLEN;case EXLEN:if(state.flags&1024){while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.length=hold;if(state.head){state.head.extra_len=hold}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0}else if(state.head){state.head.extra=null}state.mode=EXTRA;case EXTRA:if(state.flags&1024){copy=state.length;if(copy>have){copy=have}if(copy){if(state.head){len=state.head.extra_len-state.length;if(!state.head.extra){state.head.extra=new Array(state.head.extra_len)}utils.arraySet(state.head.extra,input,next,copy,len)}if(state.flags&512){state.check=crc32(state.check,input,copy,next)}have-=copy;next+=copy;state.length-=copy}if(state.length){break inf_leave}}state.length=0;state.mode=NAME;case NAME:if(state.flags&2048){if(have===0){break inf_leave}copy=0;do{len=input[next+copy++];if(state.head&&len&&state.length<65536){state.head.name+=String.fromCharCode(len)}}while(len&&copy<have);if(state.flags&512){state.check=crc32(state.check,input,copy,next)}have-=copy;next+=copy;if(len){break inf_leave}}else if(state.head){state.head.name=null}state.length=0;state.mode=COMMENT;case COMMENT:if(state.flags&4096){if(have===0){break inf_leave}copy=0;do{len=input[next+copy++];if(state.head&&len&&state.length<65536){state.head.comment+=String.fromCharCode(len)}}while(len&&copy<have);if(state.flags&512){state.check=crc32(state.check,input,copy,next)}have-=copy;next+=copy;if(len){break inf_leave}}else if(state.head){state.head.comment=null}state.mode=HCRC;case HCRC:if(state.flags&512){while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(hold!==(state.check&65535)){strm.msg="header crc mismatch";state.mode=BAD;break}hold=0;bits=0}if(state.head){state.head.hcrc=state.flags>>9&1;state.head.done=true}strm.adler=state.check=0;state.mode=TYPE;break;case DICTID:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}strm.adler=state.check=zswap32(hold);hold=0;bits=0;state.mode=DICT;case DICT:if(state.havedict===0){strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;return Z_NEED_DICT}strm.adler=state.check=1;state.mode=TYPE;case TYPE:if(flush===Z_BLOCK||flush===Z_TREES){break inf_leave}case TYPEDO:if(state.last){hold>>>=bits&7;bits-=bits&7;state.mode=CHECK;break}while(bits<3){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.last=hold&1;hold>>>=1;bits-=1;switch(hold&3){case 0:state.mode=STORED;break;case 1:fixedtables(state);state.mode=LEN_;if(flush===Z_TREES){hold>>>=2;bits-=2;break inf_leave}break;case 2:state.mode=TABLE;break;case 3:strm.msg="invalid block type";state.mode=BAD}hold>>>=2;bits-=2;break;case STORED:hold>>>=bits&7;bits-=bits&7;while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if((hold&65535)!==(hold>>>16^65535)){strm.msg="invalid stored block lengths";state.mode=BAD;break}state.length=hold&65535;hold=0;bits=0;state.mode=COPY_;if(flush===Z_TREES){break inf_leave}case COPY_:state.mode=COPY;case COPY:copy=state.length;if(copy){if(copy>have){copy=have}if(copy>left){copy=left}if(copy===0){break inf_leave}utils.arraySet(output,input,next,copy,put);have-=copy;next+=copy;left-=copy;put+=copy;state.length-=copy;break}state.mode=TYPE;break;case TABLE:while(bits<14){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.nlen=(hold&31)+257;hold>>>=5;bits-=5;state.ndist=(hold&31)+1;hold>>>=5;bits-=5;state.ncode=(hold&15)+4;hold>>>=4;bits-=4;if(state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols";state.mode=BAD;break}state.have=0;state.mode=LENLENS;case LENLENS:while(state.have<state.ncode){while(bits<3){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.lens[order[state.have++]]=hold&7;hold>>>=3;bits-=3}while(state.have<19){state.lens[order[state.have++]]=0}state.lencode=state.lendyn;state.lenbits=7;opts={bits:state.lenbits};ret=inflate_table(CODES,state.lens,0,19,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid code lengths set";state.mode=BAD;break}state.have=0;state.mode=CODELENS;case CODELENS:while(state.have<state.nlen+state.ndist){for(;;){here=state.lencode[hold&(1<<state.lenbits)-1];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(here_val<16){hold>>>=here_bits;bits-=here_bits;state.lens[state.have++]=here_val}else{if(here_val===16){n=here_bits+2;while(bits<n){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}hold>>>=here_bits;bits-=here_bits;if(state.have===0){strm.msg="invalid bit length repeat";state.mode=BAD;break}len=state.lens[state.have-1];copy=3+(hold&3);hold>>>=2;bits-=2}else if(here_val===17){n=here_bits+3;while(bits<n){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}hold>>>=here_bits;bits-=here_bits;len=0;copy=3+(hold&7);hold>>>=3;bits-=3}else{n=here_bits+7;while(bits<n){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}hold>>>=here_bits;bits-=here_bits;len=0;copy=11+(hold&127);hold>>>=7;bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg="invalid bit length repeat";state.mode=BAD;break}while(copy--){state.lens[state.have++]=len}}}if(state.mode===BAD){break}if(state.lens[256]===0){strm.msg="invalid code -- missing end-of-block";state.mode=BAD;break}state.lenbits=9;opts={bits:state.lenbits};ret=inflate_table(LENS,state.lens,0,state.nlen,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid literal/lengths set";state.mode=BAD;break}state.distbits=6;state.distcode=state.distdyn;opts={bits:state.distbits};ret=inflate_table(DISTS,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts);state.distbits=opts.bits;if(ret){strm.msg="invalid distances set";state.mode=BAD;break}state.mode=LEN_;if(flush===Z_TREES){break inf_leave}case LEN_:state.mode=LEN;case LEN:if(have>=6&&left>=258){strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;inflate_fast(strm,_out);put=strm.next_out;output=strm.output;left=strm.avail_out;next=strm.next_in;input=strm.input;have=strm.avail_in;hold=state.hold;bits=state.bits;if(state.mode===TYPE){state.back=-1}break}state.back=0;for(;;){here=state.lencode[hold&(1<<state.lenbits)-1];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(here_op&&(here_op&240)===0){last_bits=here_bits;last_op=here_op;last_val=here_val;for(;;){here=state.lencode[last_val+((hold&(1<<last_bits+last_op)-1)>>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}hold>>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;state.length=here_val;if(here_op===0){state.mode=LIT;break}if(here_op&32){state.back=-1;state.mode=TYPE;break}if(here_op&64){strm.msg="invalid literal/length code";state.mode=BAD;break}state.extra=here_op&15;state.mode=LENEXT;case LENEXT:if(state.extra){n=state.extra;while(bits<n){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.length+=hold&(1<<state.extra)-1;hold>>>=state.extra;bits-=state.extra;state.back+=state.extra}state.was=state.length;state.mode=DIST;case DIST:for(;;){here=state.distcode[hold&(1<<state.distbits)-1];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if((here_op&240)===0){last_bits=here_bits;last_op=here_op;last_val=here_val;for(;;){here=state.distcode[last_val+((hold&(1<<last_bits+last_op)-1)>>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}hold>>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;if(here_op&64){strm.msg="invalid distance code";state.mode=BAD;break}state.offset=here_val;state.extra=here_op&15;state.mode=DISTEXT;case DISTEXT:if(state.extra){n=state.extra;while(bits<n){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}state.offset+=hold&(1<<state.extra)-1;hold>>>=state.extra;bits-=state.extra;state.back+=state.extra}if(state.offset>state.dmax){strm.msg="invalid distance too far back";state.mode=BAD;break}state.mode=MATCH;case MATCH:if(left===0){break inf_leave}copy=_out-left;if(state.offset>copy){copy=state.offset-copy;if(copy>state.whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break}}if(copy>state.wnext){copy-=state.wnext;from=state.wsize-copy}else{from=state.wnext-copy}if(copy>state.length){copy=state.length}from_source=state.window}else{from_source=output;from=put-state.offset;copy=state.length}if(copy>left){copy=left}left-=copy;state.length-=copy;do{output[put++]=from_source[from++]}while(--copy);if(state.length===0){state.mode=LEN}break;case LIT:if(left===0){break inf_leave}output[put++]=state.length;left--;state.mode=LEN;break;case CHECK:if(state.wrap){while(bits<32){if(have===0){break inf_leave}have--;hold|=input[next++]<<bits;bits+=8}_out-=left;strm.total_out+=_out;state.total+=_out;if(_out){strm.adler=state.check=state.flags?crc32(state.check,output,_out,put-_out):adler32(state.check,output,_out,put-_out)}_out=left;if((state.flags?hold:zswap32(hold))!==state.check){strm.msg="incorrect data check";state.mode=BAD;break}hold=0;bits=0}state.mode=LENGTH;case LENGTH:if(state.wrap&&state.flags){while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<<bits;bits+=8}if(hold!==(state.total&4294967295)){strm.msg="incorrect length check";state.mode=BAD;break}hold=0;bits=0}state.mode=DONE;case DONE:ret=Z_STREAM_END;break inf_leave;case BAD:ret=Z_DATA_ERROR;break inf_leave;case MEM:return Z_MEM_ERROR;case SYNC:default:return Z_STREAM_ERROR}}strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;if(state.wsize||_out!==strm.avail_out&&state.mode<BAD&&(state.mode<CHECK||flush!==Z_FINISH)){if(updatewindow(strm,strm.output,strm.next_out,_out-strm.avail_out)){state.mode=MEM;return Z_MEM_ERROR}}_in-=strm.avail_in;_out-=strm.avail_out;strm.total_in+=_in;strm.total_out+=_out;state.total+=_out;if(state.wrap&&_out){strm.adler=state.check=state.flags?crc32(state.check,output,_out,strm.next_out-_out):adler32(state.check,output,_out,strm.next_out-_out)}strm.data_type=state.bits+(state.last?64:0)+(state.mode===TYPE?128:0)+(state.mode===LEN_||state.mode===COPY_?256:0);if((_in===0&&_out===0||flush===Z_FINISH)&&ret===Z_OK){ret=Z_BUF_ERROR}return ret}function inflateEnd(strm){if(!strm||!strm.state){return Z_STREAM_ERROR}var state=strm.state;if(state.window){state.window=null}strm.state=null;return Z_OK}function inflateGetHeader(strm,head){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;if((state.wrap&2)===0){return Z_STREAM_ERROR}state.head=head;head.done=false;return Z_OK}function inflateSetDictionary(strm,dictionary){var dictLength=dictionary.length;var state;var dictid;var ret;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;if(state.wrap!==0&&state.mode!==DICT){return Z_STREAM_ERROR}if(state.mode===DICT){dictid=1;dictid=adler32(dictid,dictionary,dictLength,0);if(dictid!==state.check){return Z_DATA_ERROR}}ret=updatewindow(strm,dictionary,dictLength,dictLength);if(ret){state.mode=MEM;return Z_MEM_ERROR}state.havedict=1;return Z_OK}exports.inflateReset=inflateReset;exports.inflateReset2=inflateReset2;exports.inflateResetKeep=inflateResetKeep;exports.inflateInit=inflateInit;exports.inflateInit2=inflateInit2;exports.inflate=inflate;exports.inflateEnd=inflateEnd;exports.inflateGetHeader=inflateGetHeader;exports.inflateSetDictionary=inflateSetDictionary;exports.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":155,"./adler32":156,"./crc32":158,"./inffast":160,"./inftrees":162}],162:[function(require,module,exports){"use strict";var utils=require("../utils/common");var MAXBITS=15;var ENOUGH_LENS=852;var ENOUGH_DISTS=592;var CODES=0;var LENS=1;var DISTS=2;var lbase=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0];var lext=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78];var dbase=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0];var dext=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];module.exports=function inflate_table(type,lens,lens_index,codes,table,table_index,work,opts){var bits=opts.bits;var len=0;var sym=0;var min=0,max=0;var root=0;var curr=0;var drop=0;var left=0;var used=0;var huff=0;var incr;var fill;var low;var mask;var next;var base=null;var base_index=0;var end;var count=new utils.Buf16(MAXBITS+1);var offs=new utils.Buf16(MAXBITS+1);var extra=null;var extra_index=0;var here_bits,here_op,here_val;for(len=0;len<=MAXBITS;len++){count[len]=0}for(sym=0;sym<codes;sym++){count[lens[lens_index+sym]]++}root=bits;for(max=MAXBITS;max>=1;max--){if(count[max]!==0){break}}if(root>max){root=max}if(max===0){table[table_index++]=1<<24|64<<16|0;table[table_index++]=1<<24|64<<16|0;opts.bits=1;return 0}for(min=1;min<max;min++){if(count[min]!==0){break}}if(root<min){root=min}left=1;for(len=1;len<=MAXBITS;len++){left<<=1;left-=count[len];if(left<0){return-1}}if(left>0&&(type===CODES||max!==1)){return-1}offs[1]=0;for(len=1;len<MAXBITS;len++){offs[len+1]=offs[len]+count[len]}for(sym=0;sym<codes;sym++){if(lens[lens_index+sym]!==0){work[offs[lens[lens_index+sym]]++]=sym}}if(type===CODES){base=extra=work;end=19}else if(type===LENS){base=lbase;base_index-=257;extra=lext;extra_index-=257;end=256}else{base=dbase;extra=dext;end=-1}huff=0;sym=0;len=min;next=table_index;curr=root;drop=0;low=-1;used=1<<root;mask=used-1;if(type===LENS&&used>ENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}var i=0;for(;;){i++;here_bits=len-drop;if(work[sym]<end){here_op=0;here_val=work[sym]}else if(work[sym]>end){here_op=extra[extra_index+work[sym]];here_val=base[base_index+work[sym]]}else{here_op=32+64;here_val=0}incr=1<<len-drop;fill=1<<curr;min=fill;do{fill-=incr;table[next+(huff>>drop)+fill]=here_bits<<24|here_op<<16|here_val|0}while(fill!==0);incr=1<<len-1;while(huff&incr){incr>>=1}if(incr!==0){huff&=incr-1;huff+=incr}else{huff=0}sym++;if(--count[len]===0){if(len===max){break}len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){if(drop===0){drop=root}next+=min;curr=len-drop;left=1<<curr;while(curr+drop<max){left-=count[curr+drop];if(left<=0){break}curr++;left<<=1}used+=1<<curr;if(type===LENS&&used>ENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}low=huff&mask;table[low]=root<<24|curr<<16|next-table_index|0}}if(huff!==0){table[next+huff]=len-drop<<24|64<<16|0}opts.bits=root;return 0}},{"../utils/common":155}],163:[function(require,module,exports){"use strict";module.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],164:[function(require,module,exports){"use strict";var utils=require("../utils/common");var Z_FIXED=4;var Z_BINARY=0;var Z_TEXT=1;var Z_UNKNOWN=2;function zero(buf){var len=buf.length;while(--len>=0){buf[len]=0}}var STORED_BLOCK=0;var STATIC_TREES=1;var DYN_TREES=2;var MIN_MATCH=3;var MAX_MATCH=258;var LENGTH_CODES=29;var LITERALS=256;var L_CODES=LITERALS+1+LENGTH_CODES;var D_CODES=30;var BL_CODES=19;var HEAP_SIZE=2*L_CODES+1;var MAX_BITS=15;var Buf_size=16;var MAX_BL_BITS=7;var END_BLOCK=256;var REP_3_6=16;var REPZ_3_10=17;var REPZ_11_138=18;var extra_lbits=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];var extra_dbits=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];var extra_blbits=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];var bl_order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];var DIST_CODE_LEN=512;var static_ltree=new Array((L_CODES+2)*2);zero(static_ltree);var static_dtree=new Array(D_CODES*2);zero(static_dtree);var _dist_code=new Array(DIST_CODE_LEN);zero(_dist_code);var _length_code=new Array(MAX_MATCH-MIN_MATCH+1);zero(_length_code);var base_length=new Array(LENGTH_CODES);zero(base_length);var base_dist=new Array(D_CODES);zero(base_dist);function StaticTreeDesc(static_tree,extra_bits,extra_base,elems,max_length){this.static_tree=static_tree;this.extra_bits=extra_bits;this.extra_base=extra_base;this.elems=elems;this.max_length=max_length;this.has_stree=static_tree&&static_tree.length}var static_l_desc;var static_d_desc;var static_bl_desc;function TreeDesc(dyn_tree,stat_desc){this.dyn_tree=dyn_tree;this.max_code=0;this.stat_desc=stat_desc}function d_code(dist){return dist<256?_dist_code[dist]:_dist_code[256+(dist>>>7)]}function put_short(s,w){s.pending_buf[s.pending++]=w&255;s.pending_buf[s.pending++]=w>>>8&255}function send_bits(s,value,length){if(s.bi_valid>Buf_size-length){s.bi_buf|=value<<s.bi_valid&65535;put_short(s,s.bi_buf);s.bi_buf=value>>Buf_size-s.bi_valid;s.bi_valid+=length-Buf_size}else{s.bi_buf|=value<<s.bi_valid&65535;s.bi_valid+=length}}function send_code(s,c,tree){send_bits(s,tree[c*2],tree[c*2+1])}function bi_reverse(code,len){var res=0;do{res|=code&1;code>>>=1;res<<=1}while(--len>0);return res>>>1}function bi_flush(s){if(s.bi_valid===16){put_short(s,s.bi_buf);s.bi_buf=0;s.bi_valid=0}else if(s.bi_valid>=8){s.pending_buf[s.pending++]=s.bi_buf&255;s.bi_buf>>=8;s.bi_valid-=8}}function gen_bitlen(s,desc){var tree=desc.dyn_tree;var max_code=desc.max_code;var stree=desc.stat_desc.static_tree;var has_stree=desc.stat_desc.has_stree;var extra=desc.stat_desc.extra_bits;var base=desc.stat_desc.extra_base;var max_length=desc.stat_desc.max_length;var h;var n,m;var bits;var xbits;var f;var overflow=0;for(bits=0;bits<=MAX_BITS;bits++){s.bl_count[bits]=0}tree[s.heap[s.heap_max]*2+1]=0;for(h=s.heap_max+1;h<HEAP_SIZE;h++){n=s.heap[h];bits=tree[tree[n*2+1]*2+1]+1;if(bits>max_length){bits=max_length;overflow++}tree[n*2+1]=bits;if(n>max_code){continue}s.bl_count[bits]++;xbits=0;if(n>=base){xbits=extra[n-base]}f=tree[n*2];s.opt_len+=f*(bits+xbits);if(has_stree){s.static_len+=f*(stree[n*2+1]+xbits)}}if(overflow===0){return}do{bits=max_length-1;while(s.bl_count[bits]===0){bits--}s.bl_count[bits]--;s.bl_count[bits+1]+=2;s.bl_count[max_length]--;overflow-=2}while(overflow>0);for(bits=max_length;bits!==0;bits--){n=s.bl_count[bits];while(n!==0){m=s.heap[--h];if(m>max_code){continue}if(tree[m*2+1]!==bits){s.opt_len+=(bits-tree[m*2+1])*tree[m*2];tree[m*2+1]=bits}n--}}}function gen_codes(tree,max_code,bl_count){var next_code=new Array(MAX_BITS+1);var code=0;var bits;var n;for(bits=1;bits<=MAX_BITS;bits++){next_code[bits]=code=code+bl_count[bits-1]<<1}for(n=0;n<=max_code;n++){var len=tree[n*2+1];if(len===0){continue}tree[n*2]=bi_reverse(next_code[len]++,len)}}function tr_static_init(){var n;var bits;var length;var code;var dist;var bl_count=new Array(MAX_BITS+1);length=0;for(code=0;code<LENGTH_CODES-1;code++){base_length[code]=length;for(n=0;n<1<<extra_lbits[code];n++){_length_code[length++]=code}}_length_code[length-1]=code;dist=0;for(code=0;code<16;code++){base_dist[code]=dist;for(n=0;n<1<<extra_dbits[code];n++){_dist_code[dist++]=code}}dist>>=7;for(;code<D_CODES;code++){base_dist[code]=dist<<7;for(n=0;n<1<<extra_dbits[code]-7;n++){_dist_code[256+dist++]=code}}for(bits=0;bits<=MAX_BITS;bits++){bl_count[bits]=0}n=0;while(n<=143){static_ltree[n*2+1]=8;n++;bl_count[8]++}while(n<=255){static_ltree[n*2+1]=9;n++;bl_count[9]++}while(n<=279){static_ltree[n*2+1]=7;n++;bl_count[7]++}while(n<=287){static_ltree[n*2+1]=8;n++;bl_count[8]++}gen_codes(static_ltree,L_CODES+1,bl_count);for(n=0;n<D_CODES;n++){static_dtree[n*2+1]=5;static_dtree[n*2]=bi_reverse(n,5)}static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,LITERALS+1,L_CODES,MAX_BITS);static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,D_CODES,MAX_BITS);static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES,MAX_BL_BITS)}function init_block(s){var n;for(n=0;n<L_CODES;n++){s.dyn_ltree[n*2]=0}for(n=0;n<D_CODES;n++){s.dyn_dtree[n*2]=0}for(n=0;n<BL_CODES;n++){s.bl_tree[n*2]=0}s.dyn_ltree[END_BLOCK*2]=1;s.opt_len=s.static_len=0;s.last_lit=s.matches=0}function bi_windup(s){if(s.bi_valid>8){put_short(s,s.bi_buf)}else if(s.bi_valid>0){s.pending_buf[s.pending++]=s.bi_buf}s.bi_buf=0;s.bi_valid=0}function copy_block(s,buf,len,header){bi_windup(s);if(header){put_short(s,len);put_short(s,~len)}utils.arraySet(s.pending_buf,s.window,buf,len,s.pending);s.pending+=len}function smaller(tree,n,m,depth){var _n2=n*2;var _m2=m*2;return tree[_n2]<tree[_m2]||tree[_n2]===tree[_m2]&&depth[n]<=depth[m]}function pqdownheap(s,tree,k){var v=s.heap[k];var j=k<<1;while(j<=s.heap_len){if(j<s.heap_len&&smaller(tree,s.heap[j+1],s.heap[j],s.depth)){j++}if(smaller(tree,v,s.heap[j],s.depth)){break}s.heap[k]=s.heap[j];k=j;j<<=1}s.heap[k]=v}function compress_block(s,ltree,dtree){var dist;var lc;var lx=0;var code;var extra;if(s.last_lit!==0){do{dist=s.pending_buf[s.d_buf+lx*2]<<8|s.pending_buf[s.d_buf+lx*2+1];lc=s.pending_buf[s.l_buf+lx];lx++;if(dist===0){send_code(s,lc,ltree)}else{code=_length_code[lc];send_code(s,code+LITERALS+1,ltree);extra=extra_lbits[code];if(extra!==0){lc-=base_length[code];send_bits(s,lc,extra)}dist--;code=d_code(dist);send_code(s,code,dtree);extra=extra_dbits[code];if(extra!==0){dist-=base_dist[code];send_bits(s,dist,extra)}}}while(lx<s.last_lit)}send_code(s,END_BLOCK,ltree)}function build_tree(s,desc){var tree=desc.dyn_tree;var stree=desc.stat_desc.static_tree;var has_stree=desc.stat_desc.has_stree;var elems=desc.stat_desc.elems;var n,m;var max_code=-1;var node;s.heap_len=0;s.heap_max=HEAP_SIZE;for(n=0;n<elems;n++){if(tree[n*2]!==0){s.heap[++s.heap_len]=max_code=n;s.depth[n]=0}else{tree[n*2+1]=0}}while(s.heap_len<2){node=s.heap[++s.heap_len]=max_code<2?++max_code:0;tree[node*2]=1;s.depth[node]=0;s.opt_len--;if(has_stree){s.static_len-=stree[node*2+1]}}desc.max_code=max_code;for(n=s.heap_len>>1;n>=1;n--){pqdownheap(s,tree,n)}node=elems;do{n=s.heap[1];s.heap[1]=s.heap[s.heap_len--];pqdownheap(s,tree,1);m=s.heap[1];s.heap[--s.heap_max]=n;s.heap[--s.heap_max]=m;tree[node*2]=tree[n*2]+tree[m*2];s.depth[node]=(s.depth[n]>=s.depth[m]?s.depth[n]:s.depth[m])+1;tree[n*2+1]=tree[m*2+1]=node;s.heap[1]=node++;pqdownheap(s,tree,1)}while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1];gen_bitlen(s,desc);gen_codes(tree,max_code,s.bl_count)}function scan_tree(s,tree,max_code){var n;var prevlen=-1;var curlen;var nextlen=tree[0*2+1];var count=0;var max_count=7;var min_count=4;if(nextlen===0){max_count=138;min_count=3}tree[(max_code+1)*2+1]=65535;for(n=0;n<=max_code;n++){curlen=nextlen;nextlen=tree[(n+1)*2+1];if(++count<max_count&&curlen===nextlen){continue}else if(count<min_count){s.bl_tree[curlen*2]+=count}else if(curlen!==0){if(curlen!==prevlen){s.bl_tree[curlen*2]++}s.bl_tree[REP_3_6*2]++}else if(count<=10){s.bl_tree[REPZ_3_10*2]++}else{s.bl_tree[REPZ_11_138*2]++}count=0;prevlen=curlen;if(nextlen===0){max_count=138;min_count=3}else if(curlen===nextlen){max_count=6;min_count=3}else{max_count=7;min_count=4}}}function send_tree(s,tree,max_code){var n;var prevlen=-1;var curlen;var nextlen=tree[0*2+1];var count=0;var max_count=7;var min_count=4;if(nextlen===0){max_count=138;min_count=3}for(n=0;n<=max_code;n++){curlen=nextlen;nextlen=tree[(n+1)*2+1];if(++count<max_count&&curlen===nextlen){continue}else if(count<min_count){do{send_code(s,curlen,s.bl_tree)}while(--count!==0)}else if(curlen!==0){if(curlen!==prevlen){send_code(s,curlen,s.bl_tree);count--}send_code(s,REP_3_6,s.bl_tree);send_bits(s,count-3,2)}else if(count<=10){send_code(s,REPZ_3_10,s.bl_tree);send_bits(s,count-3,3)}else{send_code(s,REPZ_11_138,s.bl_tree);send_bits(s,count-11,7)}count=0;prevlen=curlen;if(nextlen===0){max_count=138;min_count=3}else if(curlen===nextlen){max_count=6;min_count=3}else{max_count=7;min_count=4}}}function build_bl_tree(s){var max_blindex;scan_tree(s,s.dyn_ltree,s.l_desc.max_code);scan_tree(s,s.dyn_dtree,s.d_desc.max_code);build_tree(s,s.bl_desc);for(max_blindex=BL_CODES-1;max_blindex>=3;max_blindex--){if(s.bl_tree[bl_order[max_blindex]*2+1]!==0){break}}s.opt_len+=3*(max_blindex+1)+5+5+4;return max_blindex}function send_all_trees(s,lcodes,dcodes,blcodes){var rank;send_bits(s,lcodes-257,5);send_bits(s,dcodes-1,5);send_bits(s,blcodes-4,4);for(rank=0;rank<blcodes;rank++){send_bits(s,s.bl_tree[bl_order[rank]*2+1],3)}send_tree(s,s.dyn_ltree,lcodes-1);send_tree(s,s.dyn_dtree,dcodes-1)}function detect_data_type(s){var black_mask=4093624447;var n;for(n=0;n<=31;n++,black_mask>>>=1){if(black_mask&1&&s.dyn_ltree[n*2]!==0){return Z_BINARY}}
@@ -20,22 +20,22 @@ if(s.dyn_ltree[9*2]!==0||s.dyn_ltree[10*2]!==0||s.dyn_ltree[13*2]!==0){return Z_
20
20
  ;this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform)}else{ts.needTransform=true}};Transform.prototype._destroy=function(err,cb){var _this2=this;Duplex.prototype._destroy.call(this,err,function(err2){cb(err2);_this2.emit("close")})};function done(stream,er,data){if(er)return stream.emit("error",er);if(data!=null)stream.push(data);if(stream._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(stream._transformState.transforming)throw new Error("Calling transform done when still transforming");return stream.push(null)}},{"./_stream_duplex":194,"core-util-is":74,inherits:145}],198:[function(require,module,exports){(function(process,global,setImmediate){(function(){"use strict";var pna=require("process-nextick-args");module.exports=Writable;function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}function CorkedRequest(state){var _this=this;this.next=null;this.entry=null;this.finish=function(){onCorkedFinish(_this,state)}}var asyncWrite=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:pna.nextTick;var Duplex;Writable.WritableState=WritableState;var util=Object.create(require("core-util-is"));util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")};var Stream=require("./internal/streams/stream");var Buffer=require("safe-buffer").Buffer;var OurUint8Array=global.Uint8Array||function(){};function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}var destroyImpl=require("./internal/streams/destroy");util.inherits(Writable,Stream);function nop(){}function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};var isDuplex=stream instanceof Duplex;this.objectMode=!!options.objectMode;if(isDuplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var writableHwm=options.writableHighWaterMark;var defaultHwm=this.objectMode?16:16*1024;if(hwm||hwm===0)this.highWaterMark=hwm;else if(isDuplex&&(writableHwm||writableHwm===0))this.highWaterMark=writableHwm;else this.highWaterMark=defaultHwm;this.highWaterMark=Math.floor(this.highWaterMark);this.finalCalled=false;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;this.destroyed=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var current=this.bufferedRequest;var out=[];while(current){out.push(current);current=current.next}return out};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.","DEP0003")})}catch(_){}})();var realHasInstance;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){realHasInstance=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){if(realHasInstance.call(this,object))return true;if(this!==Writable)return false;return object&&object._writableState instanceof WritableState}})}else{realHasInstance=function(object){return object instanceof this}}function Writable(options){Duplex=Duplex||require("./_stream_duplex");if(!realHasInstance.call(Writable,this)&&!(this instanceof Duplex)){return new Writable(options)}this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev;if(typeof options.destroy==="function")this._destroy=options.destroy;if(typeof options.final==="function")this._final=options.final}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);pna.nextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=true;var er=false;if(chunk===null){er=new TypeError("May not write null values to stream")}else if(typeof chunk!=="string"&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}if(er){stream.emit("error",er);pna.nextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;var isBuf=!state.objectMode&&_isUint8Array(chunk);if(isBuf&&!Buffer.isBuffer(chunk)){chunk=_uint8ArrayToBuffer(chunk)}if(typeof encoding==="function"){cb=encoding;encoding=null}if(isBuf)encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(isBuf||validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)}return ret};Writable.prototype.cork=function(){var state=this._writableState;state.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!state.finished&&!state.bufferProcessing&&state.bufferedRequest)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=encoding.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=Buffer.from(chunk,encoding)}return chunk}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){var newChunk=decodeChunk(state,chunk,encoding);if(chunk!==newChunk){isBuf=true;encoding="buffer";chunk=newChunk}}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(!ret)state.needDrain=true;if(state.writing||state.corked){var last=state.lastBufferedRequest;state.lastBufferedRequest={chunk:chunk,encoding:encoding,isBuf:isBuf,callback:cb,next:null};if(last){last.next=state.lastBufferedRequest}else{state.bufferedRequest=state.lastBufferedRequest}state.bufferedRequestCount+=1}else{doWrite(stream,state,false,len,chunk,encoding,cb)}return ret}function doWrite(stream,state,writev,len,chunk,encoding,cb){state.writelen=len;state.writecb=cb;state.writing=true;state.sync=true;if(writev)stream._writev(chunk,state.onwrite);else stream._write(chunk,encoding,state.onwrite);state.sync=false}function onwriteError(stream,state,sync,er,cb){--state.pendingcb;if(sync){pna.nextTick(cb,er);pna.nextTick(finishMaybe,stream,state);stream._writableState.errorEmitted=true;stream.emit("error",er)}else{cb(er);stream._writableState.errorEmitted=true;stream.emit("error",er);finishMaybe(stream,state)}}function onwriteStateUpdate(state){state.writing=false;state.writecb=null;state.length-=state.writelen;state.writelen=0}function onwrite(stream,er){var state=stream._writableState;var sync=state.sync;var cb=state.writecb;onwriteStateUpdate(state);if(er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(state);if(!finished&&!state.corked&&!state.bufferProcessing&&state.bufferedRequest){clearBuffer(stream,state)}if(sync){asyncWrite(afterWrite,stream,state,finished,cb)}else{afterWrite(stream,state,finished,cb)}}}function afterWrite(stream,state,finished,cb){if(!finished)onwriteDrain(stream,state);state.pendingcb--;cb();finishMaybe(stream,state)}function onwriteDrain(stream,state){if(state.length===0&&state.needDrain){state.needDrain=false;stream.emit("drain")}}function clearBuffer(stream,state){state.bufferProcessing=true;var entry=state.bufferedRequest;if(stream._writev&&entry&&entry.next){var l=state.bufferedRequestCount;var buffer=new Array(l);var holder=state.corkedRequestsFree;holder.entry=entry;var count=0;var allBuffers=true;while(entry){buffer[count]=entry;if(!entry.isBuf)allBuffers=false;entry=entry.next;count+=1}buffer.allBuffers=allBuffers;doWrite(stream,state,true,state.length,buffer,"",holder.finish);state.pendingcb++;state.lastBufferedRequest=null;if(holder.next){state.corkedRequestsFree=holder.next;holder.next=null}else{state.corkedRequestsFree=new CorkedRequest(state)}state.bufferedRequestCount=0}else{while(entry){var chunk=entry.chunk;var encoding=entry.encoding;var cb=entry.callback;var len=state.objectMode?1:chunk.length;doWrite(stream,state,false,len,chunk,encoding,cb);entry=entry.next;state.bufferedRequestCount--;if(state.writing){break}}if(entry===null)state.lastBufferedRequest=null}state.bufferedRequest=entry;state.bufferProcessing=false}Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("_write() is not implemented"))};Writable.prototype._writev=null;Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;if(typeof chunk==="function"){cb=chunk;chunk=null;encoding=null}else if(typeof encoding==="function"){cb=encoding;encoding=null}if(chunk!==null&&chunk!==undefined)this.write(chunk,encoding);if(state.corked){state.corked=1;this.uncork()}if(!state.ending&&!state.finished)endWritable(this,state,cb)};function needFinish(state){return state.ending&&state.length===0&&state.bufferedRequest===null&&!state.finished&&!state.writing}function callFinal(stream,state){stream._final(function(err){state.pendingcb--;if(err){stream.emit("error",err)}state.prefinished=true;stream.emit("prefinish");finishMaybe(stream,state)})}function prefinish(stream,state){if(!state.prefinished&&!state.finalCalled){if(typeof stream._final==="function"){state.pendingcb++;state.finalCalled=true;pna.nextTick(callFinal,stream,state)}else{state.prefinished=true;stream.emit("prefinish")}}}function finishMaybe(stream,state){var need=needFinish(state);if(need){prefinish(stream,state);if(state.pendingcb===0){state.finished=true;stream.emit("finish")}}return need}function endWritable(stream,state,cb){state.ending=true;finishMaybe(stream,state);if(cb){if(state.finished)pna.nextTick(cb);else stream.once("finish",cb)}state.ended=true;stream.writable=false}function onCorkedFinish(corkReq,state,err){var entry=corkReq.entry;corkReq.entry=null;while(entry){var cb=entry.callback;state.pendingcb--;cb(err);entry=entry.next}if(state.corkedRequestsFree){state.corkedRequestsFree.next=corkReq}else{state.corkedRequestsFree=corkReq}}Object.defineProperty(Writable.prototype,"destroyed",{get:function(){if(this._writableState===undefined){return false}return this._writableState.destroyed},set:function(value){if(!this._writableState){return}this._writableState.destroyed=value}});Writable.prototype.destroy=destroyImpl.destroy;Writable.prototype._undestroy=destroyImpl.undestroy;Writable.prototype._destroy=function(err,cb){this.end();cb(err)}}).call(this)}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("timers").setImmediate)},{"./_stream_duplex":194,"./internal/streams/destroy":200,"./internal/streams/stream":201,_process:179,"core-util-is":74,inherits:145,"process-nextick-args":178,"safe-buffer":202,timers:236,"util-deprecate":240}],199:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var Buffer=require("safe-buffer").Buffer;var util=require("util");function copyBuffer(src,target,offset){src.copy(target,offset)}module.exports=function(){function BufferList(){_classCallCheck(this,BufferList);this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function push(v){var entry={data:v,next:null};if(this.length>0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function unshift(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function shift(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret};BufferList.prototype.clear=function clear(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function join(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret};BufferList.prototype.concat=function concat(n){if(this.length===0)return Buffer.alloc(0);if(this.length===1)return this.head.data;var ret=Buffer.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){copyBuffer(p.data,ret,i);i+=p.data.length;p=p.next}return ret};return BufferList}();if(util&&util.inspect&&util.inspect.custom){module.exports.prototype[util.inspect.custom]=function(){var obj=util.inspect({length:this.length});return this.constructor.name+" "+obj}}},{"safe-buffer":202,util:23}],200:[function(require,module,exports){"use strict";var pna=require("process-nextick-args");function destroy(err,cb){var _this=this;var readableDestroyed=this._readableState&&this._readableState.destroyed;var writableDestroyed=this._writableState&&this._writableState.destroyed;if(readableDestroyed||writableDestroyed){if(cb){cb(err)}else if(err&&(!this._writableState||!this._writableState.errorEmitted)){pna.nextTick(emitErrorNT,this,err)}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(err||null,function(err){if(!cb&&err){pna.nextTick(emitErrorNT,_this,err);if(_this._writableState){_this._writableState.errorEmitted=true}}else if(cb){cb(err)}});return this}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(self,err){self.emit("error",err)}module.exports={destroy:destroy,undestroy:undestroy}},{"process-nextick-args":178}],201:[function(require,module,exports){arguments[4][64][0].apply(exports,arguments)},{dup:64,events:110}],202:[function(require,module,exports){var buffer=require("buffer");var Buffer=buffer.Buffer;function copyProps(src,dst){for(var key in src){dst[key]=src[key]}}if(Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow){module.exports=buffer}else{copyProps(buffer,exports);exports.Buffer=SafeBuffer}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}copyProps(Buffer,SafeBuffer);SafeBuffer.from=function(arg,encodingOrOffset,length){if(typeof arg==="number"){throw new TypeError("Argument must not be a number")}return Buffer(arg,encodingOrOffset,length)};SafeBuffer.alloc=function(size,fill,encoding){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}var buf=Buffer(size);if(fill!==undefined){if(typeof encoding==="string"){buf.fill(fill,encoding)}else{buf.fill(fill)}}else{buf.fill(0)}return buf};SafeBuffer.allocUnsafe=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return Buffer(size)};SafeBuffer.allocUnsafeSlow=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return buffer.SlowBuffer(size)}},{buffer:71}],203:[function(require,module,exports){arguments[4][66][0].apply(exports,arguments)},{dup:66,"safe-buffer":202}],204:[function(require,module,exports){module.exports=require("./readable").PassThrough},{"./readable":205}],205:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js");exports.Stream=exports;exports.Readable=exports;exports.Writable=require("./lib/_stream_writable.js");exports.Duplex=require("./lib/_stream_duplex.js");exports.Transform=require("./lib/_stream_transform.js");exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":194,"./lib/_stream_passthrough.js":195,"./lib/_stream_readable.js":196,"./lib/_stream_transform.js":197,"./lib/_stream_writable.js":198}],206:[function(require,module,exports){module.exports=require("./readable").Transform},{"./readable":205}],207:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":198}],208:[function(require,module,exports){"use strict";var Buffer=require("buffer").Buffer;var inherits=require("inherits");var HashBase=require("hash-base");var ARRAY16=new Array(16);var zl=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13];var zr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11];var sl=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6];var sr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11];var hl=[0,1518500249,1859775393,2400959708,2840853838];var hr=[1352829926,1548603684,1836072691,2053994217,0];function RIPEMD160(){HashBase.call(this,64);this._a=1732584193;this._b=4023233417;this._c=2562383102;this._d=271733878;this._e=3285377520}inherits(RIPEMD160,HashBase);RIPEMD160.prototype._update=function(){var words=ARRAY16;for(var j=0;j<16;++j)words[j]=this._block.readInt32LE(j*4);var al=this._a|0;var bl=this._b|0;var cl=this._c|0;var dl=this._d|0;var el=this._e|0;var ar=this._a|0;var br=this._b|0;var cr=this._c|0;var dr=this._d|0;var er=this._e|0;for(var i=0;i<80;i+=1){var tl;var tr;if(i<16){tl=fn1(al,bl,cl,dl,el,words[zl[i]],hl[0],sl[i]);tr=fn5(ar,br,cr,dr,er,words[zr[i]],hr[0],sr[i])}else if(i<32){tl=fn2(al,bl,cl,dl,el,words[zl[i]],hl[1],sl[i]);tr=fn4(ar,br,cr,dr,er,words[zr[i]],hr[1],sr[i])}else if(i<48){tl=fn3(al,bl,cl,dl,el,words[zl[i]],hl[2],sl[i]);tr=fn3(ar,br,cr,dr,er,words[zr[i]],hr[2],sr[i])}else if(i<64){tl=fn4(al,bl,cl,dl,el,words[zl[i]],hl[3],sl[i]);tr=fn2(ar,br,cr,dr,er,words[zr[i]],hr[3],sr[i])}else{tl=fn5(al,bl,cl,dl,el,words[zl[i]],hl[4],sl[i]);tr=fn1(ar,br,cr,dr,er,words[zr[i]],hr[4],sr[i])}al=el;el=dl;dl=rotl(cl,10);cl=bl;bl=tl;ar=er;er=dr;dr=rotl(cr,10);cr=br;br=tr}var t=this._b+cl+dr|0;this._b=this._c+dl+er|0;this._c=this._d+el+ar|0;this._d=this._e+al+br|0;this._e=this._a+bl+cr|0;this._a=t};RIPEMD160.prototype._digest=function(){this._block[this._blockOffset++]=128;if(this._blockOffset>56){this._block.fill(0,this._blockOffset,64);this._update();this._blockOffset=0}this._block.fill(0,this._blockOffset,56);this._block.writeUInt32LE(this._length[0],56);this._block.writeUInt32LE(this._length[1],60);this._update();var buffer=Buffer.alloc?Buffer.alloc(20):new Buffer(20);buffer.writeInt32LE(this._a,0);buffer.writeInt32LE(this._b,4);buffer.writeInt32LE(this._c,8);buffer.writeInt32LE(this._d,12);buffer.writeInt32LE(this._e,16);return buffer};function rotl(x,n){return x<<n|x>>>32-n}function fn1(a,b,c,d,e,m,k,s){return rotl(a+(b^c^d)+m+k|0,s)+e|0}function fn2(a,b,c,d,e,m,k,s){return rotl(a+(b&c|~b&d)+m+k|0,s)+e|0}function fn3(a,b,c,d,e,m,k,s){return rotl(a+((b|~c)^d)+m+k|0,s)+e|0}function fn4(a,b,c,d,e,m,k,s){return rotl(a+(b&d|c&~d)+m+k|0,s)+e|0}function fn5(a,b,c,d,e,m,k,s){return rotl(a+(b^(c|~d))+m+k|0,s)+e|0}module.exports=RIPEMD160},{buffer:71,"hash-base":112,inherits:145}],209:[function(require,module,exports){var buffer=require("buffer");var Buffer=buffer.Buffer;function copyProps(src,dst){for(var key in src){dst[key]=src[key]}}if(Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow){module.exports=buffer}else{copyProps(buffer,exports);exports.Buffer=SafeBuffer}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}SafeBuffer.prototype=Object.create(Buffer.prototype);copyProps(Buffer,SafeBuffer);SafeBuffer.from=function(arg,encodingOrOffset,length){if(typeof arg==="number"){throw new TypeError("Argument must not be a number")}return Buffer(arg,encodingOrOffset,length)};SafeBuffer.alloc=function(size,fill,encoding){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}var buf=Buffer(size);if(fill!==undefined){if(typeof encoding==="string"){buf.fill(fill,encoding)}else{buf.fill(fill)}}else{buf.fill(0)}return buf};SafeBuffer.allocUnsafe=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return Buffer(size)};SafeBuffer.allocUnsafeSlow=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return buffer.SlowBuffer(size)}},{buffer:71}],210:[function(require,module,exports){var Buffer=require("safe-buffer").Buffer;function Hash(blockSize,finalSize){this._block=Buffer.alloc(blockSize);this._finalSize=finalSize;this._blockSize=blockSize;this._len=0}Hash.prototype.update=function(data,enc){if(typeof data==="string"){enc=enc||"utf8";data=Buffer.from(data,enc)}var block=this._block;var blockSize=this._blockSize;var length=data.length;var accum=this._len;for(var offset=0;offset<length;){var assigned=accum%blockSize;var remainder=Math.min(length-offset,blockSize-assigned);for(var i=0;i<remainder;i++){block[assigned+i]=data[offset+i]}accum+=remainder;offset+=remainder;if(accum%blockSize===0){this._update(block)}}this._len+=length;return this};Hash.prototype.digest=function(enc){var rem=this._len%this._blockSize;this._block[rem]=128;this._block.fill(0,rem+1);if(rem>=this._finalSize){this._update(this._block);this._block.fill(0)}var bits=this._len*8;if(bits<=4294967295){this._block.writeUInt32BE(bits,this._blockSize-4)}else{var lowBits=(bits&4294967295)>>>0;var highBits=(bits-lowBits)/4294967296;this._block.writeUInt32BE(highBits,this._blockSize-8);this._block.writeUInt32BE(lowBits,this._blockSize-4)}this._update(this._block);var hash=this._hash();return enc?hash.toString(enc):hash};Hash.prototype._update=function(){throw new Error("_update must be implemented by subclass")};module.exports=Hash},{"safe-buffer":209}],211:[function(require,module,exports){var exports=module.exports=function SHA(algorithm){algorithm=algorithm.toLowerCase();var Algorithm=exports[algorithm];if(!Algorithm)throw new Error(algorithm+" is not supported (we accept pull requests)");return new Algorithm};exports.sha=require("./sha");exports.sha1=require("./sha1");exports.sha224=require("./sha224");exports.sha256=require("./sha256");exports.sha384=require("./sha384");exports.sha512=require("./sha512")},{"./sha":212,"./sha1":213,"./sha224":214,"./sha256":215,"./sha384":216,"./sha512":217}],212:[function(require,module,exports){var inherits=require("inherits");var Hash=require("./hash");var Buffer=require("safe-buffer").Buffer;var K=[1518500249,1859775393,2400959708|0,3395469782|0];var W=new Array(80);function Sha(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha,Hash);Sha.prototype.init=function(){this._a=1732584193;this._b=4023233417;this._c=2562383102;this._d=271733878;this._e=3285377520;return this};function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){if(s===0)return b&c|~b&d;if(s===2)return b&c|b&d|c&d;return b^c^d}Sha.prototype._update=function(M){var W=this._w;var a=this._a|0;var b=this._b|0;var c=this._c|0;var d=this._d|0;var e=this._e|0;for(var i=0;i<16;++i)W[i]=M.readInt32BE(i*4);for(;i<80;++i)W[i]=W[i-3]^W[i-8]^W[i-14]^W[i-16];for(var j=0;j<80;++j){var s=~~(j/20);var t=rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s]|0;e=d;d=c;c=rotl30(b);b=a;a=t}this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0};Sha.prototype._hash=function(){var H=Buffer.allocUnsafe(20);H.writeInt32BE(this._a|0,0);H.writeInt32BE(this._b|0,4);H.writeInt32BE(this._c|0,8);H.writeInt32BE(this._d|0,12);H.writeInt32BE(this._e|0,16);return H};module.exports=Sha},{"./hash":210,inherits:145,"safe-buffer":209}],213:[function(require,module,exports){var inherits=require("inherits");var Hash=require("./hash");var Buffer=require("safe-buffer").Buffer;var K=[1518500249,1859775393,2400959708|0,3395469782|0];var W=new Array(80);function Sha1(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha1,Hash);Sha1.prototype.init=function(){this._a=1732584193;this._b=4023233417;this._c=2562383102;this._d=271733878;this._e=3285377520;return this};function rotl1(num){return num<<1|num>>>31}function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){if(s===0)return b&c|~b&d;if(s===2)return b&c|b&d|c&d;return b^c^d}Sha1.prototype._update=function(M){var W=this._w;var a=this._a|0;var b=this._b|0;var c=this._c|0;var d=this._d|0;var e=this._e|0;for(var i=0;i<16;++i)W[i]=M.readInt32BE(i*4);for(;i<80;++i)W[i]=rotl1(W[i-3]^W[i-8]^W[i-14]^W[i-16]);for(var j=0;j<80;++j){var s=~~(j/20);var t=rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s]|0;e=d;d=c;c=rotl30(b);b=a;a=t}this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0};Sha1.prototype._hash=function(){var H=Buffer.allocUnsafe(20);H.writeInt32BE(this._a|0,0);H.writeInt32BE(this._b|0,4);H.writeInt32BE(this._c|0,8);H.writeInt32BE(this._d|0,12);H.writeInt32BE(this._e|0,16);return H};module.exports=Sha1},{"./hash":210,inherits:145,"safe-buffer":209}],214:[function(require,module,exports){var inherits=require("inherits");var Sha256=require("./sha256");var Hash=require("./hash");var Buffer=require("safe-buffer").Buffer;var W=new Array(64);function Sha224(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha224,Sha256);Sha224.prototype.init=function(){this._a=3238371032;this._b=914150663;this._c=812702999;this._d=4144912697;this._e=4290775857;this._f=1750603025;this._g=1694076839;this._h=3204075428;return this};Sha224.prototype._hash=function(){var H=Buffer.allocUnsafe(28);H.writeInt32BE(this._a,0);H.writeInt32BE(this._b,4);H.writeInt32BE(this._c,8);H.writeInt32BE(this._d,12);H.writeInt32BE(this._e,16);H.writeInt32BE(this._f,20);H.writeInt32BE(this._g,24);return H};module.exports=Sha224},{"./hash":210,"./sha256":215,inherits:145,"safe-buffer":209}],215:[function(require,module,exports){var inherits=require("inherits");var Hash=require("./hash");var Buffer=require("safe-buffer").Buffer;var K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];var W=new Array(64);function Sha256(){this.init();this._w=W;Hash.call(this,64,56)}inherits(Sha256,Hash);Sha256.prototype.init=function(){this._a=1779033703;this._b=3144134277;this._c=1013904242;this._d=2773480762;this._e=1359893119;this._f=2600822924;this._g=528734635;this._h=1541459225;return this};function ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x){return(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10)}function sigma1(x){return(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7)}function gamma0(x){return(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3}function gamma1(x){return(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10}Sha256.prototype._update=function(M){var W=this._w;var a=this._a|0;var b=this._b|0;var c=this._c|0;var d=this._d|0;var e=this._e|0;var f=this._f|0;var g=this._g|0;var h=this._h|0;for(var i=0;i<16;++i)W[i]=M.readInt32BE(i*4);for(;i<64;++i)W[i]=gamma1(W[i-2])+W[i-7]+gamma0(W[i-15])+W[i-16]|0;for(var j=0;j<64;++j){var T1=h+sigma1(e)+ch(e,f,g)+K[j]+W[j]|0;var T2=sigma0(a)+maj(a,b,c)|0;h=g;g=f;f=e;e=d+T1|0;d=c;c=b;b=a;a=T1+T2|0}this._a=a+this._a|0;this._b=b+this._b|0;this._c=c+this._c|0;this._d=d+this._d|0;this._e=e+this._e|0;this._f=f+this._f|0;this._g=g+this._g|0;this._h=h+this._h|0};Sha256.prototype._hash=function(){var H=Buffer.allocUnsafe(32);H.writeInt32BE(this._a,0);H.writeInt32BE(this._b,4);H.writeInt32BE(this._c,8);H.writeInt32BE(this._d,12);H.writeInt32BE(this._e,16);H.writeInt32BE(this._f,20);H.writeInt32BE(this._g,24);H.writeInt32BE(this._h,28);return H};module.exports=Sha256},{"./hash":210,inherits:145,"safe-buffer":209}],216:[function(require,module,exports){var inherits=require("inherits");var SHA512=require("./sha512");var Hash=require("./hash");var Buffer=require("safe-buffer").Buffer;var W=new Array(160);function Sha384(){this.init();this._w=W;Hash.call(this,128,112)}inherits(Sha384,SHA512);Sha384.prototype.init=function(){this._ah=3418070365;this._bh=1654270250;this._ch=2438529370;this._dh=355462360;this._eh=1731405415;this._fh=2394180231;this._gh=3675008525;this._hh=1203062813;this._al=3238371032;this._bl=914150663;this._cl=812702999;this._dl=4144912697;this._el=4290775857;this._fl=1750603025;this._gl=1694076839;this._hl=3204075428;return this};Sha384.prototype._hash=function(){var H=Buffer.allocUnsafe(48);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset);H.writeInt32BE(l,offset+4)}writeInt64BE(this._ah,this._al,0);writeInt64BE(this._bh,this._bl,8);writeInt64BE(this._ch,this._cl,16);writeInt64BE(this._dh,this._dl,24);writeInt64BE(this._eh,this._el,32);writeInt64BE(this._fh,this._fl,40);return H};module.exports=Sha384},{"./hash":210,"./sha512":217,inherits:145,"safe-buffer":209}],217:[function(require,module,exports){var inherits=require("inherits");var Hash=require("./hash");var Buffer=require("safe-buffer").Buffer
21
21
  ;var K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];var W=new Array(160);function Sha512(){this.init();this._w=W;Hash.call(this,128,112)}inherits(Sha512,Hash);Sha512.prototype.init=function(){this._ah=1779033703;this._bh=3144134277;this._ch=1013904242;this._dh=2773480762;this._eh=1359893119;this._fh=2600822924;this._gh=528734635;this._hh=1541459225;this._al=4089235720;this._bl=2227873595;this._cl=4271175723;this._dl=1595750129;this._el=2917565137;this._fl=725511199;this._gl=4215389547;this._hl=327033209;return this};function Ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x,xl){return(x>>>28|xl<<4)^(xl>>>2|x<<30)^(xl>>>7|x<<25)}function sigma1(x,xl){return(x>>>14|xl<<18)^(x>>>18|xl<<14)^(xl>>>9|x<<23)}function Gamma0(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^x>>>7}function Gamma0l(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^(x>>>7|xl<<25)}function Gamma1(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^x>>>6}function Gamma1l(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^(x>>>6|xl<<26)}function getCarry(a,b){return a>>>0<b>>>0?1:0}Sha512.prototype._update=function(M){var W=this._w;var ah=this._ah|0;var bh=this._bh|0;var ch=this._ch|0;var dh=this._dh|0;var eh=this._eh|0;var fh=this._fh|0;var gh=this._gh|0;var hh=this._hh|0;var al=this._al|0;var bl=this._bl|0;var cl=this._cl|0;var dl=this._dl|0;var el=this._el|0;var fl=this._fl|0;var gl=this._gl|0;var hl=this._hl|0;for(var i=0;i<32;i+=2){W[i]=M.readInt32BE(i*4);W[i+1]=M.readInt32BE(i*4+4)}for(;i<160;i+=2){var xh=W[i-15*2];var xl=W[i-15*2+1];var gamma0=Gamma0(xh,xl);var gamma0l=Gamma0l(xl,xh);xh=W[i-2*2];xl=W[i-2*2+1];var gamma1=Gamma1(xh,xl);var gamma1l=Gamma1l(xl,xh);var Wi7h=W[i-7*2];var Wi7l=W[i-7*2+1];var Wi16h=W[i-16*2];var Wi16l=W[i-16*2+1];var Wil=gamma0l+Wi7l|0;var Wih=gamma0+Wi7h+getCarry(Wil,gamma0l)|0;Wil=Wil+gamma1l|0;Wih=Wih+gamma1+getCarry(Wil,gamma1l)|0;Wil=Wil+Wi16l|0;Wih=Wih+Wi16h+getCarry(Wil,Wi16l)|0;W[i]=Wih;W[i+1]=Wil}for(var j=0;j<160;j+=2){Wih=W[j];Wil=W[j+1];var majh=maj(ah,bh,ch);var majl=maj(al,bl,cl);var sigma0h=sigma0(ah,al);var sigma0l=sigma0(al,ah);var sigma1h=sigma1(eh,el);var sigma1l=sigma1(el,eh);var Kih=K[j];var Kil=K[j+1];var chh=Ch(eh,fh,gh);var chl=Ch(el,fl,gl);var t1l=hl+sigma1l|0;var t1h=hh+sigma1h+getCarry(t1l,hl)|0;t1l=t1l+chl|0;t1h=t1h+chh+getCarry(t1l,chl)|0;t1l=t1l+Kil|0;t1h=t1h+Kih+getCarry(t1l,Kil)|0;t1l=t1l+Wil|0;t1h=t1h+Wih+getCarry(t1l,Wil)|0;var t2l=sigma0l+majl|0;var t2h=sigma0h+majh+getCarry(t2l,sigma0l)|0;hh=gh;hl=gl;gh=fh;gl=fl;fh=eh;fl=el;el=dl+t1l|0;eh=dh+t1h+getCarry(el,dl)|0;dh=ch;dl=cl;ch=bh;cl=bl;bh=ah;bl=al;al=t1l+t2l|0;ah=t1h+t2h+getCarry(al,t1l)|0}this._al=this._al+al|0;this._bl=this._bl+bl|0;this._cl=this._cl+cl|0;this._dl=this._dl+dl|0;this._el=this._el+el|0;this._fl=this._fl+fl|0;this._gl=this._gl+gl|0;this._hl=this._hl+hl|0;this._ah=this._ah+ah+getCarry(this._al,al)|0;this._bh=this._bh+bh+getCarry(this._bl,bl)|0;this._ch=this._ch+ch+getCarry(this._cl,cl)|0;this._dh=this._dh+dh+getCarry(this._dl,dl)|0;this._eh=this._eh+eh+getCarry(this._el,el)|0;this._fh=this._fh+fh+getCarry(this._fl,fl)|0;this._gh=this._gh+gh+getCarry(this._gl,gl)|0;this._hh=this._hh+hh+getCarry(this._hl,hl)|0};Sha512.prototype._hash=function(){var H=Buffer.allocUnsafe(64);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset);H.writeInt32BE(l,offset+4)}writeInt64BE(this._ah,this._al,0);writeInt64BE(this._bh,this._bl,8);writeInt64BE(this._ch,this._cl,16);writeInt64BE(this._dh,this._dl,24);writeInt64BE(this._eh,this._el,32);writeInt64BE(this._fh,this._fl,40);writeInt64BE(this._gh,this._gl,48);writeInt64BE(this._hh,this._hl,56);return H};module.exports=Sha512},{"./hash":210,inherits:145,"safe-buffer":209}],218:[function(require,module,exports){var util=require("./util");var has=Object.prototype.hasOwnProperty;var hasNativeMap=typeof Map!=="undefined";function ArraySet(){this._array=[];this._set=hasNativeMap?new Map:Object.create(null)}ArraySet.fromArray=function ArraySet_fromArray(aArray,aAllowDuplicates){var set=new ArraySet;for(var i=0,len=aArray.length;i<len;i++){set.add(aArray[i],aAllowDuplicates)}return set};ArraySet.prototype.size=function ArraySet_size(){return hasNativeMap?this._set.size:Object.getOwnPropertyNames(this._set).length};ArraySet.prototype.add=function ArraySet_add(aStr,aAllowDuplicates){var sStr=hasNativeMap?aStr:util.toSetString(aStr);var isDuplicate=hasNativeMap?this.has(aStr):has.call(this._set,sStr);var idx=this._array.length;if(!isDuplicate||aAllowDuplicates){this._array.push(aStr)}if(!isDuplicate){if(hasNativeMap){this._set.set(aStr,idx)}else{this._set[sStr]=idx}}};ArraySet.prototype.has=function ArraySet_has(aStr){if(hasNativeMap){return this._set.has(aStr)}else{var sStr=util.toSetString(aStr);return has.call(this._set,sStr)}};ArraySet.prototype.indexOf=function ArraySet_indexOf(aStr){if(hasNativeMap){var idx=this._set.get(aStr);if(idx>=0){return idx}}else{var sStr=util.toSetString(aStr);if(has.call(this._set,sStr)){return this._set[sStr]}}throw new Error('"'+aStr+'" is not in the set.')};ArraySet.prototype.at=function ArraySet_at(aIdx){if(aIdx>=0&&aIdx<this._array.length){return this._array[aIdx]}throw new Error("No element indexed by "+aIdx)};ArraySet.prototype.toArray=function ArraySet_toArray(){return this._array.slice()};exports.ArraySet=ArraySet},{"./util":227}],219:[function(require,module,exports){var base64=require("./base64");var VLQ_BASE_SHIFT=5;var VLQ_BASE=1<<VLQ_BASE_SHIFT;var VLQ_BASE_MASK=VLQ_BASE-1;var VLQ_CONTINUATION_BIT=VLQ_BASE;function toVLQSigned(aValue){return aValue<0?(-aValue<<1)+1:(aValue<<1)+0}function fromVLQSigned(aValue){var isNegative=(aValue&1)===1;var shifted=aValue>>1;return isNegative?-shifted:shifted}exports.encode=function base64VLQ_encode(aValue){var encoded="";var digit;var vlq=toVLQSigned(aValue);do{digit=vlq&VLQ_BASE_MASK;vlq>>>=VLQ_BASE_SHIFT;if(vlq>0){digit|=VLQ_CONTINUATION_BIT}encoded+=base64.encode(digit)}while(vlq>0);return encoded};exports.decode=function base64VLQ_decode(aStr,aIndex,aOutParam){var strLen=aStr.length;var result=0;var shift=0;var continuation,digit;do{if(aIndex>=strLen){throw new Error("Expected more digits in base 64 VLQ value.")}digit=base64.decode(aStr.charCodeAt(aIndex++));if(digit===-1){throw new Error("Invalid base64 digit: "+aStr.charAt(aIndex-1))}continuation=!!(digit&VLQ_CONTINUATION_BIT);digit&=VLQ_BASE_MASK;result=result+(digit<<shift);shift+=VLQ_BASE_SHIFT}while(continuation);aOutParam.value=fromVLQSigned(result);aOutParam.rest=aIndex}},{"./base64":220}],220:[function(require,module,exports){var intToCharMap="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");exports.encode=function(number){if(0<=number&&number<intToCharMap.length){return intToCharMap[number]}throw new TypeError("Must be between 0 and 63: "+number)};exports.decode=function(charCode){var bigA=65;var bigZ=90;var littleA=97;var littleZ=122;var zero=48;var nine=57;var plus=43;var slash=47;var littleOffset=26;var numberOffset=52;if(bigA<=charCode&&charCode<=bigZ){return charCode-bigA}if(littleA<=charCode&&charCode<=littleZ){return charCode-littleA+littleOffset}if(zero<=charCode&&charCode<=nine){return charCode-zero+numberOffset}if(charCode==plus){return 62}if(charCode==slash){return 63}return-1}},{}],221:[function(require,module,exports){exports.GREATEST_LOWER_BOUND=1;exports.LEAST_UPPER_BOUND=2;function recursiveSearch(aLow,aHigh,aNeedle,aHaystack,aCompare,aBias){var mid=Math.floor((aHigh-aLow)/2)+aLow;var cmp=aCompare(aNeedle,aHaystack[mid],true);if(cmp===0){return mid}else if(cmp>0){if(aHigh-mid>1){return recursiveSearch(mid,aHigh,aNeedle,aHaystack,aCompare,aBias)}if(aBias==exports.LEAST_UPPER_BOUND){return aHigh<aHaystack.length?aHigh:-1}else{return mid}}else{if(mid-aLow>1){return recursiveSearch(aLow,mid,aNeedle,aHaystack,aCompare,aBias)}if(aBias==exports.LEAST_UPPER_BOUND){return mid}else{return aLow<0?-1:aLow}}}exports.search=function search(aNeedle,aHaystack,aCompare,aBias){if(aHaystack.length===0){return-1}var index=recursiveSearch(-1,aHaystack.length,aNeedle,aHaystack,aCompare,aBias||exports.GREATEST_LOWER_BOUND);if(index<0){return-1}while(index-1>=0){if(aCompare(aHaystack[index],aHaystack[index-1],true)!==0){break}--index}return index}},{}],222:[function(require,module,exports){var util=require("./util");function generatedPositionAfter(mappingA,mappingB){var lineA=mappingA.generatedLine;var lineB=mappingB.generatedLine;var columnA=mappingA.generatedColumn;var columnB=mappingB.generatedColumn;return lineB>lineA||lineB==lineA&&columnB>=columnA||util.compareByGeneratedPositionsInflated(mappingA,mappingB)<=0}function MappingList(){this._array=[];this._sorted=true;this._last={generatedLine:-1,generatedColumn:0}}MappingList.prototype.unsortedForEach=function MappingList_forEach(aCallback,aThisArg){this._array.forEach(aCallback,aThisArg)};MappingList.prototype.add=function MappingList_add(aMapping){if(generatedPositionAfter(this._last,aMapping)){this._last=aMapping;this._array.push(aMapping)}else{this._sorted=false;this._array.push(aMapping)}};MappingList.prototype.toArray=function MappingList_toArray(){if(!this._sorted){this._array.sort(util.compareByGeneratedPositionsInflated);this._sorted=true}return this._array};exports.MappingList=MappingList},{"./util":227}],223:[function(require,module,exports){function swap(ary,x,y){var temp=ary[x];ary[x]=ary[y];ary[y]=temp}function randomIntInRange(low,high){return Math.round(low+Math.random()*(high-low))}function doQuickSort(ary,comparator,p,r){if(p<r){var pivotIndex=randomIntInRange(p,r);var i=p-1;swap(ary,pivotIndex,r);var pivot=ary[r];for(var j=p;j<r;j++){if(comparator(ary[j],pivot)<=0){i+=1;swap(ary,i,j)}}swap(ary,i+1,j);var q=i+1;doQuickSort(ary,comparator,p,q-1);doQuickSort(ary,comparator,q+1,r)}}exports.quickSort=function(ary,comparator){doQuickSort(ary,comparator,0,ary.length-1)}},{}],224:[function(require,module,exports){var util=require("./util");var binarySearch=require("./binary-search");var ArraySet=require("./array-set").ArraySet;var base64VLQ=require("./base64-vlq");var quickSort=require("./quick-sort").quickSort;function SourceMapConsumer(aSourceMap){var sourceMap=aSourceMap;if(typeof aSourceMap==="string"){sourceMap=JSON.parse(aSourceMap.replace(/^\)\]\}'/,""))}return sourceMap.sections!=null?new IndexedSourceMapConsumer(sourceMap):new BasicSourceMapConsumer(sourceMap)}SourceMapConsumer.fromSourceMap=function(aSourceMap){return BasicSourceMapConsumer.fromSourceMap(aSourceMap)};SourceMapConsumer.prototype._version=3;SourceMapConsumer.prototype.__generatedMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_generatedMappings",{get:function(){if(!this.__generatedMappings){this._parseMappings(this._mappings,this.sourceRoot)}return this.__generatedMappings}});SourceMapConsumer.prototype.__originalMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_originalMappings",{get:function(){if(!this.__originalMappings){this._parseMappings(this._mappings,this.sourceRoot)}return this.__originalMappings}});SourceMapConsumer.prototype._charIsMappingSeparator=function SourceMapConsumer_charIsMappingSeparator(aStr,index){var c=aStr.charAt(index);return c===";"||c===","};SourceMapConsumer.prototype._parseMappings=function SourceMapConsumer_parseMappings(aStr,aSourceRoot){throw new Error("Subclasses must implement _parseMappings")};SourceMapConsumer.GENERATED_ORDER=1;SourceMapConsumer.ORIGINAL_ORDER=2;SourceMapConsumer.GREATEST_LOWER_BOUND=1;SourceMapConsumer.LEAST_UPPER_BOUND=2;SourceMapConsumer.prototype.eachMapping=function SourceMapConsumer_eachMapping(aCallback,aContext,aOrder){var context=aContext||null;var order=aOrder||SourceMapConsumer.GENERATED_ORDER;var mappings;switch(order){case SourceMapConsumer.GENERATED_ORDER:mappings=this._generatedMappings;break;case SourceMapConsumer.ORIGINAL_ORDER:mappings=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var sourceRoot=this.sourceRoot;mappings.map(function(mapping){var source=mapping.source===null?null:this._sources.at(mapping.source);if(source!=null&&sourceRoot!=null){source=util.join(sourceRoot,source)}return{source:source,generatedLine:mapping.generatedLine,generatedColumn:mapping.generatedColumn,originalLine:mapping.originalLine,originalColumn:mapping.originalColumn,name:mapping.name===null?null:this._names.at(mapping.name)}},this).forEach(aCallback,context)};SourceMapConsumer.prototype.allGeneratedPositionsFor=function SourceMapConsumer_allGeneratedPositionsFor(aArgs){var line=util.getArg(aArgs,"line");var needle={source:util.getArg(aArgs,"source"),originalLine:line,originalColumn:util.getArg(aArgs,"column",0)};if(this.sourceRoot!=null){needle.source=util.relative(this.sourceRoot,needle.source)}if(!this._sources.has(needle.source)){return[]}needle.source=this._sources.indexOf(needle.source);var mappings=[];var index=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions,binarySearch.LEAST_UPPER_BOUND);if(index>=0){var mapping=this._originalMappings[index];if(aArgs.column===undefined){var originalLine=mapping.originalLine;while(mapping&&mapping.originalLine===originalLine){mappings.push({line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null),lastColumn:util.getArg(mapping,"lastGeneratedColumn",null)});mapping=this._originalMappings[++index]}}else{var originalColumn=mapping.originalColumn;while(mapping&&mapping.originalLine===line&&mapping.originalColumn==originalColumn){mappings.push({line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null),lastColumn:util.getArg(mapping,"lastGeneratedColumn",null)});mapping=this._originalMappings[++index]}}}return mappings};exports.SourceMapConsumer=SourceMapConsumer;function BasicSourceMapConsumer(aSourceMap){var sourceMap=aSourceMap;if(typeof aSourceMap==="string"){sourceMap=JSON.parse(aSourceMap.replace(/^\)\]\}'/,""))}var version=util.getArg(sourceMap,"version");var sources=util.getArg(sourceMap,"sources");var names=util.getArg(sourceMap,"names",[]);var sourceRoot=util.getArg(sourceMap,"sourceRoot",null);var sourcesContent=util.getArg(sourceMap,"sourcesContent",null);var mappings=util.getArg(sourceMap,"mappings");var file=util.getArg(sourceMap,"file",null);if(version!=this._version){throw new Error("Unsupported version: "+version)}sources=sources.map(String).map(util.normalize).map(function(source){return sourceRoot&&util.isAbsolute(sourceRoot)&&util.isAbsolute(source)?util.relative(sourceRoot,source):source});this._names=ArraySet.fromArray(names.map(String),true);this._sources=ArraySet.fromArray(sources,true);this.sourceRoot=sourceRoot;this.sourcesContent=sourcesContent;this._mappings=mappings;this.file=file}BasicSourceMapConsumer.prototype=Object.create(SourceMapConsumer.prototype);BasicSourceMapConsumer.prototype.consumer=SourceMapConsumer;BasicSourceMapConsumer.fromSourceMap=function SourceMapConsumer_fromSourceMap(aSourceMap){var smc=Object.create(BasicSourceMapConsumer.prototype);var names=smc._names=ArraySet.fromArray(aSourceMap._names.toArray(),true);var sources=smc._sources=ArraySet.fromArray(aSourceMap._sources.toArray(),true);smc.sourceRoot=aSourceMap._sourceRoot;smc.sourcesContent=aSourceMap._generateSourcesContent(smc._sources.toArray(),smc.sourceRoot);smc.file=aSourceMap._file;var generatedMappings=aSourceMap._mappings.toArray().slice();var destGeneratedMappings=smc.__generatedMappings=[];var destOriginalMappings=smc.__originalMappings=[];for(var i=0,length=generatedMappings.length;i<length;i++){var srcMapping=generatedMappings[i];var destMapping=new Mapping;destMapping.generatedLine=srcMapping.generatedLine;destMapping.generatedColumn=srcMapping.generatedColumn;if(srcMapping.source){destMapping.source=sources.indexOf(srcMapping.source);destMapping.originalLine=srcMapping.originalLine;destMapping.originalColumn=srcMapping.originalColumn;if(srcMapping.name){destMapping.name=names.indexOf(srcMapping.name)}destOriginalMappings.push(destMapping)}destGeneratedMappings.push(destMapping)}quickSort(smc.__originalMappings,util.compareByOriginalPositions);return smc};BasicSourceMapConsumer.prototype._version=3;Object.defineProperty(BasicSourceMapConsumer.prototype,"sources",{get:function(){return this._sources.toArray().map(function(s){return this.sourceRoot!=null?util.join(this.sourceRoot,s):s},this)}});function Mapping(){this.generatedLine=0;this.generatedColumn=0;this.source=null;this.originalLine=null;this.originalColumn=null;this.name=null}BasicSourceMapConsumer.prototype._parseMappings=function SourceMapConsumer_parseMappings(aStr,aSourceRoot){var generatedLine=1;var previousGeneratedColumn=0;var previousOriginalLine=0;var previousOriginalColumn=0;var previousSource=0;var previousName=0;var length=aStr.length;var index=0;var cachedSegments={};var temp={};var originalMappings=[];var generatedMappings=[];var mapping,str,segment,end,value;while(index<length){if(aStr.charAt(index)===";"){generatedLine++;index++;previousGeneratedColumn=0}else if(aStr.charAt(index)===","){index++}else{mapping=new Mapping;mapping.generatedLine=generatedLine;for(end=index;end<length;end++){if(this._charIsMappingSeparator(aStr,end)){break}}str=aStr.slice(index,end);segment=cachedSegments[str];if(segment){index+=str.length}else{segment=[];while(index<end){base64VLQ.decode(aStr,index,temp);value=temp.value;index=temp.rest;segment.push(value)}if(segment.length===2){throw new Error("Found a source, but no line and column")}if(segment.length===3){throw new Error("Found a source and line, but no column")}cachedSegments[str]=segment}mapping.generatedColumn=previousGeneratedColumn+segment[0];previousGeneratedColumn=mapping.generatedColumn;if(segment.length>1){mapping.source=previousSource+segment[1];previousSource+=segment[1];mapping.originalLine=previousOriginalLine+segment[2];previousOriginalLine=mapping.originalLine;mapping.originalLine+=1;mapping.originalColumn=previousOriginalColumn+segment[3];previousOriginalColumn=mapping.originalColumn;if(segment.length>4){mapping.name=previousName+segment[4];previousName+=segment[4]}}generatedMappings.push(mapping);if(typeof mapping.originalLine==="number"){originalMappings.push(mapping)}}}quickSort(generatedMappings,util.compareByGeneratedPositionsDeflated);this.__generatedMappings=generatedMappings;quickSort(originalMappings,util.compareByOriginalPositions);this.__originalMappings=originalMappings};BasicSourceMapConsumer.prototype._findMapping=function SourceMapConsumer_findMapping(aNeedle,aMappings,aLineName,aColumnName,aComparator,aBias){if(aNeedle[aLineName]<=0){throw new TypeError("Line must be greater than or equal to 1, got "+aNeedle[aLineName])}if(aNeedle[aColumnName]<0){throw new TypeError("Column must be greater than or equal to 0, got "+aNeedle[aColumnName])}return binarySearch.search(aNeedle,aMappings,aComparator,aBias)};BasicSourceMapConsumer.prototype.computeColumnSpans=function SourceMapConsumer_computeColumnSpans(){for(var index=0;index<this._generatedMappings.length;++index){var mapping=this._generatedMappings[index];if(index+1<this._generatedMappings.length){var nextMapping=this._generatedMappings[index+1];if(mapping.generatedLine===nextMapping.generatedLine){mapping.lastGeneratedColumn=nextMapping.generatedColumn-1;continue}}mapping.lastGeneratedColumn=Infinity}};BasicSourceMapConsumer.prototype.originalPositionFor=function SourceMapConsumer_originalPositionFor(aArgs){var needle={generatedLine:util.getArg(aArgs,"line"),generatedColumn:util.getArg(aArgs,"column")};var index=this._findMapping(needle,this._generatedMappings,"generatedLine","generatedColumn",util.compareByGeneratedPositionsDeflated,util.getArg(aArgs,"bias",SourceMapConsumer.GREATEST_LOWER_BOUND));if(index>=0){var mapping=this._generatedMappings[index];if(mapping.generatedLine===needle.generatedLine){var source=util.getArg(mapping,"source",null);if(source!==null){source=this._sources.at(source);if(this.sourceRoot!=null){source=util.join(this.sourceRoot,source)}}var name=util.getArg(mapping,"name",null);if(name!==null){name=this._names.at(name)}return{source:source,line:util.getArg(mapping,"originalLine",null),column:util.getArg(mapping,"originalColumn",null),name:name}}}return{source:null,line:null,column:null,name:null}};BasicSourceMapConsumer.prototype.hasContentsOfAllSources=function BasicSourceMapConsumer_hasContentsOfAllSources(){if(!this.sourcesContent){return false}return this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(sc){return sc==null})};BasicSourceMapConsumer.prototype.sourceContentFor=function SourceMapConsumer_sourceContentFor(aSource,nullOnMissing){if(!this.sourcesContent){return null}if(this.sourceRoot!=null){aSource=util.relative(this.sourceRoot,aSource)}if(this._sources.has(aSource)){return this.sourcesContent[this._sources.indexOf(aSource)]}var url;if(this.sourceRoot!=null&&(url=util.urlParse(this.sourceRoot))){var fileUriAbsPath=aSource.replace(/^file:\/\//,"");if(url.scheme=="file"&&this._sources.has(fileUriAbsPath)){return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]}if((!url.path||url.path=="/")&&this._sources.has("/"+aSource)){return this.sourcesContent[this._sources.indexOf("/"+aSource)]}}if(nullOnMissing){return null}else{throw new Error('"'+aSource+'" is not in the SourceMap.')}};BasicSourceMapConsumer.prototype.generatedPositionFor=function SourceMapConsumer_generatedPositionFor(aArgs){var source=util.getArg(aArgs,"source");if(this.sourceRoot!=null){source=util.relative(this.sourceRoot,source)}if(!this._sources.has(source)){return{line:null,column:null,lastColumn:null}}source=this._sources.indexOf(source);var needle={source:source,originalLine:util.getArg(aArgs,"line"),originalColumn:util.getArg(aArgs,"column")};var index=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions,util.getArg(aArgs,"bias",SourceMapConsumer.GREATEST_LOWER_BOUND));if(index>=0){var mapping=this._originalMappings[index];if(mapping.source===needle.source){return{line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null),lastColumn:util.getArg(mapping,"lastGeneratedColumn",null)}}}return{line:null,column:null,lastColumn:null}};exports.BasicSourceMapConsumer=BasicSourceMapConsumer;function IndexedSourceMapConsumer(aSourceMap){var sourceMap=aSourceMap;if(typeof aSourceMap==="string"){sourceMap=JSON.parse(aSourceMap.replace(/^\)\]\}'/,""))}var version=util.getArg(sourceMap,"version");var sections=util.getArg(sourceMap,"sections");if(version!=this._version){throw new Error("Unsupported version: "+version)}this._sources=new ArraySet;this._names=new ArraySet;var lastOffset={line:-1,column:0};this._sections=sections.map(function(s){if(s.url){throw new Error("Support for url field in sections not implemented.")}var offset=util.getArg(s,"offset");var offsetLine=util.getArg(offset,"line");var offsetColumn=util.getArg(offset,"column");if(offsetLine<lastOffset.line||offsetLine===lastOffset.line&&offsetColumn<lastOffset.column){throw new Error("Section offsets must be ordered and non-overlapping.")}lastOffset=offset;return{generatedOffset:{generatedLine:offsetLine+1,generatedColumn:offsetColumn+1},consumer:new SourceMapConsumer(util.getArg(s,"map"))}})}IndexedSourceMapConsumer.prototype=Object.create(SourceMapConsumer.prototype);IndexedSourceMapConsumer.prototype.constructor=SourceMapConsumer;IndexedSourceMapConsumer.prototype._version=3;Object.defineProperty(IndexedSourceMapConsumer.prototype,"sources",{get:function(){var sources=[];for(var i=0;i<this._sections.length;i++){for(var j=0;j<this._sections[i].consumer.sources.length;j++){sources.push(this._sections[i].consumer.sources[j])}}return sources}});IndexedSourceMapConsumer.prototype.originalPositionFor=function IndexedSourceMapConsumer_originalPositionFor(aArgs){var needle={generatedLine:util.getArg(aArgs,"line"),generatedColumn:util.getArg(aArgs,"column")};var sectionIndex=binarySearch.search(needle,this._sections,function(needle,section){var cmp=needle.generatedLine-section.generatedOffset.generatedLine;if(cmp){return cmp}return needle.generatedColumn-section.generatedOffset.generatedColumn});var section=this._sections[sectionIndex];if(!section){return{source:null,line:null,column:null,name:null}}return section.consumer.originalPositionFor({line:needle.generatedLine-(section.generatedOffset.generatedLine-1),column:needle.generatedColumn-(section.generatedOffset.generatedLine===needle.generatedLine?section.generatedOffset.generatedColumn-1:0),bias:aArgs.bias})};IndexedSourceMapConsumer.prototype.hasContentsOfAllSources=function IndexedSourceMapConsumer_hasContentsOfAllSources(){return this._sections.every(function(s){return s.consumer.hasContentsOfAllSources()})};IndexedSourceMapConsumer.prototype.sourceContentFor=function IndexedSourceMapConsumer_sourceContentFor(aSource,nullOnMissing){for(var i=0;i<this._sections.length;i++){var section=this._sections[i];var content=section.consumer.sourceContentFor(aSource,true);if(content){return content}}if(nullOnMissing){return null}else{throw new Error('"'+aSource+'" is not in the SourceMap.')}};IndexedSourceMapConsumer.prototype.generatedPositionFor=function IndexedSourceMapConsumer_generatedPositionFor(aArgs){for(var i=0;i<this._sections.length;i++){var section=this._sections[i];if(section.consumer.sources.indexOf(util.getArg(aArgs,"source"))===-1){continue}var generatedPosition=section.consumer.generatedPositionFor(aArgs);if(generatedPosition){var ret={line:generatedPosition.line+(section.generatedOffset.generatedLine-1),column:generatedPosition.column+(section.generatedOffset.generatedLine===generatedPosition.line?section.generatedOffset.generatedColumn-1:0)};return ret}}return{line:null,column:null}};IndexedSourceMapConsumer.prototype._parseMappings=function IndexedSourceMapConsumer_parseMappings(aStr,aSourceRoot){this.__generatedMappings=[];this.__originalMappings=[];for(var i=0;i<this._sections.length;i++){var section=this._sections[i];var sectionMappings=section.consumer._generatedMappings;for(var j=0;j<sectionMappings.length;j++){var mapping=sectionMappings[j];var source=section.consumer._sources.at(mapping.source);if(section.consumer.sourceRoot!==null){source=util.join(section.consumer.sourceRoot,source)}this._sources.add(source);source=this._sources.indexOf(source);var name=section.consumer._names.at(mapping.name);this._names.add(name);name=this._names.indexOf(name);var adjustedMapping={source:source,generatedLine:mapping.generatedLine+(section.generatedOffset.generatedLine-1),generatedColumn:mapping.generatedColumn+(section.generatedOffset.generatedLine===mapping.generatedLine?section.generatedOffset.generatedColumn-1:0),originalLine:mapping.originalLine,originalColumn:mapping.originalColumn,name:name};this.__generatedMappings.push(adjustedMapping);if(typeof adjustedMapping.originalLine==="number"){this.__originalMappings.push(adjustedMapping)}}}quickSort(this.__generatedMappings,util.compareByGeneratedPositionsDeflated);quickSort(this.__originalMappings,util.compareByOriginalPositions)};exports.IndexedSourceMapConsumer=IndexedSourceMapConsumer},{"./array-set":218,"./base64-vlq":219,"./binary-search":221,"./quick-sort":223,"./util":227}],225:[function(require,module,exports){var base64VLQ=require("./base64-vlq");var util=require("./util");var ArraySet=require("./array-set").ArraySet;var MappingList=require("./mapping-list").MappingList;function SourceMapGenerator(aArgs){if(!aArgs){aArgs={}}this._file=util.getArg(aArgs,"file",null);this._sourceRoot=util.getArg(aArgs,"sourceRoot",null);this._skipValidation=util.getArg(aArgs,"skipValidation",false);this._sources=new ArraySet;this._names=new ArraySet;this._mappings=new MappingList;this._sourcesContents=null}SourceMapGenerator.prototype._version=3;SourceMapGenerator.fromSourceMap=function SourceMapGenerator_fromSourceMap(aSourceMapConsumer){var sourceRoot=aSourceMapConsumer.sourceRoot;var generator=new SourceMapGenerator({file:aSourceMapConsumer.file,sourceRoot:sourceRoot});aSourceMapConsumer.eachMapping(function(mapping){var newMapping={generated:{line:mapping.generatedLine,column:mapping.generatedColumn}};if(mapping.source!=null){newMapping.source=mapping.source;if(sourceRoot!=null){newMapping.source=util.relative(sourceRoot,newMapping.source)}newMapping.original={line:mapping.originalLine,column:mapping.originalColumn};if(mapping.name!=null){newMapping.name=mapping.name}}generator.addMapping(newMapping)});aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){generator.setSourceContent(sourceFile,content)}});return generator};SourceMapGenerator.prototype.addMapping=function SourceMapGenerator_addMapping(aArgs){var generated=util.getArg(aArgs,"generated");var original=util.getArg(aArgs,"original",null);var source=util.getArg(aArgs,"source",null);var name=util.getArg(aArgs,"name",null);if(!this._skipValidation){this._validateMapping(generated,original,source,name)}if(source!=null){source=String(source);if(!this._sources.has(source)){this._sources.add(source)}}if(name!=null){name=String(name);if(!this._names.has(name)){this._names.add(name)}}this._mappings.add({generatedLine:generated.line,generatedColumn:generated.column,originalLine:original!=null&&original.line,originalColumn:original!=null&&original.column,source:source,name:name})};SourceMapGenerator.prototype.setSourceContent=function SourceMapGenerator_setSourceContent(aSourceFile,aSourceContent){var source=aSourceFile;if(this._sourceRoot!=null){source=util.relative(this._sourceRoot,source)}if(aSourceContent!=null){if(!this._sourcesContents){this._sourcesContents=Object.create(null)}this._sourcesContents[util.toSetString(source)]=aSourceContent}else if(this._sourcesContents){delete this._sourcesContents[util.toSetString(source)];if(Object.keys(this._sourcesContents).length===0){this._sourcesContents=null}}};SourceMapGenerator.prototype.applySourceMap=function SourceMapGenerator_applySourceMap(aSourceMapConsumer,aSourceFile,aSourceMapPath){var sourceFile=aSourceFile;if(aSourceFile==null){if(aSourceMapConsumer.file==null){throw new Error("SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, "+'or the source map\'s "file" property. Both were omitted.')}
22
22
  sourceFile=aSourceMapConsumer.file}var sourceRoot=this._sourceRoot;if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}var newSources=new ArraySet;var newNames=new ArraySet;this._mappings.unsortedForEach(function(mapping){if(mapping.source===sourceFile&&mapping.originalLine!=null){var original=aSourceMapConsumer.originalPositionFor({line:mapping.originalLine,column:mapping.originalColumn});if(original.source!=null){mapping.source=original.source;if(aSourceMapPath!=null){mapping.source=util.join(aSourceMapPath,mapping.source)}if(sourceRoot!=null){mapping.source=util.relative(sourceRoot,mapping.source)}mapping.originalLine=original.line;mapping.originalColumn=original.column;if(original.name!=null){mapping.name=original.name}}}var source=mapping.source;if(source!=null&&!newSources.has(source)){newSources.add(source)}var name=mapping.name;if(name!=null&&!newNames.has(name)){newNames.add(name)}},this);this._sources=newSources;this._names=newNames;aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aSourceMapPath!=null){sourceFile=util.join(aSourceMapPath,sourceFile)}if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}this.setSourceContent(sourceFile,content)}},this)};SourceMapGenerator.prototype._validateMapping=function SourceMapGenerator_validateMapping(aGenerated,aOriginal,aSource,aName){if(aOriginal&&typeof aOriginal.line!=="number"&&typeof aOriginal.column!=="number"){throw new Error("original.line and original.column are not numbers -- you probably meant to omit "+"the original mapping entirely and only map the generated position. If so, pass "+"null for the original mapping instead of an object with empty or null values.")}if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aGenerated.line>0&&aGenerated.column>=0&&!aOriginal&&!aSource&&!aName){return}else if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aOriginal&&"line"in aOriginal&&"column"in aOriginal&&aGenerated.line>0&&aGenerated.column>=0&&aOriginal.line>0&&aOriginal.column>=0&&aSource){return}else{throw new Error("Invalid mapping: "+JSON.stringify({generated:aGenerated,source:aSource,original:aOriginal,name:aName}))}};SourceMapGenerator.prototype._serializeMappings=function SourceMapGenerator_serializeMappings(){var previousGeneratedColumn=0;var previousGeneratedLine=1;var previousOriginalColumn=0;var previousOriginalLine=0;var previousName=0;var previousSource=0;var result="";var next;var mapping;var nameIdx;var sourceIdx;var mappings=this._mappings.toArray();for(var i=0,len=mappings.length;i<len;i++){mapping=mappings[i];next="";if(mapping.generatedLine!==previousGeneratedLine){previousGeneratedColumn=0;while(mapping.generatedLine!==previousGeneratedLine){next+=";";previousGeneratedLine++}}else{if(i>0){if(!util.compareByGeneratedPositionsInflated(mapping,mappings[i-1])){continue}next+=","}}next+=base64VLQ.encode(mapping.generatedColumn-previousGeneratedColumn);previousGeneratedColumn=mapping.generatedColumn;if(mapping.source!=null){sourceIdx=this._sources.indexOf(mapping.source);next+=base64VLQ.encode(sourceIdx-previousSource);previousSource=sourceIdx;next+=base64VLQ.encode(mapping.originalLine-1-previousOriginalLine);previousOriginalLine=mapping.originalLine-1;next+=base64VLQ.encode(mapping.originalColumn-previousOriginalColumn);previousOriginalColumn=mapping.originalColumn;if(mapping.name!=null){nameIdx=this._names.indexOf(mapping.name);next+=base64VLQ.encode(nameIdx-previousName);previousName=nameIdx}}result+=next}return result};SourceMapGenerator.prototype._generateSourcesContent=function SourceMapGenerator_generateSourcesContent(aSources,aSourceRoot){return aSources.map(function(source){if(!this._sourcesContents){return null}if(aSourceRoot!=null){source=util.relative(aSourceRoot,source)}var key=util.toSetString(source);return Object.prototype.hasOwnProperty.call(this._sourcesContents,key)?this._sourcesContents[key]:null},this)};SourceMapGenerator.prototype.toJSON=function SourceMapGenerator_toJSON(){var map={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null){map.file=this._file}if(this._sourceRoot!=null){map.sourceRoot=this._sourceRoot}if(this._sourcesContents){map.sourcesContent=this._generateSourcesContent(map.sources,map.sourceRoot)}return map};SourceMapGenerator.prototype.toString=function SourceMapGenerator_toString(){return JSON.stringify(this.toJSON())};exports.SourceMapGenerator=SourceMapGenerator},{"./array-set":218,"./base64-vlq":219,"./mapping-list":222,"./util":227}],226:[function(require,module,exports){var SourceMapGenerator=require("./source-map-generator").SourceMapGenerator;var util=require("./util");var REGEX_NEWLINE=/(\r?\n)/;var NEWLINE_CODE=10;var isSourceNode="$$$isSourceNode$$$";function SourceNode(aLine,aColumn,aSource,aChunks,aName){this.children=[];this.sourceContents={};this.line=aLine==null?null:aLine;this.column=aColumn==null?null:aColumn;this.source=aSource==null?null:aSource;this.name=aName==null?null:aName;this[isSourceNode]=true;if(aChunks!=null)this.add(aChunks)}SourceNode.fromStringWithSourceMap=function SourceNode_fromStringWithSourceMap(aGeneratedCode,aSourceMapConsumer,aRelativePath){var node=new SourceNode;var remainingLines=aGeneratedCode.split(REGEX_NEWLINE);var remainingLinesIndex=0;var shiftNextLine=function(){var lineContents=getNextLine();var newLine=getNextLine()||"";return lineContents+newLine;function getNextLine(){return remainingLinesIndex<remainingLines.length?remainingLines[remainingLinesIndex++]:undefined}};var lastGeneratedLine=1,lastGeneratedColumn=0;var lastMapping=null;aSourceMapConsumer.eachMapping(function(mapping){if(lastMapping!==null){if(lastGeneratedLine<mapping.generatedLine){addMappingWithCode(lastMapping,shiftNextLine());lastGeneratedLine++;lastGeneratedColumn=0}else{var nextLine=remainingLines[remainingLinesIndex];var code=nextLine.substr(0,mapping.generatedColumn-lastGeneratedColumn);remainingLines[remainingLinesIndex]=nextLine.substr(mapping.generatedColumn-lastGeneratedColumn);lastGeneratedColumn=mapping.generatedColumn;addMappingWithCode(lastMapping,code);lastMapping=mapping;return}}while(lastGeneratedLine<mapping.generatedLine){node.add(shiftNextLine());lastGeneratedLine++}if(lastGeneratedColumn<mapping.generatedColumn){var nextLine=remainingLines[remainingLinesIndex];node.add(nextLine.substr(0,mapping.generatedColumn));remainingLines[remainingLinesIndex]=nextLine.substr(mapping.generatedColumn);lastGeneratedColumn=mapping.generatedColumn}lastMapping=mapping},this);if(remainingLinesIndex<remainingLines.length){if(lastMapping){addMappingWithCode(lastMapping,shiftNextLine())}node.add(remainingLines.splice(remainingLinesIndex).join(""))}aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aRelativePath!=null){sourceFile=util.join(aRelativePath,sourceFile)}node.setSourceContent(sourceFile,content)}});return node;function addMappingWithCode(mapping,code){if(mapping===null||mapping.source===undefined){node.add(code)}else{var source=aRelativePath?util.join(aRelativePath,mapping.source):mapping.source;node.add(new SourceNode(mapping.originalLine,mapping.originalColumn,source,code,mapping.name))}}};SourceNode.prototype.add=function SourceNode_add(aChunk){if(Array.isArray(aChunk)){aChunk.forEach(function(chunk){this.add(chunk)},this)}else if(aChunk[isSourceNode]||typeof aChunk==="string"){if(aChunk){this.children.push(aChunk)}}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.prepend=function SourceNode_prepend(aChunk){if(Array.isArray(aChunk)){for(var i=aChunk.length-1;i>=0;i--){this.prepend(aChunk[i])}}else if(aChunk[isSourceNode]||typeof aChunk==="string"){this.children.unshift(aChunk)}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.walk=function SourceNode_walk(aFn){var chunk;for(var i=0,len=this.children.length;i<len;i++){chunk=this.children[i];if(chunk[isSourceNode]){chunk.walk(aFn)}else{if(chunk!==""){aFn(chunk,{source:this.source,line:this.line,column:this.column,name:this.name})}}}};SourceNode.prototype.join=function SourceNode_join(aSep){var newChildren;var i;var len=this.children.length;if(len>0){newChildren=[];for(i=0;i<len-1;i++){newChildren.push(this.children[i]);newChildren.push(aSep)}newChildren.push(this.children[i]);this.children=newChildren}return this};SourceNode.prototype.replaceRight=function SourceNode_replaceRight(aPattern,aReplacement){var lastChild=this.children[this.children.length-1];if(lastChild[isSourceNode]){lastChild.replaceRight(aPattern,aReplacement)}else if(typeof lastChild==="string"){this.children[this.children.length-1]=lastChild.replace(aPattern,aReplacement)}else{this.children.push("".replace(aPattern,aReplacement))}return this};SourceNode.prototype.setSourceContent=function SourceNode_setSourceContent(aSourceFile,aSourceContent){this.sourceContents[util.toSetString(aSourceFile)]=aSourceContent};SourceNode.prototype.walkSourceContents=function SourceNode_walkSourceContents(aFn){for(var i=0,len=this.children.length;i<len;i++){if(this.children[i][isSourceNode]){this.children[i].walkSourceContents(aFn)}}var sources=Object.keys(this.sourceContents);for(var i=0,len=sources.length;i<len;i++){aFn(util.fromSetString(sources[i]),this.sourceContents[sources[i]])}};SourceNode.prototype.toString=function SourceNode_toString(){var str="";this.walk(function(chunk){str+=chunk});return str};SourceNode.prototype.toStringWithSourceMap=function SourceNode_toStringWithSourceMap(aArgs){var generated={code:"",line:1,column:0};var map=new SourceMapGenerator(aArgs);var sourceMappingActive=false;var lastOriginalSource=null;var lastOriginalLine=null;var lastOriginalColumn=null;var lastOriginalName=null;this.walk(function(chunk,original){generated.code+=chunk;if(original.source!==null&&original.line!==null&&original.column!==null){if(lastOriginalSource!==original.source||lastOriginalLine!==original.line||lastOriginalColumn!==original.column||lastOriginalName!==original.name){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}lastOriginalSource=original.source;lastOriginalLine=original.line;lastOriginalColumn=original.column;lastOriginalName=original.name;sourceMappingActive=true}else if(sourceMappingActive){map.addMapping({generated:{line:generated.line,column:generated.column}});lastOriginalSource=null;sourceMappingActive=false}for(var idx=0,length=chunk.length;idx<length;idx++){if(chunk.charCodeAt(idx)===NEWLINE_CODE){generated.line++;generated.column=0;if(idx+1===length){lastOriginalSource=null;sourceMappingActive=false}else if(sourceMappingActive){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}}else{generated.column++}}});this.walkSourceContents(function(sourceFile,sourceContent){map.setSourceContent(sourceFile,sourceContent)});return{code:generated.code,map:map}};exports.SourceNode=SourceNode},{"./source-map-generator":225,"./util":227}],227:[function(require,module,exports){function getArg(aArgs,aName,aDefaultValue){if(aName in aArgs){return aArgs[aName]}else if(arguments.length===3){return aDefaultValue}else{throw new Error('"'+aName+'" is a required argument.')}}exports.getArg=getArg;var urlRegexp=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;var dataUrlRegexp=/^data:.+\,.+$/;function urlParse(aUrl){var match=aUrl.match(urlRegexp);if(!match){return null}return{scheme:match[1],auth:match[2],host:match[3],port:match[4],path:match[5]}}exports.urlParse=urlParse;function urlGenerate(aParsedUrl){var url="";if(aParsedUrl.scheme){url+=aParsedUrl.scheme+":"}url+="//";if(aParsedUrl.auth){url+=aParsedUrl.auth+"@"}if(aParsedUrl.host){url+=aParsedUrl.host}if(aParsedUrl.port){url+=":"+aParsedUrl.port}if(aParsedUrl.path){url+=aParsedUrl.path}return url}exports.urlGenerate=urlGenerate;function normalize(aPath){var path=aPath;var url=urlParse(aPath);if(url){if(!url.path){return aPath}path=url.path}var isAbsolute=exports.isAbsolute(path);var parts=path.split(/\/+/);for(var part,up=0,i=parts.length-1;i>=0;i--){part=parts[i];if(part==="."){parts.splice(i,1)}else if(part===".."){up++}else if(up>0){if(part===""){parts.splice(i+1,up);up=0}else{parts.splice(i,2);up--}}}path=parts.join("/");if(path===""){path=isAbsolute?"/":"."}if(url){url.path=path;return urlGenerate(url)}return path}exports.normalize=normalize;function join(aRoot,aPath){if(aRoot===""){aRoot="."}if(aPath===""){aPath="."}var aPathUrl=urlParse(aPath);var aRootUrl=urlParse(aRoot);if(aRootUrl){aRoot=aRootUrl.path||"/"}if(aPathUrl&&!aPathUrl.scheme){if(aRootUrl){aPathUrl.scheme=aRootUrl.scheme}return urlGenerate(aPathUrl)}if(aPathUrl||aPath.match(dataUrlRegexp)){return aPath}if(aRootUrl&&!aRootUrl.host&&!aRootUrl.path){aRootUrl.host=aPath;return urlGenerate(aRootUrl)}var joined=aPath.charAt(0)==="/"?aPath:normalize(aRoot.replace(/\/+$/,"")+"/"+aPath);if(aRootUrl){aRootUrl.path=joined;return urlGenerate(aRootUrl)}return joined}exports.join=join;exports.isAbsolute=function(aPath){return aPath.charAt(0)==="/"||!!aPath.match(urlRegexp)};function relative(aRoot,aPath){if(aRoot===""){aRoot="."}aRoot=aRoot.replace(/\/$/,"");var level=0;while(aPath.indexOf(aRoot+"/")!==0){var index=aRoot.lastIndexOf("/");if(index<0){return aPath}aRoot=aRoot.slice(0,index);if(aRoot.match(/^([^\/]+:\/)?\/*$/)){return aPath}++level}return Array(level+1).join("../")+aPath.substr(aRoot.length+1)}exports.relative=relative;var supportsNullProto=function(){var obj=Object.create(null);return!("__proto__"in obj)}();function identity(s){return s}function toSetString(aStr){if(isProtoString(aStr)){return"$"+aStr}return aStr}exports.toSetString=supportsNullProto?identity:toSetString;function fromSetString(aStr){if(isProtoString(aStr)){return aStr.slice(1)}return aStr}exports.fromSetString=supportsNullProto?identity:fromSetString;function isProtoString(s){if(!s){return false}var length=s.length;if(length<9){return false}if(s.charCodeAt(length-1)!==95||s.charCodeAt(length-2)!==95||s.charCodeAt(length-3)!==111||s.charCodeAt(length-4)!==116||s.charCodeAt(length-5)!==111||s.charCodeAt(length-6)!==114||s.charCodeAt(length-7)!==112||s.charCodeAt(length-8)!==95||s.charCodeAt(length-9)!==95){return false}for(var i=length-10;i>=0;i--){if(s.charCodeAt(i)!==36){return false}}return true}function compareByOriginalPositions(mappingA,mappingB,onlyCompareOriginal){var cmp=mappingA.source-mappingB.source;if(cmp!==0){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp!==0){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp!==0||onlyCompareOriginal){return cmp}cmp=mappingA.generatedColumn-mappingB.generatedColumn;if(cmp!==0){return cmp}cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp!==0){return cmp}return mappingA.name-mappingB.name}exports.compareByOriginalPositions=compareByOriginalPositions;function compareByGeneratedPositionsDeflated(mappingA,mappingB,onlyCompareGenerated){var cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp!==0){return cmp}cmp=mappingA.generatedColumn-mappingB.generatedColumn;if(cmp!==0||onlyCompareGenerated){return cmp}cmp=mappingA.source-mappingB.source;if(cmp!==0){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp!==0){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp!==0){return cmp}return mappingA.name-mappingB.name}exports.compareByGeneratedPositionsDeflated=compareByGeneratedPositionsDeflated;function strcmp(aStr1,aStr2){if(aStr1===aStr2){return 0}if(aStr1>aStr2){return 1}return-1}function compareByGeneratedPositionsInflated(mappingA,mappingB){var cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp!==0){return cmp}cmp=mappingA.generatedColumn-mappingB.generatedColumn;if(cmp!==0){return cmp}cmp=strcmp(mappingA.source,mappingB.source);if(cmp!==0){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp!==0){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp!==0){return cmp}return strcmp(mappingA.name,mappingB.name)}exports.compareByGeneratedPositionsInflated=compareByGeneratedPositionsInflated},{}],228:[function(require,module,exports){exports.SourceMapGenerator=require("./lib/source-map-generator").SourceMapGenerator;exports.SourceMapConsumer=require("./lib/source-map-consumer").SourceMapConsumer;exports.SourceNode=require("./lib/source-node").SourceNode},{"./lib/source-map-consumer":224,"./lib/source-map-generator":225,"./lib/source-node":226}],229:[function(require,module,exports){module.exports=Stream;var EE=require("events").EventEmitter;var inherits=require("inherits");inherits(Stream,EE);Stream.Readable=require("readable-stream/readable.js");Stream.Writable=require("readable-stream/writable.js");Stream.Duplex=require("readable-stream/duplex.js");Stream.Transform=require("readable-stream/transform.js");Stream.PassThrough=require("readable-stream/passthrough.js");Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},{events:110,inherits:145,"readable-stream/duplex.js":193,"readable-stream/passthrough.js":204,"readable-stream/readable.js":205,"readable-stream/transform.js":206,"readable-stream/writable.js":207}],230:[function(require,module,exports){(function(global){(function(){var ClientRequest=require("./lib/request");var response=require("./lib/response");var extend=require("xtend");var statusCodes=require("builtin-status-codes");var url=require("url");var http=exports;http.request=function(opts,cb){if(typeof opts==="string")opts=url.parse(opts);else opts=extend(opts);var defaultProtocol=global.location.protocol.search(/^https?:$/)===-1?"http:":"";var protocol=opts.protocol||defaultProtocol;var host=opts.hostname||opts.host;var port=opts.port;var path=opts.path||"/";if(host&&host.indexOf(":")!==-1)host="["+host+"]";opts.url=(host?protocol+"//"+host:"")+(port?":"+port:"")+path;opts.method=(opts.method||"GET").toUpperCase();opts.headers=opts.headers||{};var req=new ClientRequest(opts);if(cb)req.on("response",cb);return req};http.get=function get(opts,cb){var req=http.request(opts,cb);req.end();return req};http.ClientRequest=ClientRequest;http.IncomingMessage=response.IncomingMessage;http.Agent=function(){};http.Agent.defaultMaxSockets=4;http.globalAgent=new http.Agent;http.STATUS_CODES=statusCodes;http.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./lib/request":232,"./lib/response":233,"builtin-status-codes":72,url:238,xtend:245}],231:[function(require,module,exports){(function(global){(function(){exports.fetch=isFunction(global.fetch)&&isFunction(global.ReadableStream);exports.writableStream=isFunction(global.WritableStream);exports.abortController=isFunction(global.AbortController);exports.blobConstructor=false;try{new Blob([new ArrayBuffer(1)]);exports.blobConstructor=true}catch(e){}var xhr;function getXHR(){if(xhr!==undefined)return xhr;if(global.XMLHttpRequest){xhr=new global.XMLHttpRequest;try{xhr.open("GET",global.XDomainRequest?"/":"https://example.com")}catch(e){xhr=null}}else{xhr=null}return xhr}function checkTypeSupport(type){var xhr=getXHR();if(!xhr)return false;try{xhr.responseType=type;return xhr.responseType===type}catch(e){}return false}var haveArrayBuffer=typeof global.ArrayBuffer!=="undefined";var haveSlice=haveArrayBuffer&&isFunction(global.ArrayBuffer.prototype.slice);exports.arraybuffer=exports.fetch||haveArrayBuffer&&checkTypeSupport("arraybuffer");exports.msstream=!exports.fetch&&haveSlice&&checkTypeSupport("ms-stream");exports.mozchunkedarraybuffer=!exports.fetch&&haveArrayBuffer&&checkTypeSupport("moz-chunked-arraybuffer");exports.overrideMimeType=exports.fetch||(getXHR()?isFunction(getXHR().overrideMimeType):false);exports.vbArray=isFunction(global.VBArray);function isFunction(value){return typeof value==="function"}xhr=null}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],232:[function(require,module,exports){(function(process,global,Buffer){(function(){var capability=require("./capability");var inherits=require("inherits");var response=require("./response");var stream=require("readable-stream");var toArrayBuffer=require("to-arraybuffer");var IncomingMessage=response.IncomingMessage;var rStates=response.readyStates;function decideMode(preferBinary,useFetch){if(capability.fetch&&useFetch){return"fetch"}else if(capability.mozchunkedarraybuffer){return"moz-chunked-arraybuffer"}else if(capability.msstream){return"ms-stream"}else if(capability.arraybuffer&&preferBinary){return"arraybuffer"}else if(capability.vbArray&&preferBinary){return"text:vbarray"}else{return"text"}}var ClientRequest=module.exports=function(opts){var self=this;stream.Writable.call(self);self._opts=opts;self._body=[];self._headers={};if(opts.auth)self.setHeader("Authorization","Basic "+new Buffer(opts.auth).toString("base64"));Object.keys(opts.headers).forEach(function(name){self.setHeader(name,opts.headers[name])});var preferBinary;var useFetch=true;if(opts.mode==="disable-fetch"||"requestTimeout"in opts&&!capability.abortController){useFetch=false;preferBinary=true}else if(opts.mode==="prefer-streaming"){preferBinary=false}else if(opts.mode==="allow-wrong-content-type"){preferBinary=!capability.overrideMimeType}else if(!opts.mode||opts.mode==="default"||opts.mode==="prefer-fast"){preferBinary=true}else{throw new Error("Invalid value for opts.mode")}self._mode=decideMode(preferBinary,useFetch);self._fetchTimer=null;self.on("finish",function(){self._onFinish()})};inherits(ClientRequest,stream.Writable);ClientRequest.prototype.setHeader=function(name,value){var self=this;var lowerName=name.toLowerCase();if(unsafeHeaders.indexOf(lowerName)!==-1)return;self._headers[lowerName]={name:name,value:value}};ClientRequest.prototype.getHeader=function(name){var header=this._headers[name.toLowerCase()];if(header)return header.value;return null};ClientRequest.prototype.removeHeader=function(name){var self=this;delete self._headers[name.toLowerCase()]};ClientRequest.prototype._onFinish=function(){var self=this;if(self._destroyed)return;var opts=self._opts;var headersObj=self._headers;var body=null;if(opts.method!=="GET"&&opts.method!=="HEAD"){if(capability.arraybuffer){body=toArrayBuffer(Buffer.concat(self._body))}else if(capability.blobConstructor){body=new global.Blob(self._body.map(function(buffer){return toArrayBuffer(buffer)}),{type:(headersObj["content-type"]||{}).value||""})}else{body=Buffer.concat(self._body).toString()}}var headersList=[];Object.keys(headersObj).forEach(function(keyName){var name=headersObj[keyName].name;var value=headersObj[keyName].value;if(Array.isArray(value)){value.forEach(function(v){headersList.push([name,v])})}else{headersList.push([name,value])}});if(self._mode==="fetch"){var signal=null;var fetchTimer=null;if(capability.abortController){var controller=new AbortController;signal=controller.signal;self._fetchAbortController=controller;if("requestTimeout"in opts&&opts.requestTimeout!==0){self._fetchTimer=global.setTimeout(function(){self.emit("requestTimeout");if(self._fetchAbortController)self._fetchAbortController.abort()},opts.requestTimeout)}}global.fetch(self._opts.url,{method:self._opts.method,headers:headersList,body:body||undefined,mode:"cors",credentials:opts.withCredentials?"include":"same-origin",signal:signal}).then(function(response){self._fetchResponse=response;self._connect()},function(reason){global.clearTimeout(self._fetchTimer);if(!self._destroyed)self.emit("error",reason)})}else{var xhr=self._xhr=new global.XMLHttpRequest;try{xhr.open(self._opts.method,self._opts.url,true)}catch(err){process.nextTick(function(){self.emit("error",err)});return}if("responseType"in xhr)xhr.responseType=self._mode.split(":")[0];if("withCredentials"in xhr)xhr.withCredentials=!!opts.withCredentials;if(self._mode==="text"&&"overrideMimeType"in xhr)xhr.overrideMimeType("text/plain; charset=x-user-defined");if("requestTimeout"in opts){xhr.timeout=opts.requestTimeout;xhr.ontimeout=function(){self.emit("requestTimeout")}}headersList.forEach(function(header){xhr.setRequestHeader(header[0],header[1])});self._response=null;xhr.onreadystatechange=function(){switch(xhr.readyState){case rStates.LOADING:case rStates.DONE:self._onXHRProgress();break}};if(self._mode==="moz-chunked-arraybuffer"){xhr.onprogress=function(){self._onXHRProgress()}}xhr.onerror=function(){if(self._destroyed)return;self.emit("error",new Error("XHR error"))};try{xhr.send(body)}catch(err){process.nextTick(function(){self.emit("error",err)});return}}};function statusValid(xhr){try{var status=xhr.status;return status!==null&&status!==0}catch(e){return false}}ClientRequest.prototype._onXHRProgress=function(){var self=this;if(!statusValid(self._xhr)||self._destroyed)return;if(!self._response)self._connect();self._response._onXHRProgress()};ClientRequest.prototype._connect=function(){var self=this;if(self._destroyed)return;self._response=new IncomingMessage(self._xhr,self._fetchResponse,self._mode,self._fetchTimer);self._response.on("error",function(err){self.emit("error",err)});self.emit("response",self._response)};ClientRequest.prototype._write=function(chunk,encoding,cb){var self=this;self._body.push(chunk);cb()};ClientRequest.prototype.abort=ClientRequest.prototype.destroy=function(){var self=this;self._destroyed=true;global.clearTimeout(self._fetchTimer);if(self._response)self._response._destroyed=true;if(self._xhr)self._xhr.abort();else if(self._fetchAbortController)self._fetchAbortController.abort()};ClientRequest.prototype.end=function(data,encoding,cb){var self=this;if(typeof data==="function"){cb=data;data=undefined}stream.Writable.prototype.end.call(self,data,encoding,cb)};ClientRequest.prototype.flushHeaders=function(){};ClientRequest.prototype.setTimeout=function(){};ClientRequest.prototype.setNoDelay=function(){};ClientRequest.prototype.setSocketKeepAlive=function(){};var unsafeHeaders=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]}).call(this)}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{"./capability":231,"./response":233,_process:179,buffer:71,inherits:145,"readable-stream":205,"to-arraybuffer":237}],233:[function(require,module,exports){(function(process,global,Buffer){(function(){var capability=require("./capability");var inherits=require("inherits");var stream=require("readable-stream");var rStates=exports.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4};var IncomingMessage=exports.IncomingMessage=function(xhr,response,mode,fetchTimer){var self=this;stream.Readable.call(self);self._mode=mode;self.headers={};self.rawHeaders=[];self.trailers={};self.rawTrailers=[];self.on("end",function(){process.nextTick(function(){self.emit("close")})});if(mode==="fetch"){self._fetchResponse=response;self.url=response.url;self.statusCode=response.status;self.statusMessage=response.statusText;response.headers.forEach(function(header,key){self.headers[key.toLowerCase()]=header;self.rawHeaders.push(key,header)});if(capability.writableStream){var writable=new WritableStream({write:function(chunk){return new Promise(function(resolve,reject){if(self._destroyed){reject()}else if(self.push(new Buffer(chunk))){resolve()}else{self._resumeFetch=resolve}})},close:function(){global.clearTimeout(fetchTimer);if(!self._destroyed)self.push(null)},abort:function(err){if(!self._destroyed)self.emit("error",err)}});try{response.body.pipeTo(writable).catch(function(err){global.clearTimeout(fetchTimer);if(!self._destroyed)self.emit("error",err)});return}catch(e){}}var reader=response.body.getReader();function read(){reader.read().then(function(result){if(self._destroyed)return;if(result.done){global.clearTimeout(fetchTimer);self.push(null);return}self.push(new Buffer(result.value));read()}).catch(function(err){global.clearTimeout(fetchTimer);if(!self._destroyed)self.emit("error",err)})}read()}else{self._xhr=xhr;self._pos=0;self.url=xhr.responseURL;self.statusCode=xhr.status;self.statusMessage=xhr.statusText;var headers=xhr.getAllResponseHeaders().split(/\r?\n/);headers.forEach(function(header){var matches=header.match(/^([^:]+):\s*(.*)/);if(matches){var key=matches[1].toLowerCase();if(key==="set-cookie"){if(self.headers[key]===undefined){self.headers[key]=[]}self.headers[key].push(matches[2])}else if(self.headers[key]!==undefined){self.headers[key]+=", "+matches[2]}else{self.headers[key]=matches[2]}self.rawHeaders.push(matches[1],matches[2])}});self._charset="x-user-defined";if(!capability.overrideMimeType){var mimeType=self.rawHeaders["mime-type"];if(mimeType){var charsetMatch=mimeType.match(/;\s*charset=([^;])(;|$)/);if(charsetMatch){self._charset=charsetMatch[1].toLowerCase()}}if(!self._charset)self._charset="utf-8"}}};inherits(IncomingMessage,stream.Readable);IncomingMessage.prototype._read=function(){var self=this;var resolve=self._resumeFetch;if(resolve){self._resumeFetch=null;resolve()}};IncomingMessage.prototype._onXHRProgress=function(){var self=this;var xhr=self._xhr;var response=null;switch(self._mode){case"text:vbarray":if(xhr.readyState!==rStates.DONE)break;try{response=new global.VBArray(xhr.responseBody).toArray()}catch(e){}if(response!==null){self.push(new Buffer(response));break}case"text":try{response=xhr.responseText}catch(e){self._mode="text:vbarray";break}if(response.length>self._pos){var newData=response.substr(self._pos);if(self._charset==="x-user-defined"){var buffer=new Buffer(newData.length);for(var i=0;i<newData.length;i++)buffer[i]=newData.charCodeAt(i)&255;self.push(buffer)}else{self.push(newData,self._charset)}self._pos=response.length}break;case"arraybuffer":if(xhr.readyState!==rStates.DONE||!xhr.response)break;response=xhr.response;self.push(new Buffer(new Uint8Array(response)));break;case"moz-chunked-arraybuffer":response=xhr.response
23
- ;if(xhr.readyState!==rStates.LOADING||!response)break;self.push(new Buffer(new Uint8Array(response)));break;case"ms-stream":response=xhr.response;if(xhr.readyState!==rStates.LOADING)break;var reader=new global.MSStreamReader;reader.onprogress=function(){if(reader.result.byteLength>self._pos){self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos))));self._pos=reader.result.byteLength}};reader.onload=function(){self.push(null)};reader.readAsArrayBuffer(response);break}if(self._xhr.readyState===rStates.DONE&&self._mode!=="ms-stream"){self.push(null)}}}).call(this)}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{"./capability":231,_process:179,buffer:71,inherits:145,"readable-stream":205}],234:[function(require,module,exports){"use strict";var Buffer=require("safe-buffer").Buffer;var isEncoding=Buffer.isEncoding||function(encoding){encoding=""+encoding;switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function _normalizeEncoding(enc){if(!enc)return"utf8";var retried;while(true){switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase();retried=true}}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if(typeof nenc!=="string"&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}exports.StringDecoder=StringDecoder;function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text;this.end=utf16End;nb=4;break;case"utf8":this.fillLast=utf8FillLast;nb=4;break;case"base64":this.text=base64Text;this.end=base64End;nb=3;break;default:this.write=simpleWrite;this.end=simpleEnd;return}this.lastNeed=0;this.lastTotal=0;this.lastChar=Buffer.allocUnsafe(nb)}StringDecoder.prototype.write=function(buf){if(buf.length===0)return"";var r;var i;if(this.lastNeed){r=this.fillLast(buf);if(r===undefined)return"";i=this.lastNeed;this.lastNeed=0}else{i=0}if(i<buf.length)return r?r+this.text(buf,i):this.text(buf,i);return r||""};StringDecoder.prototype.end=utf8End;StringDecoder.prototype.text=utf8Text;StringDecoder.prototype.fillLast=function(buf){if(this.lastNeed<=buf.length){buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,buf.length);this.lastNeed-=buf.length};function utf8CheckByte(byte){if(byte<=127)return 0;else if(byte>>5===6)return 2;else if(byte>>4===14)return 3;else if(byte>>3===30)return 4;return-1}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j<i)return 0;var nb=utf8CheckByte(buf[j]);if(nb>=0){if(nb>0)self.lastNeed=nb-1;return nb}if(--j<i)return 0;nb=utf8CheckByte(buf[j]);if(nb>=0){if(nb>0)self.lastNeed=nb-2;return nb}if(--j<i)return 0;nb=utf8CheckByte(buf[j]);if(nb>=0){if(nb>0){if(nb===2)nb=0;else self.lastNeed=nb-3}return nb}return 0}function utf8CheckExtraBytes(self,buf,p){if((buf[0]&192)!==128){self.lastNeed=0;return"�".repeat(p)}if(self.lastNeed>1&&buf.length>1){if((buf[1]&192)!==128){self.lastNeed=1;return"�".repeat(p+1)}if(self.lastNeed>2&&buf.length>2){if((buf[2]&192)!==128){self.lastNeed=2;return"�".repeat(p+2)}}}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed;var r=utf8CheckExtraBytes(this,buf,p);if(r!==undefined)return r;if(this.lastNeed<=buf.length){buf.copy(this.lastChar,p,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}buf.copy(this.lastChar,p,0,buf.length);this.lastNeed-=buf.length}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);buf.copy(this.lastChar,0,end);return buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed)return r+"�".repeat(this.lastTotal-this.lastNeed);return r}function utf16Text(buf,i){if((buf.length-i)%2===0){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(c>=55296&&c<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=buf[buf.length-2];this.lastChar[1]=buf[buf.length-1];return r.slice(0,-1)}}return r}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=buf[buf.length-1];return buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;if(n===0)return buf.toString("base64",i);this.lastNeed=3-n;this.lastTotal=3;if(n===1){this.lastChar[0]=buf[buf.length-1]}else{this.lastChar[0]=buf[buf.length-2];this.lastChar[1]=buf[buf.length-1]}return buf.toString("base64",i,buf.length-n)}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed)return r+this.lastChar.toString("base64",0,3-this.lastNeed);return r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}},{"safe-buffer":235}],235:[function(require,module,exports){arguments[4][202][0].apply(exports,arguments)},{buffer:71,dup:202}],236:[function(require,module,exports){(function(setImmediate,clearImmediate){(function(){var nextTick=require("process/browser.js").nextTick;var apply=Function.prototype.apply;var slice=Array.prototype.slice;var immediateIds={};var nextImmediateId=0;exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)};exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)};exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()};function Timeout(id,clearFn){this._id=id;this._clearFn=clearFn}Timeout.prototype.unref=Timeout.prototype.ref=function(){};Timeout.prototype.close=function(){this._clearFn.call(window,this._id)};exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId);item._idleTimeout=msecs};exports.unenroll=function(item){clearTimeout(item._idleTimeoutId);item._idleTimeout=-1};exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;if(msecs>=0){item._idleTimeoutId=setTimeout(function onTimeout(){if(item._onTimeout)item._onTimeout()},msecs)}};exports.setImmediate=typeof setImmediate==="function"?setImmediate:function(fn){var id=nextImmediateId++;var args=arguments.length<2?false:slice.call(arguments,1);immediateIds[id]=true;nextTick(function onNextTick(){if(immediateIds[id]){if(args){fn.apply(null,args)}else{fn.call(null)}exports.clearImmediate(id)}});return id};exports.clearImmediate=typeof clearImmediate==="function"?clearImmediate:function(id){delete immediateIds[id]}}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":179,timers:236}],237:[function(require,module,exports){var Buffer=require("buffer").Buffer;module.exports=function(buf){if(buf instanceof Uint8Array){if(buf.byteOffset===0&&buf.byteLength===buf.buffer.byteLength){return buf.buffer}else if(typeof buf.buffer.slice==="function"){return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}}if(Buffer.isBuffer(buf)){var arrayCopy=new Uint8Array(buf.length);var len=buf.length;for(var i=0;i<len;i++){arrayCopy[i]=buf[i]}return arrayCopy.buffer}else{throw new Error("Argument must be a Buffer")}}},{buffer:71}],238:[function(require,module,exports){"use strict";var punycode=require("punycode");var util=require("./util");exports.parse=urlParse;exports.resolve=urlResolve;exports.resolveObject=urlResolveObject;exports.format=urlFormat;exports.Url=Url;function Url(){this.protocol=null;this.slashes=null;this.auth=null;this.host=null;this.port=null;this.hostname=null;this.hash=null;this.search=null;this.query=null;this.pathname=null;this.path=null;this.href=null}var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,simplePathPattern=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,delims=["<",">",'"',"`"," ","\r","\n","\t"],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:true,"javascript:":true},hostlessProtocol={javascript:true,"javascript:":true},slashedProtocol={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},querystring=require("querystring");function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&util.isObject(url)&&url instanceof Url)return url;var u=new Url;u.parse(url,parseQueryString,slashesDenoteHost);return u}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url)){throw new TypeError("Parameter 'url' must be a string, not "+typeof url)}var queryIndex=url.indexOf("?"),splitter=queryIndex!==-1&&queryIndex<url.indexOf("#")?"?":"#",uSplit=url.split(splitter),slashRegex=/\\/g;uSplit[0]=uSplit[0].replace(slashRegex,"/");url=uSplit.join(splitter);var rest=url;rest=rest.trim();if(!slashesDenoteHost&&url.split("#").length===1){var simplePath=simplePathPattern.exec(rest);if(simplePath){this.path=rest;this.href=rest;this.pathname=simplePath[1];if(simplePath[2]){this.search=simplePath[2];if(parseQueryString){this.query=querystring.parse(this.search.substr(1))}else{this.query=this.search.substr(1)}}else if(parseQueryString){this.search="";this.query={}}return this}}var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto;rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes=rest.substr(0,2)==="//";if(slashes&&!(proto&&hostlessProtocol[proto])){rest=rest.substr(2);this.slashes=true}}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){var hostEnd=-1;for(var i=0;i<hostEndingChars.length;i++){var hec=rest.indexOf(hostEndingChars[i]);if(hec!==-1&&(hostEnd===-1||hec<hostEnd))hostEnd=hec}var auth,atSign;if(hostEnd===-1){atSign=rest.lastIndexOf("@")}else{atSign=rest.lastIndexOf("@",hostEnd)}if(atSign!==-1){auth=rest.slice(0,atSign);rest=rest.slice(atSign+1);this.auth=decodeURIComponent(auth)}hostEnd=-1;for(var i=0;i<nonHostChars.length;i++){var hec=rest.indexOf(nonHostChars[i]);if(hec!==-1&&(hostEnd===-1||hec<hostEnd))hostEnd=hec}if(hostEnd===-1)hostEnd=rest.length;this.host=rest.slice(0,hostEnd);rest=rest.slice(hostEnd);this.parseHost();this.hostname=this.hostname||"";var ipv6Hostname=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!ipv6Hostname){var hostparts=this.hostname.split(/\./);for(var i=0,l=hostparts.length;i<l;i++){var part=hostparts[i];if(!part)continue;if(!part.match(hostnamePartPattern)){var newpart="";for(var j=0,k=part.length;j<k;j++){if(part.charCodeAt(j)>127){newpart+="x"}else{newpart+=part[j]}}if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i);var notHost=hostparts.slice(i+1);var bit=part.match(hostnamePartStart);if(bit){validParts.push(bit[1]);notHost.unshift(bit[2])}if(notHost.length){rest="/"+notHost.join(".")+rest}this.hostname=validParts.join(".");break}}}}if(this.hostname.length>hostnameMaxLen){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!ipv6Hostname){this.hostname=punycode.toASCII(this.hostname)}var p=this.port?":"+this.port:"";var h=this.hostname||"";this.host=h+p;this.href+=this.host;if(ipv6Hostname){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(rest[0]!=="/"){rest="/"+rest}}}if(!unsafeProtocol[lowerProto]){for(var i=0,l=autoEscape.length;i<l;i++){var ae=autoEscape[i];if(rest.indexOf(ae)===-1)continue;var esc=encodeURIComponent(ae);if(esc===ae){esc=escape(ae)}rest=rest.split(ae).join(esc)}}var hash=rest.indexOf("#");if(hash!==-1){this.hash=rest.substr(hash);rest=rest.slice(0,hash)}var qm=rest.indexOf("?");if(qm!==-1){this.search=rest.substr(qm);this.query=rest.substr(qm+1);if(parseQueryString){this.query=querystring.parse(this.query)}rest=rest.slice(0,qm)}else if(parseQueryString){this.search="";this.query={}}if(rest)this.pathname=rest;if(slashedProtocol[lowerProto]&&this.hostname&&!this.pathname){this.pathname="/"}if(this.pathname||this.search){var p=this.pathname||"";var s=this.search||"";this.path=p+s}this.href=this.format();return this};function urlFormat(obj){if(util.isString(obj))obj=urlParse(obj);if(!(obj instanceof Url))return Url.prototype.format.call(obj);return obj.format()}Url.prototype.format=function(){var auth=this.auth||"";if(auth){auth=encodeURIComponent(auth);auth=auth.replace(/%3A/i,":");auth+="@"}var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",host=false,query="";if(this.host){host=auth+this.host}else if(this.hostname){host=auth+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]");if(this.port){host+=":"+this.port}}if(this.query&&util.isObject(this.query)&&Object.keys(this.query).length){query=querystring.stringify(this.query)}var search=this.search||query&&"?"+query||"";if(protocol&&protocol.substr(-1)!==":")protocol+=":";if(this.slashes||(!protocol||slashedProtocol[protocol])&&host!==false){host="//"+(host||"");if(pathname&&pathname.charAt(0)!=="/")pathname="/"+pathname}else if(!host){host=""}if(hash&&hash.charAt(0)!=="#")hash="#"+hash;if(search&&search.charAt(0)!=="?")search="?"+search;pathname=pathname.replace(/[?#]/g,function(match){return encodeURIComponent(match)});search=search.replace("#","%23");return protocol+host+pathname+search+hash};function urlResolve(source,relative){return urlParse(source,false,true).resolve(relative)}Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,false,true)).format()};function urlResolveObject(source,relative){if(!source)return relative;return urlParse(source,false,true).resolveObject(relative)}Url.prototype.resolveObject=function(relative){if(util.isString(relative)){var rel=new Url;rel.parse(relative,false,true);relative=rel}var result=new Url;var tkeys=Object.keys(this);for(var tk=0;tk<tkeys.length;tk++){var tkey=tkeys[tk];result[tkey]=this[tkey]}result.hash=relative.hash;if(relative.href===""){result.href=result.format();return result}if(relative.slashes&&!relative.protocol){var rkeys=Object.keys(relative);for(var rk=0;rk<rkeys.length;rk++){var rkey=rkeys[rk];if(rkey!=="protocol")result[rkey]=relative[rkey]}if(slashedProtocol[result.protocol]&&result.hostname&&!result.pathname){result.path=result.pathname="/"}result.href=result.format();return result}if(relative.protocol&&relative.protocol!==result.protocol){if(!slashedProtocol[relative.protocol]){var keys=Object.keys(relative);for(var v=0;v<keys.length;v++){var k=keys[v];result[k]=relative[k]}result.href=result.format();return result}result.protocol=relative.protocol;if(!relative.host&&!hostlessProtocol[relative.protocol]){var relPath=(relative.pathname||"").split("/");while(relPath.length&&!(relative.host=relPath.shift()));if(!relative.host)relative.host="";if(!relative.hostname)relative.hostname="";if(relPath[0]!=="")relPath.unshift("");if(relPath.length<2)relPath.unshift("");result.pathname=relPath.join("/")}else{result.pathname=relative.pathname}result.search=relative.search;result.query=relative.query;result.host=relative.host||"";result.auth=relative.auth;result.hostname=relative.hostname||relative.host;result.port=relative.port;if(result.pathname||result.search){var p=result.pathname||"";var s=result.search||"";result.path=p+s}result.slashes=result.slashes||relative.slashes;result.href=result.format();return result}var isSourceAbs=result.pathname&&result.pathname.charAt(0)==="/",isRelAbs=relative.host||relative.pathname&&relative.pathname.charAt(0)==="/",mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic){result.hostname="";result.port=null;if(result.host){if(srcPath[0]==="")srcPath[0]=result.host;else srcPath.unshift(result.host)}result.host="";if(relative.protocol){relative.hostname=null;relative.port=null;if(relative.host){if(relPath[0]==="")relPath[0]=relative.host;else relPath.unshift(relative.host)}relative.host=null}mustEndAbs=mustEndAbs&&(relPath[0]===""||srcPath[0]==="")}if(isRelAbs){result.host=relative.host||relative.host===""?relative.host:result.host;result.hostname=relative.hostname||relative.hostname===""?relative.hostname:result.hostname;result.search=relative.search;result.query=relative.query;srcPath=relPath}else if(relPath.length){if(!srcPath)srcPath=[];srcPath.pop();srcPath=srcPath.concat(relPath);result.search=relative.search;result.query=relative.query}else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift()}}result.search=relative.search;result.query=relative.query;if(!util.isNull(result.pathname)||!util.isNull(result.search)){result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")}result.href=result.format();return result}if(!srcPath.length){result.pathname=null;if(result.search){result.path="/"+result.search}else{result.path=null}result.href=result.format();return result}var last=srcPath.slice(-1)[0];var hasTrailingSlash=(result.host||relative.host||srcPath.length>1)&&(last==="."||last==="..")||last==="";var up=0;for(var i=srcPath.length;i>=0;i--){last=srcPath[i];if(last==="."){srcPath.splice(i,1)}else if(last===".."){srcPath.splice(i,1);up++}else if(up){srcPath.splice(i,1);up--}}if(!mustEndAbs&&!removeAllDots){for(;up--;up){srcPath.unshift("..")}}if(mustEndAbs&&srcPath[0]!==""&&(!srcPath[0]||srcPath[0].charAt(0)!=="/")){srcPath.unshift("")}if(hasTrailingSlash&&srcPath.join("/").substr(-1)!=="/"){srcPath.push("")}var isAbsolute=srcPath[0]===""||srcPath[0]&&srcPath[0].charAt(0)==="/";if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift()}}mustEndAbs=mustEndAbs||result.host&&srcPath.length;if(mustEndAbs&&!isAbsolute){srcPath.unshift("")}if(!srcPath.length){result.pathname=null;result.path=null}else{result.pathname=srcPath.join("/")}if(!util.isNull(result.pathname)||!util.isNull(result.search)){result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")}result.auth=relative.auth||result.auth;result.slashes=result.slashes||relative.slashes;result.href=result.format();return result};Url.prototype.parseHost=function(){var host=this.host;var port=portPattern.exec(host);if(port){port=port[0];if(port!==":"){this.port=port.substr(1)}host=host.substr(0,host.length-port.length)}if(host)this.hostname=host}},{"./util":239,punycode:187,querystring:190}],239:[function(require,module,exports){"use strict";module.exports={isString:function(arg){return typeof arg==="string"},isObject:function(arg){return typeof arg==="object"&&arg!==null},isNull:function(arg){return arg===null},isNullOrUndefined:function(arg){return arg==null}}},{}],240:[function(require,module,exports){(function(global){(function(){module.exports=deprecate;function deprecate(fn,msg){if(config("noDeprecation")){return fn}var warned=false;function deprecated(){if(!warned){if(config("throwDeprecation")){throw new Error(msg)}else if(config("traceDeprecation")){console.trace(msg)}else{console.warn(msg)}warned=true}return fn.apply(this,arguments)}return deprecated}function config(name){try{if(!global.localStorage)return false}catch(_){return false}var val=global.localStorage[name];if(null==val)return false;return String(val).toLowerCase()==="true"}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],241:[function(require,module,exports){arguments[4][17][0].apply(exports,arguments)},{dup:17}],242:[function(require,module,exports){arguments[4][18][0].apply(exports,arguments)},{dup:18}],243:[function(require,module,exports){arguments[4][19][0].apply(exports,arguments)},{"./support/isBuffer":242,_process:179,dup:19,inherits:241}],244:[function(require,module,exports){var indexOf=require("indexof");var Object_keys=function(obj){if(Object.keys)return Object.keys(obj);else{var res=[];for(var key in obj)res.push(key);return res}};var forEach=function(xs,fn){if(xs.forEach)return xs.forEach(fn);else for(var i=0;i<xs.length;i++){fn(xs[i],i,xs)}};var defineProp=function(){try{Object.defineProperty({},"_",{});return function(obj,name,value){Object.defineProperty(obj,name,{writable:true,enumerable:false,configurable:true,value:value})}}catch(e){return function(obj,name,value){obj[name]=value}}}();var globals=["Array","Boolean","Date","Error","EvalError","Function","Infinity","JSON","Math","NaN","Number","Object","RangeError","ReferenceError","RegExp","String","SyntaxError","TypeError","URIError","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","eval","isFinite","isNaN","parseFloat","parseInt","undefined","unescape"];function Context(){}Context.prototype={};var Script=exports.Script=function NodeScript(code){if(!(this instanceof Script))return new Script(code);this.code=code};Script.prototype.runInContext=function(context){if(!(context instanceof Context)){throw new TypeError("needs a 'context' argument.")}var iframe=document.createElement("iframe");if(!iframe.style)iframe.style={};iframe.style.display="none";document.body.appendChild(iframe);var win=iframe.contentWindow;var wEval=win.eval,wExecScript=win.execScript;if(!wEval&&wExecScript){wExecScript.call(win,"null");wEval=win.eval}forEach(Object_keys(context),function(key){win[key]=context[key]});forEach(globals,function(key){if(context[key]){win[key]=context[key]}});var winKeys=Object_keys(win);var res=wEval.call(win,this.code);forEach(Object_keys(win),function(key){if(key in context||indexOf(winKeys,key)===-1){context[key]=win[key]}});forEach(globals,function(key){if(!(key in context)){defineProp(context,key,win[key])}});document.body.removeChild(iframe);return res};Script.prototype.runInThisContext=function(){return eval(this.code)};Script.prototype.runInNewContext=function(context){var ctx=Script.createContext(context);var res=this.runInContext(ctx);forEach(Object_keys(ctx),function(key){context[key]=ctx[key]});return res};forEach(Object_keys(Script.prototype),function(name){exports[name]=Script[name]=function(code){var s=Script(code);return s[name].apply(s,[].slice.call(arguments,1))}});exports.createScript=function(code){return exports.Script(code)};exports.createContext=Script.createContext=function(context){var copy=new Context;if(typeof context==="object"){forEach(Object_keys(context),function(key){copy[key]=context[key]})}return copy}},{indexof:144}],245:[function(require,module,exports){module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty;function extend(){var target={};for(var i=0;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(hasOwnProperty.call(source,key)){target[key]=source[key]}}}return target}},{}],246:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./lib/feature-detection","./lib/config","./lib/browser-agent","./lib/configuration-override"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var feature_detection_1=require("./lib/feature-detection");var config_1=require("./lib/config");var browser_agent_1=require("./lib/browser-agent");var configuration_override_1=require("./lib/configuration-override");var SEALIGHTS_WINDOW_OBJECT="$Sealights";var COMPONENTS="components";var featureDetection=null;try{featureDetection=new feature_detection_1.FeatureDetection(window);if(window&&window[SEALIGHTS_WINDOW_OBJECT]){window[SEALIGHTS_WINDOW_OBJECT].configuration=configuration_override_1.ConfigurationOverride.create(window[SEALIGHTS_WINDOW_OBJECT].configuration);var browserAgent_1=new browser_agent_1.BrowserAgent(window,featureDetection);window["$SealightsAgent"]=browserAgent_1;window[SEALIGHTS_WINDOW_OBJECT].agentVersion=config_1.SL_AGENT_VERSION;if(window[SEALIGHTS_WINDOW_OBJECT]&&window[SEALIGHTS_WINDOW_OBJECT][COMPONENTS]){Object.keys(window[SEALIGHTS_WINDOW_OBJECT][COMPONENTS]).forEach(function(buildSessionId){browserAgent_1.createInstance(window[SEALIGHTS_WINDOW_OBJECT][COMPONENTS][buildSessionId])})}else{browserAgent_1.createInstance(window[SEALIGHTS_WINDOW_OBJECT])}}}catch(e){if(featureDetection&&featureDetection.hasConsoleLogAPI()){console.log("Sealights browser listener failed to start. Error: ",e)}}})},{"./lib/browser-agent":251,"./lib/config":257,"./lib/configuration-override":259,"./lib/feature-detection":266}],247:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./state-tracker","../../common/state-tracker","./test-state-helper","./entities/environment-data","./services/http/http-client","./services/json/json-client","./istanbul-to-footprints-convertor","./istanbul-to-footprints-convertor-v3","./services/light-backend-proxy","./footprints-queue-sender","./watchdog","./code-coverage-manager","./browser-agent-instance","./queues/footprints-items-queue","./configuration-manager","./logger/log-factory","./basic-uuid-generator","./window-timers-wrapper","./color-cookie-handler","./queues/queue","./delegate","./services/json/json-client-adapter","./browser-events-process","./browser-hits-converter","./browser-agent-instance-fpv6","./browser-hits-collector","./sl-mapping-loader","./services/json/noop-json-client","../../common/agent-instance-data","../../common/agent-events/agent-events-conracts","../../common/agent-events/cockpit-notifier","../../common/http/backend-proxy","../../common/config-process/config-loader","../../common/footprints-process-v6/relative-path-resolver","../../common/footprints-process-v6/footprints-buffer","../../common/footprints-process-v6/index","../../common/config-process","../../common/system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentFactory=void 0;var state_tracker_1=require("./state-tracker");var state_tracker_2=require("../../common/state-tracker");var test_state_helper_1=require("./test-state-helper");var environment_data_1=require("./entities/environment-data");var http_client_1=require("./services/http/http-client");var json_client_1=require("./services/json/json-client");var istanbul_to_footprints_convertor_1=require("./istanbul-to-footprints-convertor");var istanbul_to_footprints_convertor_v3_1=require("./istanbul-to-footprints-convertor-v3");var light_backend_proxy_1=require("./services/light-backend-proxy");var footprints_queue_sender_1=require("./footprints-queue-sender");var watchdog_1=require("./watchdog");var code_coverage_manager_1=require("./code-coverage-manager");var browser_agent_instance_1=require("./browser-agent-instance");var footprints_items_queue_1=require("./queues/footprints-items-queue");var configuration_manager_1=require("./configuration-manager");var log_factory_1=require("./logger/log-factory");var basic_uuid_generator_1=require("./basic-uuid-generator");var window_timers_wrapper_1=require("./window-timers-wrapper");var color_cookie_handler_1=require("./color-cookie-handler");var queue_1=require("./queues/queue");var delegate_1=require("./delegate");var json_client_adapter_1=require("./services/json/json-client-adapter");var browser_events_process_1=require("./browser-events-process");var browser_hits_converter_1=require("./browser-hits-converter");var browser_agent_instance_fpv6_1=require("./browser-agent-instance-fpv6");var browser_hits_collector_1=require("./browser-hits-collector");var sl_mapping_loader_1=require("./sl-mapping-loader");var noop_json_client_1=require("./services/json/noop-json-client");var agent_instance_data_1=require("../../common/agent-instance-data");var agent_events_conracts_1=require("../../common/agent-events/agent-events-conracts");var cockpit_notifier_1=require("../../common/agent-events/cockpit-notifier");var backend_proxy_1=require("../../common/http/backend-proxy");var config_loader_1=require("../../common/config-process/config-loader");var relative_path_resolver_1=require("../../common/footprints-process-v6/relative-path-resolver");var footprints_buffer_1=require("../../common/footprints-process-v6/footprints-buffer");var index_1=require("../../common/footprints-process-v6/index");var config_process_1=require("../../common/config-process");var system_date_1=require("../../common/system-date");var FOOTPRINTS_SENDER_WATCHDOG="FootPrintsSenderWatchdog";var FOOTPRINTS_FLUSH_WATCHDOG="FootprintsFlushWatchdog";var ACTIVE_EXECUTION_WATCHDOG="ActiveExecutionWatchdog";var KEEP_ALIVE_WATCHDOG="KeepaliveWatchdog";var CONFIGURATION_WATCHDOG="getConfigFromServerWatchdog";var AgentFactory=function(){function AgentFactory(){}AgentFactory.createBrowserAgent=function(window,featureDetection,basicConfiguration){var configurationManager=AgentFactory.createConfigurationManager(basicConfiguration,window);var configuration=configurationManager.getConfiguration();var colorCookieHandler=AgentFactory.createColorCookieHandler(window);if(!configurationManager.isValidConfiguration()){return null}var agentInstanceData=new agent_instance_data_1.AgentInstanceData(agent_events_conracts_1.AgentType.TEST_LISTENER,agent_events_conracts_1.Technology.BROWSER);var logger=AgentFactory.createLogger("BrowserAgent",configuration,window);var agentConfiguration=this.createAgentConfiguration(configuration);var backendProxy=this.createBackendProxy(agentConfiguration,agentInstanceData,window,featureDetection,configuration);var eventProcess=this.createEventProcess(window,featureDetection,configuration,agentConfiguration,agentInstanceData,backendProxy);cockpit_notifier_1.CockpitNotifier.notifyStart(agentConfiguration,agentInstanceData,logger,{},backendProxy);if(agentConfiguration.footprintsEnableV6.value){return this.createBrowserAgentInstanceFPV6(window,featureDetection,configuration,agentInstanceData,logger,agentConfiguration,backendProxy,eventProcess,colorCookieHandler)}var stateTracker=AgentFactory.createStateTracker(configuration,window,featureDetection);var footprintsQueueSender=AgentFactory.createFootprintsQueueSender(window,featureDetection,configuration,stateTracker);var agent=new browser_agent_instance_1.BrowserAgentInstance(logger,footprintsQueueSender,configuration,window,colorCookieHandler,stateTracker,eventProcess,agentConfiguration);return agent};AgentFactory.createBrowserAgentInstanceFPV6=function(window,featureDetection,configuration,agentInstanceData,logger,agentConfig,backendProxy,eventsProcess,colorCookieHandler){
24
- var configProcess=this.createConfigProcess(window,configuration,agentInstanceData,agentConfig,backendProxy);var stateTracker=this.createStateTrackerInfra(window,configuration,agentInstanceData,agentConfig,backendProxy,configProcess);var footprintsProcessV6=this.getCreateFootprintsProcessV6(window,configuration,agentInstanceData,agentConfig,backendProxy,stateTracker);var lightBackendProxy=AgentFactory.createLightBackendProxy(window,featureDetection,configuration);var slMappingLoader=this.createSlMappingLoader(window,lightBackendProxy,configuration);var flushFootprintsWatchdog=AgentFactory.createWatchdog(window,configuration,FOOTPRINTS_FLUSH_WATCHDOG,agentConfig.footprintsCollectIntervalSecs.value);return new browser_agent_instance_fpv6_1.BrowserAgentInstanceFpv6(logger,footprintsProcessV6,configuration,window,colorCookieHandler,stateTracker,eventsProcess,agentConfig,flushFootprintsWatchdog,slMappingLoader)};AgentFactory.createFootprintsQueueSender=function(window,featureDetection,configuration,stateTracker){var watchdog=AgentFactory.createWatchdog(window,configuration,FOOTPRINTS_SENDER_WATCHDOG);var lightBackendProxy=AgentFactory.createLightBackendProxy(window,featureDetection,configuration);var codeCoverageManager=AgentFactory.createCodeCoverageManager(window,configuration);var testStateHelper=AgentFactory.createTestStateHelper();var environmentData=AgentFactory.createEnvironmentData(window,configuration);var footprintsItemsQueue=AgentFactory.createFootprintsItemsQueue(configuration);var logger=AgentFactory.createLogger("FootprintsQueueSender",configuration,window);var slMappingLoader=this.createSlMappingLoader(window,lightBackendProxy,configuration);var footprintsQueueSender=new footprints_queue_sender_1.FootprintsQueueSender(watchdog,lightBackendProxy,codeCoverageManager,stateTracker,testStateHelper,environmentData,configuration,footprintsItemsQueue,window,logger,slMappingLoader);return footprintsQueueSender};AgentFactory.createWatchdog=function(window,configuration,classname,intervalSec){var intervalMS=(intervalSec||configuration.interval||10)*1e3;var logger=AgentFactory.createLogger(classname,configuration,window);var windowTimeoutWrapper=AgentFactory.createWindowTimersWrapper(window);var watchdog=new watchdog_1.Watchdog(intervalMS,windowTimeoutWrapper,{autoReset:true},logger);return watchdog};AgentFactory.createCodeCoverageManager=function(window,configuration){var istanbulToFootprintsConvertor=AgentFactory.createInstanbulToFootprintsConvertor(window,configuration);var codeCoverageManager=new code_coverage_manager_1.CodeCoverageManager(istanbulToFootprintsConvertor,configuration);return codeCoverageManager};AgentFactory.createLightBackendProxy=function(window,featureDetection,configuration){var jsonClient=AgentFactory.createJsonClient(window,featureDetection,configuration);var logger=AgentFactory.createLogger("FootprintsServiceProxy",configuration,window);var lightBackendProxy=new light_backend_proxy_1.LightBackendProxy(configuration,jsonClient,logger);return lightBackendProxy};AgentFactory.createSlMappingLoader=function(window,lightBackendProxy,configuration){var logger=AgentFactory.createLogger("slMappingLoader",configuration,window);return new sl_mapping_loader_1.SlMappingLoader(lightBackendProxy,window,logger)};AgentFactory.createJsonClient=function(window,featureDetection,configuration){var httpClient=AgentFactory.createHttpClient(window,featureDetection,configuration);return configuration.blockBrowserHttpTraffic?new noop_json_client_1.NoopJsonClient(httpClient,configuration.token):new json_client_1.JsonClient(httpClient,configuration.token)};AgentFactory.createHttpClient=function(window,featureDetection,configuration){var logger=AgentFactory.createLogger("HttpClient",configuration,window);var httpClient=new http_client_1.HttpClient(window,featureDetection,logger);return httpClient};AgentFactory.createStateTracker=function(configuration,window,featureDetection){var watchdog=AgentFactory.createWatchdog(window,configuration,ACTIVE_EXECUTION_WATCHDOG);var logger=AgentFactory.createLogger("StateTracker",configuration,window);var jsonClient=AgentFactory.createJsonClient(window,featureDetection,configuration);var stateTracker=new state_tracker_1.StateTracker(configuration,jsonClient,watchdog,logger);return stateTracker};AgentFactory.createColorCookieHandler=function(window){var colorCookieHandler=new color_cookie_handler_1.ColorCookieHandler(window);return colorCookieHandler};AgentFactory.createTestStateHelper=function(){var testStateHelper=new test_state_helper_1.TestStateHelper;return testStateHelper};AgentFactory.createWindowTimersWrapper=function(window){var windowTimersWrapper=new window_timers_wrapper_1.WindowTimersWrapper(window);return windowTimersWrapper};AgentFactory.createEnvironmentData=function(window,configuration){if(!environment_data_1.EnvironmentData.constantAgentId)environment_data_1.EnvironmentData.constantAgentId=basic_uuid_generator_1.BasicUuidGenerator.createUuid()+"<|>"+this.getTime(window);var environmentData=environment_data_1.EnvironmentData.create(configuration);return environmentData};AgentFactory.createInstanbulToFootprintsConvertor=function(window,configuration){var instanbulToFootprintsConvertor=null;if(configuration.resolveWithoutHash){instanbulToFootprintsConvertor=new istanbul_to_footprints_convertor_v3_1.IstanbulToFootprintsConvertorV3(window,configuration)}else{instanbulToFootprintsConvertor=new istanbul_to_footprints_convertor_1.IstanbulToFootprintsConverter(window,configuration)}return instanbulToFootprintsConvertor};AgentFactory.createFootprintsItemsQueue=function(configuration){var footprintsItemsQueue=new footprints_items_queue_1.FootprintsItemsQueue(configuration);return footprintsItemsQueue};AgentFactory.createEventProcess=function(window,featureDetection,configurationData,agentConfiguration,agentInstanceData,backendProxy){var sendToServerWatchdog=this.createWatchdog(window,configurationData,"sendToServer");var keepAliveWatchdog=this.createWatchdog(window,configurationData,"keepAlive");var environmentData=this.createEnvironmentData(window,configurationData);environmentData.testStage=agentConfiguration.testStage.value;var logger=AgentFactory.createLogger("BrowserAgent",configurationData,window);var queue=new queue_1.Queue(new delegate_1.Delegate);var eventsProcess=new browser_events_process_1.BrowserEventsProcess(agentConfiguration,agentInstanceData,sendToServerWatchdog,keepAliveWatchdog,environmentData,backendProxy,queue,logger);return eventsProcess};AgentFactory.createBackendProxy=function(agentConfiguration,agentInstanceData,window,featureDetection,configurationData){var logger=this.createLogger("BackendProxy",configurationData,window);var httpClientConfig=this.createHttpClientConfig(agentConfiguration);var jsonClientAdapter=this.createJsonClientAdapter(window,featureDetection,configurationData);var backendProxy=new backend_proxy_1.BackendProxy(agentInstanceData,httpClientConfig,logger,jsonClientAdapter);return backendProxy};AgentFactory.createHttpClientConfig=function(agentConfig){return{token:agentConfig.token.value,proxy:agentConfig.proxy.value,server:agentConfig.server.value,compressRequests:agentConfig.gzip.value}};AgentFactory.createConfigurationManager=function(basicConfiguration,window){var logger=AgentFactory.createLogger("ConfigurationManager",basicConfiguration,window);var configurationManager=new configuration_manager_1.ConfigurationManager(logger,basicConfiguration,window);return configurationManager};AgentFactory.createLogger=function(className,basicConfiguration,window){var _a,_b;return log_factory_1.LogFactory.createLogger(className,basicConfiguration.logLevel||((_b=(_a=window===null||window===void 0?void 0:window.$Sealights)===null||_a===void 0?void 0:_a.configuration)===null||_b===void 0?void 0:_b.logLevel))};AgentFactory.getTime=function(window){if(window&&window.performance&&typeof window.performance.now==="function"){return performance.now()}return system_date_1.getSystemDateValueOf()};AgentFactory.createAgentConfiguration=function(configuration){var configLoader=new config_loader_1.ConfigLoader;var configObject=configuration;if(!configObject.build){configObject.build=configObject.buildName}if(!configObject.branch){configObject.branch=configObject.branchName}return configLoader.loadAgentConfiguration(configuration)};AgentFactory.createJsonClientAdapter=function(window,featureDetection,config){var jsonClient=this.createJsonClient(window,featureDetection,config);return new json_client_adapter_1.JsonClientAdapter(jsonClient,config.server)};AgentFactory.getCreateFootprintsProcessV6=function(window,configuration,agentInstanceData,agentConfig,backendProxy,stateTracker){var sendToServerWatchdog=AgentFactory.createWatchdog(window,configuration,FOOTPRINTS_SENDER_WATCHDOG,agentConfig.footprintsSendIntervalSecs.value);var keepaliveWatchdog=AgentFactory.createWatchdog(window,configuration,KEEP_ALIVE_WATCHDOG);var relativePathResolver=new relative_path_resolver_1.RelativePathResolver;var hitsCollector=new browser_hits_collector_1.BrowserHitsCollector(configuration.buildSessionId,this.createLogger("browserHitsCollector",configuration,window));var hitsConverter=new browser_hits_converter_1.BrowserHitsConverter(relativePathResolver,window,agentConfig.buildSessionId.value,this.createLogger("HitsConverter",configuration,window));var footprintsBuffer=new footprints_buffer_1.FootprintsBuffer(agentInstanceData,agentConfig);return new index_1.FootprintsProcess(agentConfig,sendToServerWatchdog,keepaliveWatchdog,this.createLogger("footprintsProcess",configuration,window),hitsCollector,hitsConverter,footprintsBuffer,backendProxy,stateTracker)};AgentFactory.createConfigProcess=function(window,configuration,agentInstanceData,agentConfig,backendProxy){var sendToServerWatchdog=AgentFactory.createWatchdog(window,configuration,CONFIGURATION_WATCHDOG,30);return new config_process_1.ConfigProcess(agentConfig,sendToServerWatchdog,backendProxy,this.createLogger("configProcess",configuration,window))};AgentFactory.createStateTrackerInfra=function(window,configuration,agentInstanceData,agentConfig,backendProxy,configProcess){var watchdog=AgentFactory.createWatchdog(window,configuration,ACTIVE_EXECUTION_WATCHDOG,agentConfig.executionQueryIntervalSecs.value);return new state_tracker_2.StateTracker(agentConfig,configProcess,watchdog,backendProxy,this.createLogger("stateTracker",configuration,window))};return AgentFactory}();exports.AgentFactory=AgentFactory})},{"../../common/agent-events/agent-events-conracts":289,"../../common/agent-events/cockpit-notifier":294,"../../common/agent-instance-data":299,"../../common/config-process":303,"../../common/config-process/config-loader":300,"../../common/footprints-process-v6/footprints-buffer":317,"../../common/footprints-process-v6/index":320,"../../common/footprints-process-v6/relative-path-resolver":322,"../../common/http/backend-proxy":324,"../../common/state-tracker":331,"../../common/system-date":332,"./basic-uuid-generator":248,"./browser-agent-instance":250,"./browser-agent-instance-fpv6":249,"./browser-events-process":252,"./browser-hits-collector":253,"./browser-hits-converter":254,"./code-coverage-manager":255,"./color-cookie-handler":256,"./configuration-manager":258,"./delegate":261,"./entities/environment-data":264,"./footprints-queue-sender":267,"./istanbul-to-footprints-convertor":269,"./istanbul-to-footprints-convertor-v3":268,"./logger/log-factory":272,"./queues/footprints-items-queue":274,"./queues/queue":275,"./services/http/http-client":276,"./services/json/json-client":280,"./services/json/json-client-adapter":279,"./services/json/noop-json-client":281,"./services/light-backend-proxy":282,"./sl-mapping-loader":283,"./state-tracker":284,"./test-state-helper":285,"./watchdog":287,"./window-timers-wrapper":288}],248:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BasicUuidGenerator=void 0;var BasicUuidGenerator=function(){function BasicUuidGenerator(){}BasicUuidGenerator.createUuid=function(){var uuid="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=Math.random()*16|0,v=c=="x"?r:r&3|8;return v.toString(16)});return uuid};return BasicUuidGenerator}();exports.BasicUuidGenerator=BasicUuidGenerator})},{}],249:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./browser-agent-instance"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserAgentInstanceFpv6=void 0;var browser_agent_instance_1=require("./browser-agent-instance");var BrowserAgentInstanceFpv6=function(_super){__extends(BrowserAgentInstanceFpv6,_super);function BrowserAgentInstanceFpv6(logger,footprintsProcess,configuration,window,colorCookieHandler,stateTracker,eventsProcess,agentConfig,flushFootprintsWatchdog,slMappingLoader){var _this=_super.call(this,logger,{},configuration,window,colorCookieHandler,stateTracker,eventsProcess,agentConfig)||this;_this.footprintsProcess=footprintsProcess;_this.flushFootprintsWatchdog=flushFootprintsWatchdog;_this.slMappingLoader=slMappingLoader;_this.stateTracker.on("test_identifier_changed",_this.footprintsProcess.handleTestIdChanged.bind(_this.footprintsProcess));return _this}BrowserAgentInstanceFpv6.prototype.delegateEvents=function(){};BrowserAgentInstanceFpv6.prototype.startFootprintsProcess=function(){this.flushFootprintsWatchdog.addOnAlarmListener(this.footprintsProcess.flushCurrentFootprints.bind(this.footprintsProcess));this.flushFootprintsWatchdog.start();this.footprintsProcess.start();this.stateTracker.start();this.slMappingLoader.loadSlMapping(this.configuration.buildSessionId)};BrowserAgentInstanceFpv6.prototype.stopFootprintsProcess=function(){this.flushFootprintsWatchdog.stop();this.footprintsProcess.stop(function(){})};BrowserAgentInstanceFpv6.prototype.submitFootprints=function(){this.footprintsProcess.submitQueuedFootprints()};BrowserAgentInstanceFpv6.prototype.submitFootprintsSync=function(){return __awaiter(this,void 0,void 0,function(){var e_1;return __generator(this,function(_a){switch(_a.label){case 0:_a.trys.push([0,3,,4]);return[4,this.footprintsProcess.flushCurrentFootprints()];case 1:_a.sent();return[4,this.footprintsProcess.submitQueuedFootprints()];case 2:_a.sent();return[3,4];case 3:e_1=_a.sent();this.logger.error("Failed to submit footprint sync '"+e_1.message+"'");return[3,4];case 4:return[2]}})})};return BrowserAgentInstanceFpv6}(browser_agent_instance_1.BrowserAgentInstance);exports.BrowserAgentInstanceFpv6=BrowserAgentInstanceFpv6})},{"./browser-agent-instance":250}],250:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./config","./karma-handler","./basic-uuid-generator","../../common/agent-events/cockpit-notifier"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserAgentInstance=void 0;var config_1=require("./config");var karma_handler_1=require("./karma-handler");var basic_uuid_generator_1=require("./basic-uuid-generator");var cockpit_notifier_1=require("../../common/agent-events/cockpit-notifier");var BrowserAgentInstance=function(){function BrowserAgentInstance(logger,footprintsQueueSender,configuration,window,colorCookieHandler,stateTracker,eventsProcess,agentConfig){this.logger=logger;this.footprintsQueueSender=footprintsQueueSender;this.configuration=configuration;this.window=window;this.colorCookieHandler=colorCookieHandler;this.stateTracker=stateTracker;this.eventsProcess=eventsProcess;this.agentConfig=agentConfig;this._isStarted=false;if(logger==null)throw new Error("'logger' cannot be null or undefined");if(configuration==null)throw new Error("'configuration' cannot be null or undefined");if(window==null)throw new Error("'window' cannot be null or undefined");if(eventsProcess==null)throw new Error("'eventsProcess' cannot be null or undefined");if(agentConfig==null)throw new Error("'agentConfig' cannot be null or undefined");logger.info("Sealights "+config_1.SL_AGENT_TYPE+" version "+config_1.SL_AGENT_VERSION+" has been loaded");this.delegateEvents()}BrowserAgentInstance.prototype.delegateEvents=function(footprintsProcess){var _this=this;this.stateTracker.addOnColorChangedListener(function(){var color=_this.stateTracker.getCurrentColor();_this.colorCookieHandler.handleColorChange(color)})};BrowserAgentInstance.getExecutionId=function(){if(!BrowserAgentInstance.executionId){var execId=basic_uuid_generator_1.BasicUuidGenerator.createUuid();BrowserAgentInstance.executionId=execId}return BrowserAgentInstance.executionId};BrowserAgentInstance.prototype.enqueueEvent=function(event){this.eventsProcess.enqueueEvent(event)};BrowserAgentInstance.prototype.start=function(){if(this._isStarted)return;this.logger.info("Agent is starting. registerShutdownHook:"+this.configuration.registerShutdownHook);if(this.configuration.registerShutdownHook){this.registerShutdownHook()}this.eventsProcess.start();this.startFootprintsProcess();this._isStarted=true};BrowserAgentInstance.prototype.startFootprintsProcess=function(){this.footprintsQueueSender.start()};BrowserAgentInstance.prototype.stop=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:if(!this._isStarted)return[2];this.logger.info("Agent is stopping.");return[4,this.eventsProcess.stop()];case 1:_a.sent();this.stopFootprintsProcess();return[4,cockpit_notifier_1.CockpitNotifier.notifyShutdown()];case 2:_a.sent();this._isStarted=false;return[2]}})})};BrowserAgentInstance.prototype.stopFootprintsProcess=function(){this.footprintsQueueSender.sendAllSync()};BrowserAgentInstance.prototype.setCurrentTestIdentifier=function(testIdentifier){this.logger.info("Agent is setting current test identifier. testIdentifier:'"+testIdentifier+"'.");this.stateTracker.setCurrentTestIdentifier(testIdentifier)};BrowserAgentInstance.prototype.endTest=function(){this.logger.info("Test '"+this.stateTracker.getCurrentTestIdentifier()+"' ended, sending remaining footprints");this.submitFootprints();this.stateTracker.setCurrentTestIdentifier(null)};BrowserAgentInstance.prototype.submitFootprints=function(){this.footprintsQueueSender.sendAll()};BrowserAgentInstance.prototype.submitFootprintsSync=function(){try{this.footprintsQueueSender.sendAllSync()}catch(e){this.logger.error("Failed to submit footprint sync '"+e.message+"'")}};BrowserAgentInstance.prototype.isStarted=function(){return this._isStarted};BrowserAgentInstance.prototype.registerShutdownHook=function(){var context=this;var oldUnload=this.window.onunload;this.window.onunload=function(){if(oldUnload){oldUnload.call(arguments)}context.stop()};var oldBeforeUnload=this.window.onbeforeunload;this.window.onbeforeunload=function(){if(oldBeforeUnload){oldBeforeUnload.call(arguments)}context.stop()};if(this.window.__karma__){var handler=new karma_handler_1.KarmaHandler(this.window,this,this.logger);handler.overrideKarmaMethods();handler.start()}};return BrowserAgentInstance}();exports.BrowserAgentInstance=BrowserAgentInstance})},{"../../common/agent-events/cockpit-notifier":294,"./basic-uuid-generator":248,"./config":257,"./karma-handler":270}],251:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-factory","./logger/log-factory"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserAgent=void 0;var agent_factory_1=require("./agent-factory");var log_factory_1=require("./logger/log-factory");var BrowserAgent=function(){function BrowserAgent(window,featureDetection){this.instances=[];this.running=false;this.logger=log_factory_1.LogFactory.createLogger("BrowserAgent");this.instanceAddedForBsid={};this.window=window;this.featureDetection=featureDetection}BrowserAgent.prototype.addInstance=function(instance){this.instances.push(instance)};BrowserAgent.prototype.createInstance=function(configuration){if(this.instanceAddedForBsid[configuration.buildSessionId]){this.logger.info("Already has instance for bsid '"+configuration.buildSessionId+"'");return}try{this.instanceAddedForBsid[configuration.buildSessionId]=true;var browserAgent=agent_factory_1.AgentFactory.createBrowserAgent(this.window,this.featureDetection,configuration);if(browserAgent){browserAgent.start();this.instances.push(browserAgent)}else{this.logger.error("Invalid configuration for app: "+configuration.appName+",\n build: "+configuration.buildName+", branch: "+configuration.branchName+"\n Sealights agent disabled")}}catch(e){this.logger.error("Error while creating agent for app: "+configuration.appName+", build: "+configuration.buildName+",\n branch: "+configuration.branchName+". Error "+e)}};BrowserAgent.prototype.start=function(){if(this.instances.length==0){return}this.instances.forEach(function(instance){return instance.start()});this.running=true};BrowserAgent.prototype.stop=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,Promise.all(this.instances.map(function(instance){return instance.stop()}))];case 1:_a.sent();this.running=false;return[2]}})})};BrowserAgent.prototype.isRunning=function(){return this.running};BrowserAgent.prototype.setCurrentTestIdentifier=function(identifier){this.instances.forEach(function(instance){return instance.setCurrentTestIdentifier(identifier)})};BrowserAgent.prototype.sendAllFootprints=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,Promise.all(this.instances.map(function(instance){return instance.submitFootprintsSync()}))];case 1:_a.sent();return[2]}})})};return BrowserAgent}();exports.BrowserAgent=BrowserAgent})},{"./agent-factory":247,"./logger/log-factory":272}],252:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/events-process"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserEventsProcess=void 0;var events_process_1=require("../../common/events-process");var BrowserEventsProcess=function(_super){__extends(BrowserEventsProcess,_super);function BrowserEventsProcess(){return _super!==null&&_super.apply(this,arguments)||this}BrowserEventsProcess.prototype.stop=function(){return __awaiter(this,void 0,void 0,function(){var callback,items,packet;var _this=this;return __generator(this,function(_a){this.isRunning=false;this.sendToServerWatchdog.stop();if(this.configuration.enabled.value===false||this.configuration.sendEvents.value===false){return[2]}callback=function(err){if(err){_this.logger.error("Failed to submit final events, Error : '"+err+"'")}};while(this.eventsQueue.getQueueSize()>0){items=this.eventsQueue.dequeue(events_process_1.EventsProcess.ITEMS_TO_DEQUE);packet=this.createEventsPacket(items);this.backendProxy.submitEvents(packet,callback,false)}return[2]})})};return BrowserEventsProcess}(events_process_1.EventsProcess)
25
- ;exports.BrowserEventsProcess=BrowserEventsProcess})},{"../../common/events-process":314}],253:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/footprints-process-v6/hits-collector"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserHitsCollector=void 0;var hits_collector_1=require("../../common/footprints-process-v6/hits-collector");var BrowserHitsCollector=function(_super){__extends(BrowserHitsCollector,_super);function BrowserHitsCollector(buildSessionId,logger,globalCoverageObject){var _this=_super.call(this,logger,globalCoverageObject)||this;_this.buildSessionId=buildSessionId;return _this}BrowserHitsCollector.prototype.getGlobalCoverageObject=function(){if(!this.globalCoverageObject){var coverageObject="$SealightsCoverage";var coverageObjectForBSID=coverageObject+"_"+this.buildSessionId;this.globalCoverageObject=window[coverageObjectForBSID]||window[coverageObject]}return this.globalCoverageObject};return BrowserHitsCollector}(hits_collector_1.HitsCollector);exports.BrowserHitsCollector=BrowserHitsCollector})},{"../../common/footprints-process-v6/hits-collector":318}],254:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/footprints-process-v6/base-browser-hits-converter"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserHitsConverter=void 0;var base_browser_hits_converter_1=require("../../common/footprints-process-v6/base-browser-hits-converter");var BrowserHitsConverter=function(_super){__extends(BrowserHitsConverter,_super);function BrowserHitsConverter(relativePathResolver,window,buildSessionId,logger){var _this=_super.call(this,relativePathResolver,buildSessionId,logger)||this;_this.window=window;return _this}BrowserHitsConverter.prototype.getSlMapping=function(){return this.window.slMappings[this.buildSessionId]||{}};return BrowserHitsConverter}(base_browser_hits_converter_1.BaseBrowserHitsConverter);exports.BrowserHitsConverter=BrowserHitsConverter})},{"../../common/footprints-process-v6/base-browser-hits-converter":315}],255:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CodeCoverageManager=void 0;var CodeCoverageManager=function(){function CodeCoverageManager(convertor,configuration){this.convertor=convertor;this.configuration=configuration;this.aggregatedCoverage={};this.isDestroyed=false}CodeCoverageManager.prototype.findCoverageContainer=function(){var coverageObject="$SealightsCoverage";var coverageObjectForBSID=coverageObject+"_"+this.configuration.buildSessionId;return window[coverageObjectForBSID]||window[coverageObject]};CodeCoverageManager.prototype.getFootprints=function(testInfo){var counters=this.getCounters(true);return this.convertor.convert(counters,testInfo.testName,testInfo.executionId)};CodeCoverageManager.prototype._clearCounters=function(istanbulCoverageObject){if(!istanbulCoverageObject)return;if(this.isDestroyed)return;var context=this;this.forEachProp(istanbulCoverageObject,function(moduleName,m){context.aggregatedCoverage[moduleName]=context.aggregatedCoverage[moduleName]||{s:{},b:{},f:{}};var am=context.aggregatedCoverage[moduleName];context.forEachProp(m.s,function(sid,s){am.s[sid]=(am.s[sid]||0)+m.s[sid];m.s[sid]=0});context.forEachProp(m.b,function(bid,b){am.b[bid]=am.b[bid]||Array.apply(null,Array(m.b[bid].length)).map(Number.prototype.valueOf,0);for(var idx=0;idx<am.b[bid].length;idx++){am.b[bid][idx]+=m.b[bid][idx];m.b[bid][idx]=0}});context.forEachProp(m.f,function(fid,f){am.f[fid]=(am.f[fid]||0)+m.f[fid];m.f[fid]=0})})};CodeCoverageManager.prototype.cloneCodeMetrics=function(o){var cloned={};for(var i in o){cloned[i]=this.cloneModule(o[i])}return cloned};CodeCoverageManager.prototype.cloneModule=function(m){var cm={b:{},f:{},s:{}};for(var i in m.s){cm.s[i]=m.s[i]}for(var i in m.f){cm.f[i]=m.f[i]}for(var i in m.b){cm.b[i]=m.b[i].slice()}cm.metadata=m.metadata;cm.path=m.path;cm.fnMap=m.fnMap;cm.fnToBranch=m.fnToBranch;cm.branchMap=m.branchMap;cm.inputSourceMap=m.inputSourceMap;return cm};CodeCoverageManager.prototype.forEachProp=function(obj,func){Object.keys(obj).forEach(function(k){func(k,obj[k])})};CodeCoverageManager.prototype.clearCounters=function(){if(this.isDestroyed)return;var ct=this.findCoverageContainer();if(ct){this._clearCounters(ct)}};CodeCoverageManager.prototype.getCounters=function(clearAfterwards){if(this.isDestroyed)return{};var ct=this.findCoverageContainer();if(ct){var ret=this.cloneCodeMetrics(ct);if(clearAfterwards)this._clearCounters(ct);return ret}};return CodeCoverageManager}();exports.CodeCoverageManager=CodeCoverageManager})},{}],256:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./state-tracker"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ColorCookieHandler=void 0;var state_tracker_1=require("./state-tracker");var ColorCookieHandler=function(){function ColorCookieHandler(window){this.window=window;this.COOKIE_KEY="x-sl-testid"}ColorCookieHandler.prototype.setCookie=function(color){var cookie=this.COOKIE_KEY+"="+color;this.window.document.cookie=cookie};ColorCookieHandler.prototype.handleColorChange=function(color){if(color!=null&&color!=state_tracker_1.StateTracker.ANONYMOUS_FOOTPRINTS_COLOR){this.setCookie(color)}else{this.removeCookie()}};ColorCookieHandler.prototype.removeCookie=function(){this.window.document.cookie=this.COOKIE_KEY+"=;expires=Thu, 01 Jan 1970 00:00:01 GMT;"};ColorCookieHandler.prototype.getCookie=function(){return this.window.document.cookie};return ColorCookieHandler}();exports.ColorCookieHandler=ColorCookieHandler})},{"./state-tracker":284}],257:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SL_AGENT_TYPE=exports.SL_AGENT_VERSION=void 0;exports.SL_AGENT_VERSION="1.0.0";exports.SL_AGENT_TYPE="browser"})},{}],258:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./entities/configuration-data"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigurationManager=void 0;var configuration_data_1=require("./entities/configuration-data");var ConfigurationManager=function(){function ConfigurationManager(logger,basicConfiguration,window){this.logger=logger;this.basicConfiguration=basicConfiguration;this.window=window;if(logger==null)throw new Error("'logger' cannot be null or undefined");if(basicConfiguration==null)throw new Error("'basicConfiguration' cannot be null or undefined");if(window==null)throw new Error("'window' cannot be null or undefined")}ConfigurationManager.prototype.getConfiguration=function(){if(this.currentConfiguration)return this.currentConfiguration;var configurationData=this.getDefaults();this.overrideConfiguration(configurationData);configurationData.labId=this.resolveLabId();this.currentConfiguration=configurationData;this.printConfiguration(configurationData);this.validateConfiguration(configurationData);return configurationData};ConfigurationManager.prototype.getDefaults=function(){var config=new configuration_data_1.ConfigurationData;config.appName=this.basicConfiguration.appName;config.branchName=this.basicConfiguration.branchName;config.buildName=this.basicConfiguration.buildName;config.buildSessionId=this.basicConfiguration.buildSessionId;config.customerId=this.basicConfiguration.customerId;config.token=this.basicConfiguration.token;config.server=this.basicConfiguration.server;config.interval=this.basicConfiguration.interval||10;config.maxItemsInQueue=this.basicConfiguration.maxItemsInQueue||500;config.workspacepath=this.basicConfiguration.workspacepath;return config};ConfigurationManager.prototype.resolveLabId=function(){var labId=this.readLabIdFromWindow();if(labId){this.logger.info("Using labId from the 'window' object. LabId:"+labId);return labId}labId=this.basicConfiguration.labId;if(labId){this.logger.info("Using labId from basic configuration. LabId:"+labId);return labId}labId=this.readLabIdFromSessionStorage();if(labId){this.logger.info("Using labId from session storage. LabId:"+labId);return labId}labId=this.basicConfiguration.buildSessionId;if(labId){this.logger.info("Using buildSessionId as labId. LabId:"+labId);return labId}labId=this.basicConfiguration.appName;if(labId){this.logger.info("Using appName as labId. LabId:"+labId);return labId}return"DefaultLabId"};ConfigurationManager.prototype.overrideConfiguration=function(configurationData){for(var p in this.basicConfiguration){configurationData[p]=this.basicConfiguration[p]}this.logger.info("[TO CS] - TODO: Send request to server to get the configuration.")};ConfigurationManager.prototype.printConfiguration=function(configurationData){this.logger.info("***********************************************************");this.logger.info("Current configuration:");this.logger.info("------------------------------------------------");for(var prop in configurationData){this.logger.info(prop+": '"+configurationData[prop])+"'"}this.logger.info("***********************************************************")};ConfigurationManager.prototype.validateConfiguration=function(configurationData){var _this=this;var fieldsWithError=[];if(!configurationData.customerId||configurationData.customerId=="")fieldsWithError.push("customerId");if(!configurationData.server||configurationData.server=="")fieldsWithError.push("server");if(!configurationData.appName||configurationData.appName=="")fieldsWithError.push("appName");if(!configurationData.branchName||configurationData.branchName=="")fieldsWithError.push("branchName");if(!configurationData.buildName||configurationData.buildName=="")fieldsWithError.push("buildName");if(!configurationData.token||configurationData.token=="")fieldsWithError.push("token");if(fieldsWithError.length>0){this.logger.warn("------------------------------------------------");this.logger.warn("Detected an invalid configuration:");fieldsWithError.forEach(function(field){_this.logger.warn("'"+field+"' is required but it had a 'null' or empty value.")});this.logger.warn("Please fix the configuration prior to using SeaLights.");this.logger.warn("------------------------------------------------")}this._isValidConfiguration=fieldsWithError.length==0};ConfigurationManager.prototype.isValidConfiguration=function(){return this._isValidConfiguration};ConfigurationManager.prototype.readLabIdFromSessionStorage=function(){var labId=null;if(this.window.sessionStorage&&typeof this.window.sessionStorage==="function"){labId=this.window.sessionStorage.getItem(ConfigurationManager.LAB_ID_KEY)}return labId};ConfigurationManager.prototype.readLabIdFromWindow=function(){return this.window[ConfigurationManager.LAB_ID_KEY]};ConfigurationManager.LAB_ID_KEY="__sl.labId__";return ConfigurationManager}();exports.ConfigurationManager=ConfigurationManager})},{"./entities/configuration-data":263}],259:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","events","./logger/console-logger"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigurationOverride=exports.ConfigChangedEvents=void 0;var EventEmitter=require("events");var console_logger_1=require("./logger/console-logger");var ConfigChangedEvents;(function(ConfigChangedEvents){ConfigChangedEvents["LOG_LEVEL_CHANGED"]="logLevelChanged"})(ConfigChangedEvents=exports.ConfigChangedEvents||(exports.ConfigChangedEvents={}));var ConfigurationOverride=function(_super){__extends(ConfigurationOverride,_super);function ConfigurationOverride(initialConfig){var _this=_super.call(this)||this;_this._logLevel=console_logger_1.LogLevels.INFO;_this.setMaxListeners(500);_this.loadInitialConfig(initialConfig);return _this}Object.defineProperty(ConfigurationOverride.prototype,"logLevel",{get:function(){return this._logLevel},set:function(value){this._logLevel=value;this.emit(ConfigChangedEvents.LOG_LEVEL_CHANGED,value)},enumerable:false,configurable:true});ConfigurationOverride.prototype.loadInitialConfig=function(initialConfig){if(initialConfig===void 0){initialConfig={}}for(var prop in initialConfig){var descriptor=Object.getOwnPropertyDescriptor(this.constructor.prototype,prop);if(descriptor&&typeof descriptor.set==="function"){this[prop]=initialConfig[prop]}}};ConfigurationOverride.create=function(configuration){if(configuration instanceof ConfigurationOverride){return configuration}return new ConfigurationOverride(configuration)};return ConfigurationOverride}(EventEmitter);exports.ConfigurationOverride=ConfigurationOverride})},{"./logger/console-logger":271,events:110}],260:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ExecutionStatus=void 0;var ExecutionStatus;(function(ExecutionStatus){ExecutionStatus["InProgress"]="created";ExecutionStatus["Ending"]="pendingDelete"})(ExecutionStatus=exports.ExecutionStatus||(exports.ExecutionStatus={}))})},{}],261:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Delegate=void 0;var Delegate=function(){function Delegate(){this.functions=new Array}Delegate.prototype.addListener=function(func){if(!func)return;if(this.functions)this.functions.push(func)};Delegate.prototype.fire=function(){if(!this.functions)return;for(var i=0;i<this.functions.length;i++){this.functions[i]()}};return Delegate}();exports.Delegate=Delegate})},{}],262:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BasicConfigurationData=void 0;var BasicConfigurationData=function(){function BasicConfigurationData(){}return BasicConfigurationData}();exports.BasicConfigurationData=BasicConfigurationData})},{}],263:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./basic-configuation-data"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigurationData=void 0;var basic_configuation_data_1=require("./basic-configuation-data");var ConfigurationData=function(_super){__extends(ConfigurationData,_super);function ConfigurationData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.registerShutdownHook=true;_this.enabled=true;return _this}return ConfigurationData}(basic_configuation_data_1.BasicConfigurationData);exports.ConfigurationData=ConfigurationData})},{"./basic-configuation-data":262}],264:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../config"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EnvironmentData=void 0;var config_1=require("../config");var EnvironmentData=function(){function EnvironmentData(){}EnvironmentData.create=function(configuration){var data=new EnvironmentData;data.agentType=config_1.SL_AGENT_TYPE;data.agentVersion=config_1.SL_AGENT_VERSION;data.agentId=EnvironmentData.constantAgentId;data.labId=configuration.labId||"";data.meta={navigator:window.navigator,userAgent:window.navigator&&window.navigator.userAgent,location:window.location};return data};return EnvironmentData}();exports.EnvironmentData=EnvironmentData})},{"../config":257}],265:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsItemData=void 0;var FootprintsItemData=function(){function FootprintsItemData(){}return FootprintsItemData}();exports.FootprintsItemData=FootprintsItemData})},{}],266:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FeatureDetection=void 0;var FeatureDetection=function(){function FeatureDetection(window){this.window=window;if(!window)throw new Error("'window' cannot be null or undefined")}FeatureDetection.prototype.hasBeaconAPI=function(){var result=window.navigator&&this.isFunction(window.navigator["sendBeacon"]);return result};FeatureDetection.prototype.hasConsoleLogAPI=function(){var result=window.console&&this.isFunction(window.console.log);return result};FeatureDetection.prototype.hasJsonAPI=function(){var result=JSON&&this.isFunction(JSON.stringify)&&this.isFunction(JSON.parse);return result};FeatureDetection.prototype.isFunction=function(o){return o&&typeof o==="function"};return FeatureDetection}();exports.FeatureDetection=FeatureDetection})},{}],267:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./entities/footprints-item-data","../../common/system-date","../../common/agent-events/cockpit-notifier"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsQueueSender=void 0;var footprints_item_data_1=require("./entities/footprints-item-data");var system_date_1=require("../../common/system-date");var cockpit_notifier_1=require("../../common/agent-events/cockpit-notifier");var FootprintsQueueSender=function(){function FootprintsQueueSender(watchdog,lightBackendProxy,codeCoverageManager,stateTracker,testStateHelper,environmentData,configuration,footprintsQueue,window,logger,slMappingLoader){var _this=this;this.watchdog=watchdog;this.lightBackendProxy=lightBackendProxy;this.codeCoverageManager=codeCoverageManager;this.stateTracker=stateTracker;this.testStateHelper=testStateHelper;this.environmentData=environmentData;this.configuration=configuration;this.footprintsQueue=footprintsQueue;this.window=window;this.logger=logger;this.slMappingLoader=slMappingLoader;this.isStarted=false;if(watchdog==null)throw new Error("'watchdog' cannot be null or undefined");if(lightBackendProxy==null)throw new Error("'lightBackendProxy' cannot be null or undefined");if(codeCoverageManager==null)throw new Error("'codeCoverageManager' cannot be null or undefined");if(stateTracker==null)throw new Error("'stateTracker' cannot be null or undefined");if(testStateHelper==null)throw new Error("'testStateHelper' cannot be null or undefined");if(environmentData==null)throw new Error("'environmentData' cannot be null or undefined");if(configuration==null)throw new Error("'configuration' cannot be null or undefined");if(footprintsQueue==null)throw new Error("'footprintsQueue' cannot be null or undefined");if(window==null)throw new Error("'window' cannot be null or undefined");if(logger==null)throw new Error("'logger' cannot be null or undefined");this.context=this;this.watchdog.addOnAlarmListener(function(){_this.context.onTimerTick()})}FootprintsQueueSender.prototype.onTimerTick=function(){if(!this.stateTracker.shouldCollectFootprints()){return}var footprints=this.getCurrentFootprints();this.send(footprints)};FootprintsQueueSender.prototype.start=function(){if(this.isStarted)return;this.watchdog.start();this.slMappingLoader.loadSlMapping(this.configuration.buildSessionId);this.isStarted=true};FootprintsQueueSender.prototype.stop=function(){if(!this.isStarted)return;this.watchdog.stop();this.isStarted=false};FootprintsQueueSender.prototype.send=function(footprintsData,async,shouldRequeue){if(async===void 0){async=true}if(shouldRequeue===void 0){shouldRequeue=true}if(!footprintsData){this.logger.info("No need to send footprints as the 'footprintsData' is null or undefined.");return}var request=this.createRequest(footprintsData);if(request==null){this.logger.info("No need to send footprints as the request is empty.");return}var context=this;var onSuccess=function(){context.logger.info("Sent footprints successfully")};var onError=function(response){context.logger.error("Failed while trying to send footprints. response.responseText: '"+response.responseText+"'. response.statusCode:"+response.statusCode);if(shouldRequeue){context.logger.info("Requeuing footprints again");context.footprintsQueue.requeueItems(footprintsData)}};this.lightBackendProxy.submitRequest(request,onSuccess,onError,async)};FootprintsQueueSender.prototype.sendAllSync=function(){if(!this.stateTracker.shouldCollectFootprints()){return}this.logger.info("Sending all remaining footprints synchronously.");this.delayIfHasRequestsInProgress();var async=false;var footprints=this.getCurrentFootprints();this.send(footprints,async)};FootprintsQueueSender.prototype.sendAll=function(){var footprints=this.getCurrentFootprints();this.send(footprints)};FootprintsQueueSender.prototype.delayIfHasRequestsInProgress=function(){var counter=this.configuration.delayShutdownInSeconds||30;while(this.lightBackendProxy.hasRequestsInProgress()&&counter-- >0){this.logger.info("Has other requests in progress. Sleeping.. # of requests: "+this.lightBackendProxy.getRequestsInProgressCount()+". Remaining retries: "+counter);this.sleep(1e3)}};FootprintsQueueSender.prototype.pushCurrentFootprints=function(){if(!this.stateTracker.shouldCollectFootprints()){return}var testId=this.stateTracker.getCurrentTestIdentifier();var testInfo=this.testStateHelper.splitTestIdToExecutionAndTestName(testId);var footprints=this.codeCoverageManager.getFootprints(testInfo);if(this.configuration.resolveWithoutHash){this.enqueueV5Footprints(footprints)}else{this.enqueueV2Footprints(footprints,testInfo)}};FootprintsQueueSender.prototype.enqueueV2Footprints=function(appsAndFootprintsArray,testInfo){if(appsAndFootprintsArray&&appsAndFootprintsArray.length){var queueItem=new footprints_item_data_1.FootprintsItemData;queueItem.testName=testInfo.testName;queueItem.executionId=testInfo.executionId;queueItem.apps=appsAndFootprintsArray;this.footprintsQueue.enqueueItem(queueItem)}};FootprintsQueueSender.prototype.enqueueV5Footprints=function(footprintsRequest){if(!footprintsRequest)return;if(!footprintsRequest.apps||footprintsRequest.apps.length==0)return;if(!footprintsRequest.tests||footprintsRequest.tests.length==0)return;this.footprintsQueue.enqueueItem(footprintsRequest)};FootprintsQueueSender.prototype.getCurrentFootprints=function(){this.pushCurrentFootprints();var footprints=this.footprintsQueue.getQueueContentsAndEmptyQueue();return footprints};FootprintsQueueSender.prototype.createRequest=function(data){if(this.configuration.resolveWithoutHash){return this.createV5FootprintsRequest(data)}return this.createV2FootprintsRequest(data)};FootprintsQueueSender.prototype.createV5FootprintsRequest=function(footprintsData){var originalRequest=footprintsData[0];if(!originalRequest){return null}if(!this.hasApps(originalRequest)||!this.hasTests(originalRequest)){return null}var request={};request.customerId=this.configuration.customerId;request.environment=this.environmentData;request.configurationData=this.configuration;request.apps=originalRequest.apps;request.tests=originalRequest.tests;request.meta=originalRequest.meta;return request};FootprintsQueueSender.prototype.createV2FootprintsRequest=function(appsAndFootprintsArray){if(!appsAndFootprintsArray||!appsAndFootprintsArray.length){return null}var request={};request.customerId=this.configuration.customerId;request.items=appsAndFootprintsArray;request.environment=this.environmentData;request.configurationData=this.configuration;return request};FootprintsQueueSender.prototype.sleep=function(millis){var start=system_date_1.getSystemDateValueOf();var end=null;do{end=system_date_1.getSystemDateValueOf()}while(end-start<millis)};FootprintsQueueSender.prototype.hasApps=function(request){return request.apps&&request.apps.length>0};FootprintsQueueSender.prototype.hasTests=function(request){return request.tests&&request.tests.length>0};FootprintsQueueSender.prototype.loadSlMapping=function(){var _this=this;this.window.slMappings=this.window.slMappings||{};if(!this.window.slMappings[this.configuration.buildSessionId]){this.lightBackendProxy.getSlMappingFromServer(this.configuration.buildSessionId).then(function(mapping){return _this.window.slMappings[_this.configuration.buildSessionId]=mapping},function(err){var errMsg="Error while trying to load slMapping from server '"+err+"'";_this.logger.error(errMsg);cockpit_notifier_1.CockpitNotifier.sendGenericMessage(errMsg);_this.window.slMappings[_this.configuration.buildSessionId]={}})}};return FootprintsQueueSender}();exports.FootprintsQueueSender=FootprintsQueueSender})},{"../../common/agent-events/cockpit-notifier":294,"../../common/system-date":332,"./entities/footprints-item-data":265}],268:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./logger/log-factory","../../common/footprints-process-v6/location-formatter","../../common/footprints-process/collection-interval","../../common/system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.IstanbulToFootprintsConvertorV3=void 0;var log_factory_1=require("./logger/log-factory");var location_formatter_1=require("../../common/footprints-process-v6/location-formatter");var collection_interval_1=require("../../common/footprints-process/collection-interval");var system_date_1=require("../../common/system-date");var IstanbulToFootprintsConvertorV3=function(){function IstanbulToFootprintsConvertorV3(window,cfg){this.window=window;this.cfg=cfg;this.totalTests=0;if(!window)throw new Error("window is required");if(!cfg)throw new Error("cfg is required");this.collectionInterval=new collection_interval_1.CollectionInterval(this.cfg.interval*1e3);this.logger=log_factory_1.LogFactory.createLogger("IstanbulToFootprintsConvertor")}IstanbulToFootprintsConvertorV3.prototype.resetState=function(){this.totalTests=0;this.eidToHitsIndex={};this.uniqueIdToElement={};this.testNameToTestData={};this.fileNameToAppFile={};this.collectionInterval.next()};IstanbulToFootprintsConvertorV3.prototype.convert=function(istanbulFootprints,testName,executionId,mockTime){this.resetState();var result=this.createFootprintsFile();var app=result.apps[0];var localTime=mockTime?mockTime:system_date_1.getSystemDateValueOf();var test=this.getOrCreateTestData(testName,executionId,localTime,result);for(var moduleName in istanbulFootprints){var istanbulModule=istanbulFootprints[moduleName];if(!istanbulModule){continue}var scopeData={test:test,app:app,modulePath:istanbulModule.path.replace(/\\/g,"/"),istanbulModule:istanbulModule};if(istanbulModule.f){this.addMethodsWithHits(scopeData)}if(istanbulModule.b){this.addBranchesWithHits(scopeData)}}result.apps=this.filterAppsWithoutHits(result.apps);return result};IstanbulToFootprintsConvertorV3.prototype.filterAppsWithoutHits=function(apps){var _this=this;if(!apps)return apps;return apps.filter(function(app){return _this.filterFilesWithoutHits(app)})}
26
- ;IstanbulToFootprintsConvertorV3.prototype.filterFilesWithoutHits=function(app){var _this=this;var hasFiles=false;if(!app||!app.files){return hasFiles}app.files=app.files.filter(function(file){return _this.filterElementsWithoutHits(file)});hasFiles=app.files.length>0;return hasFiles};IstanbulToFootprintsConvertorV3.prototype.filterElementsWithoutHits=function(file){var hasMethodHits=this.filterElementWithoutHits(file,"methods");var hasBranchHits=this.filterElementWithoutHits(file,"branches");var hasLineHits=this.filterElementWithoutHits(file,"lines");var hasHits=hasMethodHits||hasBranchHits||hasLineHits;return hasHits};IstanbulToFootprintsConvertorV3.prototype.filterElementWithoutHits=function(file,coverageType){var _this=this;var fileObject=file;var arrayOfCodeElements=fileObject[coverageType]||[];arrayOfCodeElements=arrayOfCodeElements.filter(function(ce){return _this.hasHit(ce)});fileObject[coverageType]=arrayOfCodeElements;var hasHits=arrayOfCodeElements.length>0;return hasHits};IstanbulToFootprintsConvertorV3.prototype.hasHit=function(element){var hasHitInAnyTest=element.hits.some(function(hitToTest){return hitToTest[1]>0});return hasHitInAnyTest};IstanbulToFootprintsConvertorV3.prototype.addMethodsWithHits=function(scopeData){var istanbulModule=scopeData.istanbulModule;for(var methodId in istanbulModule.f){var hits=istanbulModule.f[methodId];if(hits>0){var methodData=istanbulModule.fnMap[methodId];this.addOrUpdateMethodElement(scopeData,methodData,hits)}}};IstanbulToFootprintsConvertorV3.prototype.addBranchesWithHits=function(scopeData){var istanbulModule=scopeData.istanbulModule;for(var branchId in istanbulModule.b){var probesArray=istanbulModule.b[branchId];for(var idx=0;idx<probesArray.length;idx++){var hits=probesArray[idx];if(hits>0){var branchData=istanbulModule.branchMap[branchId];this.addOrUpdateBranchElement(scopeData,branchData,idx,hits)}}}};IstanbulToFootprintsConvertorV3.prototype.addOrUpdateMethodElement=function(scopeData,methodData,hits){var loc=methodData.loc||methodData.lc;var decl=methodData.decl||methodData.d;this.addOrUpdateElement(scopeData,loc,hits,this.getOrCreateMethodElement,false);if(decl){this.addOrUpdateElement(scopeData,decl,hits,this.getOrCreateMethodElement,false)}};IstanbulToFootprintsConvertorV3.prototype.addOrUpdateBranchElement=function(scopeData,branchData,probeIndex,hits){var locations=branchData.locations||branchData.lcs;var probePositionData=locations[probeIndex];this.addOrUpdateElement(scopeData,probePositionData,hits,this.getOrCreateBranchElement,true,probeIndex)};IstanbulToFootprintsConvertorV3.prototype.addOrUpdateElement=function(scopeData,startPositionData,hits,getOrCreateElement,isBranch,probIndex){var file=this.getOrCreateFootprintsAppFile(scopeData.modulePath,scopeData.app);var startPosition=startPositionData.start||startPositionData.st;var uniqueId=this.createUniqueId(startPosition,scopeData.modulePath,isBranch,probIndex);if(!uniqueId){return}var element=getOrCreateElement.call(this,uniqueId,file);this.addOrUpdateElementHits(scopeData.test,uniqueId,element,hits)};IstanbulToFootprintsConvertorV3.prototype.createUniqueId=function(startPosition,fullFilePath,isBranch,probIndex){var delimiter=isBranch?"|":"@";var uniqueId=fullFilePath+delimiter+this.formatLoc(startPosition);if(probIndex!=null){uniqueId+="|"+probIndex}var mapping=this.window.slMappings[this.cfg.buildSessionId];if(mapping){uniqueId=mapping[uniqueId]||uniqueId}return uniqueId};IstanbulToFootprintsConvertorV3.prototype.addOrUpdateElementHits=function(testData,elementUniqueId,element,hits){var HITS_INDEX=1;var eid=elementUniqueId+"|"+testData.index;var index=this.eidToHitsIndex[eid];if(index!=null){var testIndexAndHits=element.hits[index];var elementHits=testIndexAndHits[HITS_INDEX];elementHits=elementHits+hits;testIndexAndHits[HITS_INDEX]=elementHits}else{var testIndexAndHits=new Array;testIndexAndHits.push(testData.index);testIndexAndHits.push(hits);var length_1=element.hits.push(testIndexAndHits);this.eidToHitsIndex[eid]=length_1-1}};IstanbulToFootprintsConvertorV3.prototype.getOrCreateTestData=function(testName,executionId,localTime,result){if(!this.testNameToTestData[testName]){var test_1={executionId:executionId,localTime:localTime,testName:testName,collectionInterval:this.collectionInterval.toJson()};result.tests.push(test_1);this.testNameToTestData[testName]={index:this.totalTests++,test:test_1}}return this.testNameToTestData[testName]};IstanbulToFootprintsConvertorV3.prototype.getOrCreateMethodElement=function(uniqueId,file){if(!this.uniqueIdToElement[uniqueId]){var x={hits:new Array,uniqueId:uniqueId};this.uniqueIdToElement[uniqueId]=x;file.methods.push(x)}return this.uniqueIdToElement[uniqueId]};IstanbulToFootprintsConvertorV3.prototype.getOrCreateBranchElement=function(uniqueId,file){if(!this.uniqueIdToElement[uniqueId]){var x={hits:new Array,uniqueId:uniqueId};this.uniqueIdToElement[uniqueId]=x;if(file.branches)file.branches.push(x)}return this.uniqueIdToElement[uniqueId]};IstanbulToFootprintsConvertorV3.prototype.getOrCreateFootprintsAppFile=function(fileName,app){if(this.fileNameToAppFile[fileName]){return this.fileNameToAppFile[fileName]}var file={methods:new Array,branches:new Array,lines:new Array,path:fileName};app.files.push(file);this.fileNameToAppFile[fileName]=file;return file};IstanbulToFootprintsConvertorV3.prototype.createFootprintsFile=function(){var result={configurationData:{},customerId:this.cfg.customerId,environment:{},tests:[],apps:[],meta:{}};this.fileNameToAppFile={};this.testNameToTestData={};var app={appName:this.cfg.appName,branchName:this.cfg.branchName,buildName:this.cfg.buildName,moduleName:"",buildSessionId:this.cfg.buildSessionId,files:new Array};result.apps.push(app);return result};IstanbulToFootprintsConvertorV3.prototype.formatLoc=function(loc){return location_formatter_1.formatLocation(loc,this.logger)};return IstanbulToFootprintsConvertorV3}();exports.IstanbulToFootprintsConvertorV3=IstanbulToFootprintsConvertorV3})},{"../../common/footprints-process-v6/location-formatter":321,"../../common/footprints-process/collection-interval":323,"../../common/system-date":332,"./logger/log-factory":272}],269:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.IstanbulToFootprintsConverter=void 0;var utils_1=require("./utils");var IstanbulToFootprintsConverter=function(){function IstanbulToFootprintsConverter(window,configuration){this.window=window;this.configuration=configuration;if(configuration==null)throw new Error("'configuration' cannot be null or undefined")}IstanbulToFootprintsConverter.prototype.convert=function(istanbulFootprints){var apps={};var appsArray=new Array;if(istanbulFootprints){var context_1=this;Object.keys(istanbulFootprints).forEach(function(moduleName){var m=istanbulFootprints[moduleName];context_1.configuration.appName=context_1.configuration.appName||"";var a=apps[context_1.configuration.appName];var isNewApp=false;if(!a){a={appName:context_1.configuration.appName,build:context_1.configuration.buildName,branch:context_1.configuration.branchName,footprints:[]};isNewApp=true}var footprints=a.footprints;var filename=m.path;filename=filename.replace(/\\/g,"/");Object.keys(m.f).forEach(function(funcId){var funcInfo=m.fnMap[funcId];if(!funcInfo||funcInfo.skip)return;if(m.f[funcId]>0){var mn=context_1.getMethodName(funcInfo.name,funcInfo.guessedName);var pos=context_1.formatLoc(funcInfo.loc.originalStart||funcInfo.loc.start);if(m.inputSourceMap&&context_1.window["sourceMap"]){var sourceMapConsumer=new context_1.window["sourceMap"].SourceMapConsumer(m.inputSourceMap);pos=context_1.formatLoc(sourceMapConsumer.originalPositionFor(funcInfo.loc.start))}filename=funcInfo.originalFilename||filename;filename=context_1.getRelativeModulePath(filename);var fqmn=[mn,filename,pos].join("@");var hash=funcInfo.hash&&funcInfo.hash.hash;var footprintsItem_1={name:fqmn,hits:m.f[funcId],hash:hash,branches:new Array};if(m.fnToBranch&&m.fnToBranch[funcId]&&m.fnToBranch[funcId].length){m.fnToBranch[funcId].forEach(function(branchArray,index){var fileBranch=branchArray[0];var branchIndex=branchArray[1];if(m.b[fileBranch.toString()][branchIndex]>0){footprintsItem_1.branches.push(index)}})}footprints.push(footprintsItem_1)}});if(footprints.length&&isNewApp){appsArray.push(a);apps[a.appName]=a}})}return appsArray};IstanbulToFootprintsConverter.prototype.getMethodName=function(name,guessedName){var mn=name||guessedName||"(Anonymous)";if(mn.indexOf("(anonymous")>=0){mn="(Anonymous)"}return mn};IstanbulToFootprintsConverter.prototype.formatLoc=function(loc){return[loc.line,loc.column].join(",")};IstanbulToFootprintsConverter.prototype.getRelativeModulePath=function(path){var workspacepath=utils_1.Utils.adjustPathSlashes(this.configuration.workspacepath);path=utils_1.Utils.adjustPathSlashes(path);if(workspacepath){return path.replace(workspacepath,"")}return path};return IstanbulToFootprintsConverter}();exports.IstanbulToFootprintsConverter=IstanbulToFootprintsConverter})},{"./utils":286}],270:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./browser-agent-instance","../../common/utils/validation-utils","../../common/events-process/events-creator","../../common/events-process/events-contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.KarmaHandler=void 0;var browser_agent_instance_1=require("./browser-agent-instance");var validation_utils_1=require("../../common/utils/validation-utils");var events_creator_1=require("../../common/events-process/events-creator");var events_contracts_1=require("../../common/events-process/events-contracts");var KarmaHandler=function(){function KarmaHandler(window,agent,logger){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(window,"window");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agent,"agent");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this.window=window;this.agent=agent;this.logger=logger}KarmaHandler.prototype.overrideKarmaMethods=function(){if(!this.window.__karma__){this.logger.warn("Could not find '__karma__' object on window, skip overriding methods");return}var that=this;var originalResult=this.window.__karma__.result;var originalComplete=this.window.__karma__.complete;this.window.__karma__.result=function(resultObject){var testResult=that.resolveTestResult(resultObject);var testStartEvent=events_creator_1.EventsCreator.createTestStartedEvent(browser_agent_instance_1.BrowserAgentInstance.getExecutionId(),"karma",resultObject.fullName,resultObject.time);var testEndEvent=events_creator_1.EventsCreator.createTestEndEvent(browser_agent_instance_1.BrowserAgentInstance.getExecutionId(),"karma",resultObject.fullName,testResult,resultObject.time);that.agent.enqueueEvent(testStartEvent);that.agent.enqueueEvent(testEndEvent);var currentTestIdentifier=browser_agent_instance_1.BrowserAgentInstance.getExecutionId()+"/"+resultObject.fullName;that.agent.setCurrentTestIdentifier(currentTestIdentifier);if(originalResult instanceof Function){originalResult.apply(this,arguments)}};this.window.__karma__.complete=function(){var executionEndEvent=events_creator_1.EventsCreator.createEvent(events_contracts_1.EventTypes.ExecutionIdEnded,browser_agent_instance_1.BrowserAgentInstance.getExecutionId(),"karma");that.agent.enqueueEvent(executionEndEvent);that.agent.stop();if(originalComplete instanceof Function){originalComplete.apply(this,arguments)}}};KarmaHandler.prototype.start=function(){var agentStartedEvent=events_creator_1.EventsCreator.createEvent(events_contracts_1.EventTypes.AgentStarted,browser_agent_instance_1.BrowserAgentInstance.getExecutionId(),"karma");var executionStartedEvent=events_creator_1.EventsCreator.createEvent(events_contracts_1.EventTypes.ExecutionIdStarted,browser_agent_instance_1.BrowserAgentInstance.getExecutionId(),"karma");this.agent.enqueueEvent(agentStartedEvent);this.agent.enqueueEvent(executionStartedEvent)};KarmaHandler.prototype.resolveTestResult=function(result){if(result.skipped){return"skipped"}if(result.success){return"passed"}return"failed"};return KarmaHandler}();exports.KarmaHandler=KarmaHandler})},{"../../common/events-process/events-contracts":312,"../../common/events-process/events-creator":313,"../../common/utils/validation-utils":336,"./browser-agent-instance":250}],271:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../../common/system-date","../configuration-override"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConsoleLogger=exports.LogLevels=void 0;var system_date_1=require("../../../common/system-date");var configuration_override_1=require("../configuration-override");var LogLevels;(function(LogLevels){LogLevels["TRACE"]="trace";LogLevels["DEBUG"]="debug";LogLevels["INFO"]="info";LogLevels["WARNING"]="warning";LogLevels["ERROR"]="error";LogLevels["CRITICAL"]="critical";LogLevels["FATAL"]="fatal"})(LogLevels=exports.LogLevels||(exports.LogLevels={}));var ConsoleLogger=function(){function ConsoleLogger(level,selectedLogLevels){if(level===void 0){level=LogLevels.INFO}if(selectedLogLevels===void 0){selectedLogLevels=null}var _a,_b;this.level=level;this.selectedLogLevels=selectedLogLevels;this.logFn=function(){};this.stringifyFn=function(o){return""};this.context={};(_b=(_a=window.$Sealights)===null||_a===void 0?void 0:_a.configuration)===null||_b===void 0?void 0:_b.on(configuration_override_1.ConfigChangedEvents.LOG_LEVEL_CHANGED,this.initLogLevels.bind(this));if(!selectedLogLevels)this.initLogLevels(level);this.initStringifyFn();this.initLogFn()}ConsoleLogger.prototype.withLogLevel=function(level){var c=new ConsoleLogger(this.level);c.context=this.context;return c};ConsoleLogger.prototype.initLogFn=function(){var _this=this;if(console&&typeof console.log=="function"){this.logFn=function(o){var line=_this.stringifyFn(o);console.log(line)}}else{}};ConsoleLogger.prototype.initStringifyFn=function(){if(JSON&&typeof JSON.stringify=="function"){this.stringifyFn=JSON.stringify}else{this.stringifyFn=this.crudeStringifier}};ConsoleLogger.prototype.crudeStringifier=function(o){var strParts=Array();for(var p in o){strParts.push(p+"="+o[p].toString())}return strParts.join(", ")};ConsoleLogger.prototype.initLogLevels=function(level){var orderedLogLevels=[LogLevels.TRACE,LogLevels.DEBUG,LogLevels.INFO,LogLevels.WARNING,LogLevels.ERROR,LogLevels.CRITICAL,LogLevels.FATAL];var logLevel=level.toLowerCase();var minIdx=orderedLogLevels.indexOf(logLevel);if(minIdx===-1){this.handleLevelNotFound(level)}else{this.selectedLogLevels={};for(var i=0;i<orderedLogLevels.length;i++){this.selectedLogLevels[orderedLogLevels[i]]=i>=minIdx}}};ConsoleLogger.prototype.handleLevelNotFound=function(logLevel){if(logLevel=="off"){this.selectedLogLevels={}}};ConsoleLogger.prototype.internalLog=function(logLevel,logMsg,obj){if(!this.selectedLogLevels||!this.selectedLogLevels[logLevel])return;var logObject={level:logLevel.toUpperCase(),ts:system_date_1.getSystemDate().toISOString(),msg:logMsg?logMsg.toString():undefined};var ctx=this.context;for(var p in ctx){logObject[p]=ctx[p]}if(obj){if(obj instanceof Error){logObject.error=obj.toString()}else if(obj instanceof Object){for(var p in obj){logObject[p]=obj[p]}}else{logObject.data=obj}}this.logFn(logObject)};ConsoleLogger.prototype.clone=function(){var c=new ConsoleLogger(this.level,this.selectedLogLevels);var _t=this.context;for(var p in _t){c.context[p]=_t[p]}return c};ConsoleLogger.prototype.withClass=function(className){var c=this.clone();c.context.className=className;delete c.context.methodName;return c};ConsoleLogger.prototype.withMethod=function(methodName){var c=this.clone();c.context.methodName=methodName;return c};ConsoleLogger.prototype.withTx=function(tx){var c=this.clone();c.context.tx=tx;return c};ConsoleLogger.prototype.withComponent=function(componentName,componentVersion){var c=this.clone();c.context.componentName=componentName;c.context.componentVersion=componentVersion;return c};ConsoleLogger.prototype.withActivity=function(activityName){var c=this.clone();c.context.activityName=activityName;return c};ConsoleLogger.prototype.withProperty=function(propName,propValue){var c=this.clone();c.context[propName]=propValue;return c};ConsoleLogger.prototype.withProperties=function(objWithProperties,propNames){var c=this.clone();if(!propNames){propNames=Object.keys(objWithProperties)}propNames.forEach(function(pn){c.context[pn]=objWithProperties[pn]});return c};ConsoleLogger.prototype.fatal=function(logMsg,obj){this.internalLog(LogLevels.FATAL,logMsg,obj)};ConsoleLogger.prototype.critical=function(logMsg,obj){this.internalLog(LogLevels.CRITICAL,logMsg,obj)};ConsoleLogger.prototype.error=function(logMsg,obj){this.internalLog(LogLevels.ERROR,logMsg,obj)};ConsoleLogger.prototype.warn=function(logMsg,obj){this.internalLog(LogLevels.WARNING,logMsg,obj)};ConsoleLogger.prototype.info=function(logMsg,obj){this.internalLog(LogLevels.INFO,logMsg,obj)};ConsoleLogger.prototype.debug=function(logMsg,obj){this.internalLog(LogLevels.DEBUG,logMsg,obj)};ConsoleLogger.prototype.trace=function(logMsg,obj){this.internalLog(LogLevels.TRACE,logMsg,obj)};return ConsoleLogger}();exports.ConsoleLogger=ConsoleLogger})},{"../../../common/system-date":332,"../configuration-override":259}],272:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./null-logger","./console-logger"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.LogFactory=void 0;var null_logger_1=require("./null-logger");var console_logger_1=require("./console-logger");var LogFactory=function(){function LogFactory(){}LogFactory.createLogger=function(className,logLevel){try{var logger=new console_logger_1.ConsoleLogger(logLevel);logger.withClass(className);return logger}catch(e){return null_logger_1.NullLogger.INSTANCE}};return LogFactory}();exports.LogFactory=LogFactory})},{"./console-logger":271,"./null-logger":273}],273:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NullLogger=void 0;var NullLogger=function(){function NullLogger(){}NullLogger.prototype.fatal=function(logMsg,obj){};NullLogger.prototype.critical=function(logMsg,obj){};NullLogger.prototype.error=function(logMsg,obj){};NullLogger.prototype.warn=function(logMsg,obj){};NullLogger.prototype.info=function(logMsg,obj){};NullLogger.prototype.debug=function(logMsg,obj){};NullLogger.prototype.trace=function(logMsg,obj){};NullLogger.prototype.withClass=function(className){return NullLogger.INSTANCE};NullLogger.prototype.withMethod=function(methodName){return NullLogger.INSTANCE};NullLogger.prototype.withTx=function(tx){return NullLogger.INSTANCE};NullLogger.prototype.withComponent=function(componentName,componentVersion){return NullLogger.INSTANCE};NullLogger.prototype.withActivity=function(activityName){return NullLogger.INSTANCE};NullLogger.prototype.withProperty=function(propName,propValue){return NullLogger.INSTANCE};NullLogger.prototype.withProperties=function(objWithProperties,propNames){return NullLogger.INSTANCE};NullLogger.prototype.withLogLevel=function(level){return NullLogger.INSTANCE};NullLogger.INSTANCE=new NullLogger;return NullLogger}();exports.NullLogger=NullLogger})},{}],274:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../entities/footprints-item-data","../delegate","../../../common/system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsItemsQueue=void 0;var footprints_item_data_1=require("../entities/footprints-item-data");var delegate_1=require("../delegate");var system_date_1=require("../../../common/system-date");var FootprintsItemsQueue=function(){function FootprintsItemsQueue(configuration){this.maxItemsInQueue=500;this.queueSize=0;this.queue=new Array;this.onQueueFull=new delegate_1.Delegate;this.isQueueFull=function(){return this.getCurrentQueueSize()>=this.maxItemsInQueue};if(!configuration)throw new Error("'configuration' cannot be null or undefined");this.enabled=configuration.enabled;this.maxItemsInQueue=configuration.maxItemsInQueue}FootprintsItemsQueue.prototype.setEnabled=function(isEnabled){isEnabled=!!isEnabled;if(isEnabled!==this.enabled){this.enabled=isEnabled}if(!isEnabled){this.queue=new Array}};FootprintsItemsQueue.prototype.getEnabled=function(){return this.enabled};FootprintsItemsQueue.prototype.enqueueItem=function(footprintsItem){if(!this.enabled){return}footprintsItem=footprintsItem||new footprints_item_data_1.FootprintsItemData;footprintsItem.localTime=system_date_1.getSystemDateValueOf();this.queue.push(footprintsItem);this.queueSize++;this.checkQueueSize()};FootprintsItemsQueue.prototype.checkQueueSize=function(){if(this.isQueueFull()){this.onQueueFull.fire()}};FootprintsItemsQueue.prototype.getCurrentQueueSize=function(){return this.queueSize};FootprintsItemsQueue.prototype.requeueItems=function(footprintsItems){if(!this.enabled){return}var context=this;footprintsItems.forEach(function(item){context.queue.push(item);context.queueSize+=1});this.checkQueueSize()};FootprintsItemsQueue.prototype.getQueueContentsAndEmptyQueue=function(){var returnedItems=this.queue;this.queue=new Array;this.queueSize=0;return returnedItems};return FootprintsItemsQueue}();exports.FootprintsItemsQueue=FootprintsItemsQueue})},{"../../../common/system-date":332,"../delegate":261,"../entities/footprints-item-data":265}],275:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../../common/utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Queue=void 0;var validation_utils_1=require("../../../common/utils/validation-utils");var Queue=function(){function Queue(onQueueFull){this.queue=[];this._maxItemsInQueue=Queue.DEFAULT_MAX_ITEMS_IN_QUEUE;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(onQueueFull,"onQueueFull");this.onQueueFull=onQueueFull}Queue.prototype.requeue=function(items){if(!items||!items.length){return}this.queue=items.concat(this.queue)};Queue.prototype.enqueue=function(item){this.queue.push(item);if(this._maxItemsInQueue===this.queue.length){this.onQueueFull.fire()}};Queue.prototype.getQueueSize=function(){return this.queue.length};Queue.prototype.dequeue=function(size){if(!size){size=this.queue.length}if(this.queue.length===0){return[]}if(size>this.queue.length){size=this.queue.length}var dequeuedItems=this.queue.splice(0,size);return dequeuedItems};Queue.prototype.clear=function(){this.queue=[]};Queue.prototype.on=function(event,listener){this.onQueueFull.addListener(listener);return this};Object.defineProperty(Queue.prototype,"maxItemsInQueue",{get:function(){return this._maxItemsInQueue},set:function(value){this._maxItemsInQueue=value},enumerable:false,configurable:true});Queue.DEFAULT_MAX_ITEMS_IN_QUEUE=1e3;return Queue}();exports.Queue=Queue})},{"../../../common/utils/validation-utils":336}],276:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./http-response"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpClient=void 0;var http_response_1=require("./http-response");var HttpClient=function(){function HttpClient(window,featureDetection,logger){this.window=window;this.featureDetection=featureDetection;this.logger=logger;if(window==null)throw new Error("'window' cannot be null or undefined");if(featureDetection==null)throw new Error("'featureDetection' cannot be null or undefined")}HttpClient.prototype.send=function(request,onSuccess,onError){if(!request.url)return;var url=request.url;var httpMethod=request.httpMethod;var httpRequest=new XMLHttpRequest;httpRequest.open(httpMethod,url,request.async);if(request.headers){for(var i=0;i<request.headers.length;i++){var header=request.headers[i];if(header&&header.name&&header.value){httpRequest.setRequestHeader(header.name,header.value)}}}httpRequest.onreadystatechange=function(){if(httpRequest.readyState===XMLHttpRequest.DONE){var httpResponse=new http_response_1.HttpResponse;httpResponse.statusCode=httpRequest.status;httpResponse.responseText=httpRequest.responseText;if(httpRequest.status===200){if(onSuccess){onSuccess(httpResponse)}}else{if(onError){onError(httpResponse)}}}};httpRequest.send(request.data)};return HttpClient}();exports.HttpClient=HttpClient})},{"./http-response":278}],277:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpRequest=void 0;var HttpRequest=function(){function HttpRequest(){this.async=true}return HttpRequest}();exports.HttpRequest=HttpRequest})},{}],278:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpResponse=void 0;var HttpResponse=function(){function HttpResponse(){}return HttpResponse}();exports.HttpResponse=HttpResponse})},{}],279:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../../../common/utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.JsonClientAdapter=void 0;var validation_utils_1=require("../../../../common/utils/validation-utils");var JsonClientAdapter=function(){function JsonClientAdapter(jsonClient,serverUrl){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(jsonClient,"jsonClient");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(serverUrl,"serverUrl");this.jsonClient=jsonClient;this.serverUrl=serverUrl}JsonClientAdapter.prototype.delete=function(body,urlPath,callback){throw new Error("'delete' not implemented yet")};JsonClientAdapter.prototype.get=function(urlPath,callback,isNotFoundAcceptable,async){if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}if(async===void 0){async=false}urlPath=this.serverUrl+urlPath;var onSuccess=function(response){return callback(null,response,response.statusCode)};var onError=function(response){var error=new Error(response.responseText);callback(error,null,response.statusCode)};this.jsonClient.get(urlPath,onSuccess,onError,async)};JsonClientAdapter.prototype.put=function(requestData,urlPath,callback,async){if(async===void 0){async=true}throw new Error("'delete' not implemented yet")};JsonClientAdapter.prototype.post=function(requestData,urlPath,callback,async,contentType){if(async===void 0){async=true}urlPath=this.serverUrl+urlPath;var onSuccess=function(response){return callback(null,response,response.statusCode)};var onError=function(response){var error=new Error(response.responseText);callback(error,null,response.statusCode)};this.jsonClient.post(urlPath,requestData,onSuccess,onError,async,contentType)};JsonClientAdapter.prototype.postMultipart=function(requestData,urlPath,callback){throw new Error("'postMultipart' not implemented yet")};return JsonClientAdapter}();exports.JsonClientAdapter=JsonClientAdapter})},{"../../../../common/utils/validation-utils":336}],280:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../http/http-request","../../../../common/http/contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.JsonClient=void 0;var http_request_1=require("../http/http-request");var contracts_1=require("../../../../common/http/contracts");var JsonClient=function(){function JsonClient(httpClient,token){this.httpClient=httpClient;this.token=token;this.requestsInProgress=0;this.requestsInProgress=0}JsonClient.prototype.sendHttpRequest=function(request,onSuccess,onError,contentType){var context=this;try{this.requestsInProgress++;var httpRequest=new http_request_1.HttpRequest;httpRequest.headers=this.getHeaders(contentType);httpRequest.url=request.url;httpRequest.httpMethod=request.httpMethod;httpRequest.async=request.async;if(request.data!=null)httpRequest.data=JSON.stringify(request.data);this.httpClient.send(httpRequest,parseResponse,function(response){context.requestsInProgress--;if(onError!=null){onError(response)}})}catch(e){this.requestsInProgress--}function parseResponse(jsonResponse){try{var object=void 0;context.requestsInProgress--;if(jsonResponse&&jsonResponse.responseText&&jsonResponse.responseText!=""){object=JSON.parse(jsonResponse.responseText)}else{object=jsonResponse}if(onSuccess!=null){onSuccess(object)}}catch(e){if(onError!=null){jsonResponse.responseText="Failed parsing response. Response: '"+jsonResponse.responseText+"'";onError(jsonResponse)}}}};JsonClient.prototype.post=function(url,data,onSuccess,onError,async,contentType){if(async===void 0){async=true}this.send(url,data,onSuccess,onError,async,"POST",contentType)};JsonClient.prototype.get=function(url,onSuccess,onError,async,data){if(async===void 0){async=true}this.send(url,data,onSuccess,onError,async,"GET")};JsonClient.prototype.send=function(url,data,onSuccess,onError,async,httpMethod,contentType){if(async===void 0){async=true}var request=new http_request_1.HttpRequest;request.url=url;request.data=data;request.httpMethod=httpMethod;request.async=async;this.sendHttpRequest(request,onSuccess,onError,contentType)};JsonClient.prototype.hasRequestsInProgress=function(){return this.requestsInProgress>0}
27
- ;JsonClient.prototype.getHeaders=function(contentType){var headers=[{name:"Content-Type",value:contentType||contracts_1.ContentType.JSON}];if(this.token){headers.push({name:"Authorization",value:"Bearer "+this.token})}return headers};return JsonClient}();exports.JsonClient=JsonClient})},{"../../../../common/http/contracts":325,"../http/http-request":277}],281:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./json-client","../../logger/log-factory"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NoopJsonClient=void 0;var json_client_1=require("./json-client");var log_factory_1=require("../../logger/log-factory");var NoopJsonClient=function(_super){__extends(NoopJsonClient,_super);function NoopJsonClient(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.logger=log_factory_1.LogFactory.createLogger("NoopJsonClient");return _this}NoopJsonClient.prototype.send=function(url,data,onSuccess,onError,async,httpMethod,contentType){if(async===void 0){async=true}this.logger.info("noop json client not executing http request for url '"+url);onSuccess({})};return NoopJsonClient}(json_client_1.JsonClient);exports.NoopJsonClient=NoopJsonClient})},{"../../logger/log-factory":272,"./json-client":280}],282:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.LightBackendProxy=void 0;var LightBackendProxy=function(){function LightBackendProxy(configuration,jsonClient,logger){this.configuration=configuration;this.jsonClient=jsonClient;this.logger=logger}LightBackendProxy.prototype.submitRequest=function(request,onSuccess,onError,async){if(async===void 0){async=true}var url=this.createServerUrl(this.configuration);this.jsonClient.post(url,request,onSuccess,onError,async)};LightBackendProxy.prototype.hasRequestsInProgress=function(){return this.jsonClient.hasRequestsInProgress()};LightBackendProxy.prototype.getRequestsInProgressCount=function(){return this.jsonClient.requestsInProgress};LightBackendProxy.prototype.getSlMappingFromServer=function(buildSessionId){var _this=this;var url=[this.configuration.server,"v1","agents","blobs",buildSessionId].join("/")+"?view=concatJson";url=encodeURI(url);return new Promise(function(resolve,reject){_this.jsonClient.get(url,resolve,reject,false)})};LightBackendProxy.prototype.createServerUrl=function(configuration){if(configuration.token){var apiVersion=configuration.resolveWithoutHash?"/v5":"/v3";return configuration.server+apiVersion+"/agents/footprints/"}return configuration.server+"/v1/testfootprints/"};return LightBackendProxy}();exports.LightBackendProxy=LightBackendProxy})},{}],283:[function(require,module,exports){var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/agent-events/cockpit-notifier"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SlMappingLoader=void 0;var cockpit_notifier_1=require("../../common/agent-events/cockpit-notifier");var SlMappingLoader=function(){function SlMappingLoader(lightBackendProxy,window,logger){this.lightBackendProxy=lightBackendProxy;this.window=window;this.logger=logger}SlMappingLoader.prototype.loadSlMapping=function(buildSessionId){return __awaiter(this,void 0,void 0,function(){var flatted_1,slMappingArr,err_1,errMsg;return __generator(this,function(_a){switch(_a.label){case 0:this.window.slMappings=this.window.slMappings||{};if(!!this.window.slMappings[buildSessionId])return[3,4];_a.label=1;case 1:_a.trys.push([1,3,,4]);flatted_1={};return[4,this.lightBackendProxy.getSlMappingFromServer(buildSessionId)];case 2:slMappingArr=_a.sent();slMappingArr.forEach(function(mapping){flatted_1=__assign(__assign({},flatted_1),mapping)});this.window.slMappings[buildSessionId]=flatted_1;return[3,4];case 3:err_1=_a.sent();errMsg="Error while trying to load slMapping from server '"+err_1+"'";this.logger.error(errMsg);cockpit_notifier_1.CockpitNotifier.sendGenericMessage(errMsg);this.window.slMappings[buildSessionId]={};return[3,4];case 4:return[2]}})})};return SlMappingLoader}();exports.SlMappingLoader=SlMappingLoader})},{"../../common/agent-events/cockpit-notifier":294}],284:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./delegate","./contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StateTracker=void 0;var delegate_1=require("./delegate");var contracts_1=require("./contracts");var StateTracker=function(){function StateTracker(configuration,jsonClient,watchdog,logger){var _this=this;this.configuration=configuration;this.jsonClient=jsonClient;this.watchdog=watchdog;this.logger=logger;this.colorChanged=new delegate_1.Delegate;this.setCurrentTestIdentifier(StateTracker.ANONYMOUS_FOOTPRINTS_COLOR);this.watchdog.addOnAlarmListener(function(){_this.checkForActiveExecution()});this.checkForActiveExecution(false);this.watchdog.start()}StateTracker.prototype.setCurrentTestIdentifier=function(newColorOnWindow){if(newColorOnWindow!=null){if(newColorOnWindow!=StateTracker.ANONYMOUS_FOOTPRINTS_COLOR){this.stopWatchdog()}else{this.startWatchdog()}if(newColorOnWindow!=this.currentColorOnWindow){this.currentColorOnWindow=newColorOnWindow;this.colorChanged.fire()}}else if(this.currentColorOnWindow!=null&&newColorOnWindow==null){this.currentColorOnWindow=null;this.colorChanged.fire()}};StateTracker.prototype.getCurrentTestIdentifier=function(){return this.currentColorOnWindow};StateTracker.prototype.addOnColorChangedListener=function(listener){this.colorChanged.addListener(listener)};StateTracker.prototype.getCurrentColor=function(){return this.currentColorOnWindow};StateTracker.prototype.checkForActiveExecution=function(async){var _this=this;if(async===void 0){async=true}var url=this.configuration.server+("/v4/testExecution/"+this.configuration.labId);this.logger.info("[TO TST] - checkMappingStatus. Url '"+url+"'.");var onSuccess=function(data){_this.logger.info("[ACTIVE EXECUTION] Checking for active execution. No errors");if(data==null){_this.logger.warn("[ACTIVE EXECUTION] Received empty response. not sending footprints.");_this.hasActiveExecution=false;return}if(data.execution==null){_this.logger.info("[ACTIVE EXECUTION] Couldn't find active execution. not sending footprints.");_this.hasActiveExecution=false}else if(data.execution.status==contracts_1.ExecutionStatus.Ending){_this.logger.info("[ACTIVE EXECUTION] Execution is pending delete. sending last footprints");_this.hasActiveExecution=true}else if(data.execution.status==contracts_1.ExecutionStatus.InProgress){_this.logger.info("[ACTIVE EXECUTION] Active execution for labid '"+_this.configuration.labId+"'");_this.hasActiveExecution=true}else{_this.logger.warn("[ACTIVE EXECUTION] Unexpected status. status: ",data.execution.status);_this.hasActiveExecution=false}};var onError=function(response){_this.logger.error("[ACTIVE EXECUTION] Error checking for active execution: %s",response.responseText);_this.hasActiveExecution=false};this.jsonClient.get(url,onSuccess,onError,async)};StateTracker.prototype.shouldCollectFootprints=function(){if(this.getCurrentColor()==null){this.logger.info("Current test identifier is null, should not collect footprints");return false}if(this.getCurrentColor()!=StateTracker.ANONYMOUS_FOOTPRINTS_COLOR){this.logger.info("Not in anonymous footprints, should collect footprints");return true}if(this.hasActiveExecution){this.logger.info("Has active execution, should collect footprints");return true}this.logger.info("No active execution, should not collect footprints");return false};StateTracker.prototype.setActiveExecution=function(value){this.hasActiveExecution=value};StateTracker.prototype.stopWatchdog=function(){if(this.watchdog.getStatus().running){this.watchdog.stop()}};StateTracker.prototype.startWatchdog=function(){if(!this.watchdog.getStatus().running){this.watchdog.start()}};StateTracker.ANONYMOUS_FOOTPRINTS_COLOR="00000000-0000-0000-0000-000000000000/__init";return StateTracker}();exports.StateTracker=StateTracker})},{"./contracts":260,"./delegate":261}],285:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TestStateHelper=void 0;var TestStateHelper=function(){function TestStateHelper(){this.combineExecutionIdAndTestName=function(executionId,testName){testName=testName||"";if(!executionId)return"";return executionId+"/"+testName};this.splitTestIdToExecutionAndTestName=function(testId){testId=testId||"";var executionId=testId.split("/")[0];var testName=testId.indexOf("/")==-1?"":testId.substring(executionId.length+1);if(!executionId)testName="";return{executionId:executionId,testName:testName}}}return TestStateHelper}();exports.TestStateHelper=TestStateHelper})},{}],286:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","path"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Utils=void 0;var path=require("path");var Utils=function(){function Utils(){}Utils.adjustPathSlashes=function(path){path=(path||"").replace(/\\/g,"/");return path};Utils.getRelativeModulePath=function(path,workspacepath){workspacepath=Utils.adjustPathSlashes(workspacepath);path=Utils.adjustPathSlashes(path);if(workspacepath){return path.replace(workspacepath,"")}return path};Utils.resolveOriginalFullFileName=function(fullPath,originalFilename){if(path.isAbsolute(originalFilename)){return originalFilename}var generatedDir=path.dirname(fullPath);originalFilename=path.resolve(generatedDir,originalFilename);return originalFilename};Utils.parseBooleanValue=function(value){if(value&&typeof value=="boolean"){return value}if(value&&typeof value=="string"){return value.toLowerCase()=="true"}return false};return Utils}();exports.Utils=Utils})},{path:171}],287:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./delegate"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Watchdog=void 0;var delegate_1=require("./delegate");var Watchdog=function(){function Watchdog(timeout,timersWrapper,options,logger){this.timeout=timeout;this.timersWrapper=timersWrapper;this.options=options;this.logger=logger;this.handle=null;this.alarm=new delegate_1.Delegate;this.context=this;this.stopped=false;this.options=options||{}}Watchdog.prototype.abortTimer=function(){if(this.handle){this.timersWrapper.clearTimeout(this.handle);this.handle=null}};Watchdog.prototype.fireAlarm=function(){this.handle=null;try{this.alarm.fire()}catch(e){this.logger.error("Alarm caught an exception: %s",e)}if(this.options.autoReset){this.context.reset()}};Watchdog.prototype.addOnAlarmListener=function(listener){this.alarm.addListener(listener)};Watchdog.prototype.reset=function(){var _this=this;this.abortTimer();if(!this.stopped){this.handle=this.timersWrapper.setTimeout(function(){_this.fireAlarm()},this.timeout)}};Watchdog.prototype.stop=function(){this.stopped=true;this.abortTimer()};Watchdog.prototype.start=function(){this.stopped=false;this.reset()};Watchdog.prototype.getStatus=function(){return{running:!this.stopped}};Watchdog.prototype.on=function(event,listener){this.addOnAlarmListener(listener)};Watchdog.prototype.setInterval=function(newInterval){if(newInterval<=0)throw new Error("Invalid value for interval: "+newInterval);this.timeout=newInterval};return Watchdog}();exports.Watchdog=Watchdog})},{"./delegate":261}],288:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.WindowTimersWrapper=void 0;var WindowTimersWrapper=function(){function WindowTimersWrapper(window){this.window=window;if(!this.window)throw new Error("'window' cannot be null or undefined")}WindowTimersWrapper.prototype.clearInterval=function(handle){this.window.clearInterval(handle)};WindowTimersWrapper.prototype.clearTimeout=function(handle){this.window.clearTimeout(handle)};WindowTimersWrapper.prototype.setInterval=function(handler,timeout){var args=[];for(var _i=2;_i<arguments.length;_i++){args[_i-2]=arguments[_i]}return this.window.setInterval(handler,timeout,args)};WindowTimersWrapper.prototype.setTimeout=function(handler,timeout){var args=[];for(var _i=2;_i<arguments.length;_i++){args[_i-2]=arguments[_i]}return this.window.setTimeout(handler,timeout,args)};return WindowTimersWrapper}();exports.WindowTimersWrapper=WindowTimersWrapper})},{}],289:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Technology=exports.AgentEventCode=exports.AgentType=void 0;var AgentType;(function(AgentType){AgentType["BUILD_SCANNER"]="BuildScanner";AgentType["TEST_LISTENER"]="TestListener";AgentType["PRODUCTION_LISTENER"]="ProductionListener";AgentType["BROWSER_AGENT"]="BrowserAgent";AgentType["SLNODEJS"]="slnodejs"})(AgentType=exports.AgentType||(exports.AgentType={}));var AgentEventCode;(function(AgentEventCode){AgentEventCode[AgentEventCode["GENERIC_AGENT_EVENT"]=1e3]="GENERIC_AGENT_EVENT";AgentEventCode[AgentEventCode["AGENT_STARTED"]=1001]="AGENT_STARTED";AgentEventCode[AgentEventCode["AGENT_SHUTDOWN"]=1002]="AGENT_SHUTDOWN";AgentEventCode[AgentEventCode["AGENT_PING"]=1003]="AGENT_PING";AgentEventCode[AgentEventCode["AGENT_CONFIG_CHANGED"]=1004]="AGENT_CONFIG_CHANGED";AgentEventCode[AgentEventCode["FIRST_COVERAGE_INSTRUMENTATION_PERFORMED"]=1005]="FIRST_COVERAGE_INSTRUMENTATION_PERFORMED";AgentEventCode[AgentEventCode["FIRST_TIME_HAS_EXECUTION"]=1006]="FIRST_TIME_HAS_EXECUTION";AgentEventCode[AgentEventCode["FIRST_TIME_NO_EXECUTION"]=1007]="FIRST_TIME_NO_EXECUTION";AgentEventCode[AgentEventCode["AGENT_MUTED"]=1008]="AGENT_MUTED";AgentEventCode[AgentEventCode["AGENT_UNMUTED"]=1009]="AGENT_UNMUTED";AgentEventCode[AgentEventCode["FIRST_TIME_COLLECTED_FP"]=1010]="FIRST_TIME_COLLECTED_FP";AgentEventCode[AgentEventCode["GENERIC_MESSAGE"]=2e3]="GENERIC_MESSAGE";AgentEventCode[AgentEventCode["GENERIC_MESSAGE_SUPERUSER"]=2999]="GENERIC_MESSAGE_SUPERUSER";AgentEventCode[AgentEventCode["WARN"]=3e3]="WARN";AgentEventCode[AgentEventCode["AGENT_DID_NOT_SHUTDOWN"]=3001]="AGENT_DID_NOT_SHUTDOWN";AgentEventCode[AgentEventCode["GENERIC_WARNING_SUPERUSER"]=3999]="GENERIC_WARNING_SUPERUSER";AgentEventCode[AgentEventCode["GENERIC_ERROR"]=4e3]="GENERIC_ERROR";AgentEventCode[AgentEventCode["DUPLICATE_MODULE"]=4001]="DUPLICATE_MODULE";AgentEventCode[AgentEventCode["DATA_PROCESSOR_NO_EXECUTIONS"]=4002]="DATA_PROCESSOR_NO_EXECUTIONS";AgentEventCode[AgentEventCode["DATA_PROCESSOR_INVALID_FORMAT"]=4003]="DATA_PROCESSOR_INVALID_FORMAT";AgentEventCode[AgentEventCode["DATA_PROCESSOR_EMPTY_DATA"]=4004]="DATA_PROCESSOR_EMPTY_DATA";AgentEventCode[AgentEventCode["BUILD_MAP_SUBMISSION_ERROR"]=4005]="BUILD_MAP_SUBMISSION_ERROR";AgentEventCode[AgentEventCode["FOOTPRINTS_SUBMISSION_ERROR"]=4006]="FOOTPRINTS_SUBMISSION_ERROR";AgentEventCode[AgentEventCode["TEST_EVENTS_SUBMISSION_ERROR"]=4007]="TEST_EVENTS_SUBMISSION_ERROR";AgentEventCode[AgentEventCode["EXTERNAL_DATA_PROCESSOR_SUBMISSION_ERROR"]=4008]="EXTERNAL_DATA_PROCESSOR_SUBMISSION_ERROR";AgentEventCode[AgentEventCode["UNSUPPORTED_OS"]=4009]="UNSUPPORTED_OS";AgentEventCode[AgentEventCode["UNSUPPORTED_RUNTIME"]=4010]="UNSUPPORTED_RUNTIME";AgentEventCode[AgentEventCode["THIRD_PARTY_PACKAGE_DETECTED"]=4011]="THIRD_PARTY_PACKAGE_DETECTED";AgentEventCode[AgentEventCode["THIRD_PARTY_FILE_DETECTED"]=4012]="THIRD_PARTY_FILE_DETECTED";AgentEventCode[AgentEventCode["FOOTPRINTS_LOSS"]=4999]="FOOTPRINTS_LOSS";AgentEventCode[AgentEventCode["LEAST_VERBOSE_LOG"]=5001]="LEAST_VERBOSE_LOG";AgentEventCode[AgentEventCode["MOST_VERBOSE_LOG"]=5999]="MOST_VERBOSE_LOG"})(AgentEventCode=exports.AgentEventCode||(exports.AgentEventCode={}));var Technology;(function(Technology){Technology["NODEJS"]="nodejs";Technology["BROWSER"]="browser"})(Technology=exports.Technology||(exports.Technology={}))})},{}],290:[function(require,module,exports){var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-events-conracts","./agent-instance-info-builder","./machine-info-builder","./nodejs-env-info-builder","./agent-start-info-builder","./ci-info-builder","../http/backend-proxy","../utils/validation-utils","../watchdog","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentEventsController=void 0;var agent_events_conracts_1=require("./agent-events-conracts");var agent_instance_info_builder_1=require("./agent-instance-info-builder");var machine_info_builder_1=require("./machine-info-builder");var nodejs_env_info_builder_1=require("./nodejs-env-info-builder");var agent_start_info_builder_1=require("./agent-start-info-builder");var ci_info_builder_1=require("./ci-info-builder");var backend_proxy_1=require("../http/backend-proxy");var validation_utils_1=require("../utils/validation-utils");var watchdog_1=require("../watchdog");var system_date_1=require("../system-date");var AgentEventsController=function(){function AgentEventsController(agentConfig,agentInstanceData,logger,backendProxy,tool){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentConfig,"agentConfig");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentInstanceData,"agentInstanceData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this._agentConfig=agentConfig;this._logger=logger;this._agentInstanceData=agentInstanceData;this.shutDownRetries=0;this.backendProxy=backendProxy||this.createBackendProxy();this.addTool(tool);this.initWatchdog();this.submittedEventsMap=new Map}AgentEventsController.prototype.submitAgentStartedEvent=function(packageJsonFile){return __awaiter(this,void 0,void 0,function(){var event,result;return __generator(this,function(_a){switch(_a.label){case 0:this.startRequestStatus=StartRequestStatus.PENDING;event=this.buildAgentStartEvent(packageJsonFile||{});return[4,this.submitAgentEventRequest(event)];case 1:result=_a.sent();this.startRequestStatus=result?StartRequestStatus.SUCCEED:StartRequestStatus.FAILED;if(this.startRequestStatus!==StartRequestStatus.SUCCEED){this._logger.info("Agent start event failed to submit - ping events will not be sent")}else{this._pingWatchdog.start()}return[2]}})})};AgentEventsController.prototype.submitAgentEventRequest=function(event){return __awaiter(this,void 0,void 0,function(){var request,e_1;return __generator(this,function(_a){switch(_a.label){case 0:request={agentId:this._agentInstanceData.agentId,events:Array.isArray(event)?event:[event],appName:this._agentConfig.appName.value,buildSessionId:this._agentConfig.buildSessionId.value};_a.label=1;case 1:_a.trys.push([1,3,,4]);return[4,this.backendProxy.submitAgentEvent(request)];case 2:_a.sent();this._logger.info("Submitted '"+request.events.length+"' events successfully");return[2,true];case 3:e_1=_a.sent();this._logger.warn("Failed to submit '"+request.events.length+"' events. Error "+e_1);return[2,false];case 4:return[2]}})})};AgentEventsController.prototype.buildAgentStartEvent=function(packageJsonFile){var agentInstanceInfoBuilder=new agent_instance_info_builder_1.AgentInstanceInfoBuilder(this);var machineInfoBuilder=new machine_info_builder_1.MachineInfoBuilder;var dependencies=__assign(__assign({},packageJsonFile.dependencies),packageJsonFile.devDependencies);var nodejsEnvInfoBuilder=new nodejs_env_info_builder_1.NodejsEnvInfoBuilder(dependencies);var ciInfoBuilder=new ci_info_builder_1.CiInfoBuilder;var agentStartInfoBuilder=new agent_start_info_builder_1.AgentStartInfoBuilder(agentInstanceInfoBuilder,machineInfoBuilder,nodejsEnvInfoBuilder,ciInfoBuilder);var agentStartInfo=agentStartInfoBuilder.build();return this.buildEvent(agent_events_conracts_1.AgentEventCode.AGENT_STARTED,agentStartInfo)};AgentEventsController.prototype.buildAgentShutdownEvent=function(){return this.buildEvent(agent_events_conracts_1.AgentEventCode.AGENT_SHUTDOWN)};AgentEventsController.prototype.submitAgentShutdownEvent=function(){return __awaiter(this,void 0,void 0,function(){var event;var _this=this;return __generator(this,function(_a){this.shutDownRetries++;if(this.startRequestStatus==StartRequestStatus.FAILED){this._logger.debug("Agent start not submitted - not sending shut down events");return[2]}if(this.shutDownRetries>AgentEventsController.MAX_SHUTDOWN_RETRIES){this._logger.debug("Stop trying to send shutdown event after 60 seconds ");return[2]}this._pingWatchdog.stop();event=this.buildAgentShutdownEvent();if(this.startRequestStatus==StartRequestStatus.PENDING){setTimeout(function(){return _this.submitAgentShutdownEvent.call(_this)},1e3)}else{return[2,this.submitAgentEventRequest(event)]}return[2]})})};AgentEventsController.prototype.submitPingEvent=function(){return this.submitEvent(agent_events_conracts_1.AgentEventCode.AGENT_PING)};AgentEventsController.prototype.submitEvent=function(code){var _this=this;this.submittedEventsMap.set(code,true);this._logger.debug("About to send event with code '"+code+"', current time: "+system_date_1.getSystemDateValueOf());var event=this.buildEvent(code);this.submitAgentEventRequest(event).then(function(){return _this._logger.debug("Event with code '"+code+"' submitted successfully")})};AgentEventsController.prototype.submitEventOnce=function(code){if(!this.submittedEventsMap.get(code)){this.submitEvent(code)}};AgentEventsController.prototype.submitGenericMessage=function(message){this.sendMessage(message,agent_events_conracts_1.AgentEventCode.GENERIC_MESSAGE)};AgentEventsController.prototype.submitWarning=function(message){this.sendMessage(message,agent_events_conracts_1.AgentEventCode.WARN)};AgentEventsController.prototype.submitError=function(message){this.sendMessage(message,agent_events_conracts_1.AgentEventCode.GENERIC_ERROR)};AgentEventsController.prototype.submitErrorsBatch=function(messages){var _this=this;if(!messages||!messages.length){return}var events=messages.map(function(msg){return _this.buildEvent(agent_events_conracts_1.AgentEventCode.GENERIC_ERROR,msg)});this.submitAgentEventRequest(events).then(function(){return _this.logger.debug("'"+events.length+"' events were submitted successfully")})};AgentEventsController.prototype.sendMessage=function(message,code){var _this=this;this.logger.debug("About to send message '"+message+"' with code '"+code+"', current time: "+system_date_1.getSystemDateValueOf());var messageEvent=this.buildEvent(code,message);this.submitAgentEventRequest(messageEvent).then(function(){return _this.logger.debug("Message submitted successfully")})};AgentEventsController.prototype.submitConfigChanged=function(){var _this=this;var messageEvent=this.buildEvent(agent_events_conracts_1.AgentEventCode.AGENT_CONFIG_CHANGED,this._agentConfig.toJsonObject());this.submitAgentEventRequest(messageEvent).then(function(){return _this.logger.debug("Config changed event submitted successfully")})};Object.defineProperty(AgentEventsController.prototype,"watchdog",{get:function(){return this._pingWatchdog},enumerable:false,configurable:true});Object.defineProperty(AgentEventsController.prototype,"agentConfig",{get:function(){return this._agentConfig},enumerable:false,configurable:true});Object.defineProperty(AgentEventsController.prototype,"logger",{get:function(){return this._logger},enumerable:false,configurable:true});Object.defineProperty(AgentEventsController.prototype,"tools",{get:function(){return this._tools},enumerable:false,configurable:true});AgentEventsController.prototype.resolveTags=function(){return[]};AgentEventsController.prototype.addTool=function(tollInfo){if(!tollInfo)return;this._tools=this._tools||[];this._tools.push(tollInfo)};AgentEventsController.prototype.createBackendProxy=function(){var httpConfig={token:this._agentConfig.token.value,proxy:this._agentConfig.proxy.value,server:this._agentConfig.server.value,compressRequests:this._agentConfig.gzip.value};return new backend_proxy_1.BackendProxy(this._agentInstanceData,httpConfig,this._logger)};AgentEventsController.prototype.initWatchdog=function(){var watchdogOptions={interval:AgentEventsController.PING_INTERVAL,name:"AgentEventsWatchdog",autoReset:true,unref:true};var timers=this.getTimers();this._pingWatchdog=new watchdog_1.Watchdog(watchdogOptions,timers);this._pingWatchdog.on("alarm",this.submitPingEvent.bind(this))};AgentEventsController.prototype.getTimers=function(){if(this._agentInstanceData.technology===agent_events_conracts_1.Technology.BROWSER){return{setTimeout:setTimeout.bind(window),clearTimeout:clearTimeout.bind(window)}}else{return{setTimeout:setTimeout,clearTimeout:clearTimeout}}};AgentEventsController.prototype.buildEvent=function(type,data){return{type:type,utcTimestamp_ms:system_date_1.getSystemDateValueOf(),data:data}};Object.defineProperty(AgentEventsController.prototype,"agentInstanceData",{get:function(){return this._agentInstanceData},enumerable:false,configurable:true});AgentEventsController.PING_INTERVAL=2*60*1e3;AgentEventsController.MAX_SHUTDOWN_RETRIES=60;return AgentEventsController}();exports.AgentEventsController=AgentEventsController;var StartRequestStatus;(function(StartRequestStatus){StartRequestStatus["FAILED"]="failed";StartRequestStatus["SUCCEED"]="succeed";StartRequestStatus["PENDING"]="pending"})(StartRequestStatus||(StartRequestStatus={}))})},{"../http/backend-proxy":324,"../system-date":332,"../utils/validation-utils":336,
28
- "../watchdog":337,"./agent-events-conracts":289,"./agent-instance-info-builder":291,"./agent-start-info-builder":292,"./ci-info-builder":293,"./machine-info-builder":296,"./nodejs-env-info-builder":297}],291:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./sensitive-data-filter"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentInstanceInfoBuilder=void 0;var sensitive_data_filter_1=require("./sensitive-data-filter");var SEALIGHTS_ENV_VAR_PREFIX="SL_";var AgentInstanceInfoBuilder=function(){function AgentInstanceInfoBuilder(agentEventsController){this.sendsPing=true;this.agentConfig=agentEventsController.agentConfig;this.agentId=agentEventsController.agentInstanceData.agentId;this.agentType=agentEventsController.agentInstanceData.agentType;this.tags=agentEventsController.resolveTags();this.tools=agentEventsController.tools;this.logger=agentEventsController.logger;this.technology=agentEventsController.agentInstanceData.technology;this.info={agentId:agentEventsController.agentInstanceData.agentId,agentType:agentEventsController.agentInstanceData.agentType,agentVersion:agentEventsController.agentInstanceData.agentVersion,technology:agentEventsController.agentInstanceData.technology}}AgentInstanceInfoBuilder.prototype.fillData=function(){this.info.tags=this.tags;this.info.tools=this.tools;this.info.technology=this.technology;this.info.sendsPing=this.sendsPing;this.fillFromAgentConfig();this.fillFromProcessObject()};AgentInstanceInfoBuilder.prototype.build=function(){this.fillData();return this.info};AgentInstanceInfoBuilder.prototype.fillFromAgentConfig=function(){this.info.buildSessionId=this.agentConfig.buildSessionId.value;this.info.labId=this.agentConfig.labId.value;this.info.agentConfig=this.agentConfig.toJsonObject()};AgentInstanceInfoBuilder.prototype.fillFromProcessObject=function(){this.info.processId=process.pid;this.info.processArch=process.arch;this.info.argv=process.argv;this.info.cwd=process.cwd();this.info.envVars=this.extractSealightsEnvVars()};AgentInstanceInfoBuilder.prototype.extractSealightsEnvVars=function(){var _this=this;var slEnvVars={};Object.keys(process.env).forEach(function(key){if(key.indexOf(SEALIGHTS_ENV_VAR_PREFIX)===0){slEnvVars[key]=sensitive_data_filter_1.isSensitive(key,process.env[key],_this.logger)?AgentInstanceInfoBuilder.SECRET_VALUE_PLACEHOLDER:process.env[key]}});return slEnvVars};AgentInstanceInfoBuilder.DEFAULT_BROWSER_AGENT_VERSION="1.0.0";AgentInstanceInfoBuilder.SEALIGHTS_WINDOW_OBJECT="$Sealights";AgentInstanceInfoBuilder.SECRET_VALUE_PLACEHOLDER="********";return AgentInstanceInfoBuilder}();exports.AgentInstanceInfoBuilder=AgentInstanceInfoBuilder})}).call(this)}).call(this,require("_process"))},{"./sensitive-data-filter":298,_process:179}],292:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentStartInfoBuilder=void 0;var AgentStartInfoBuilder=function(){function AgentStartInfoBuilder(agentInstanceInfoBuilder,machineInfoBuilder,techSpecificInfoBuilder,ciInfoBuilder){this.agentInstanceInfoBuilder=agentInstanceInfoBuilder;this.machineInfoBuilder=machineInfoBuilder;this.techSpecificInfoBuilder=techSpecificInfoBuilder;this.ciInfoBuilder=ciInfoBuilder}AgentStartInfoBuilder.prototype.fillData=function(){};AgentStartInfoBuilder.prototype.build=function(){return{agentInfo:this.agentInstanceInfoBuilder.build(),machineInfo:this.machineInfoBuilder.build(),techSpecificInfo:this.techSpecificInfoBuilder.build(),ciInfo:this.ciInfoBuilder.build()}};return AgentStartInfoBuilder}();exports.AgentStartInfoBuilder=AgentStartInfoBuilder})},{}],293:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CiInfoBuilder=void 0;var JENKINS_JOB_NAME_ENV="JOB_NAME";var JENKINS_JOB_ID_ENV="BUILD_ID";var JENKINS_JOB_URL_ENV="BUILD_URL";var CiInfoBuilder=function(){function CiInfoBuilder(){this.info={}}CiInfoBuilder.prototype.fillData=function(){if(this.isJenkins()){this.info.jobId=process.env[JENKINS_JOB_ID_ENV];this.info.jobName=process.env[JENKINS_JOB_NAME_ENV];this.info.jobUrl=process.env[JENKINS_JOB_URL_ENV]}};CiInfoBuilder.prototype.isJenkins=function(){return process.env[JENKINS_JOB_ID_ENV]&&process.env[JENKINS_JOB_NAME_ENV]&&process.env[JENKINS_JOB_URL_ENV]};CiInfoBuilder.prototype.build=function(){this.fillData();return this.info};return CiInfoBuilder}();exports.CiInfoBuilder=CiInfoBuilder})}).call(this)}).call(this,require("_process"))},{_process:179}],294:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-events-controller","./dry-run-agent-events-controller"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CockpitNotifier=void 0;var agent_events_controller_1=require("./agent-events-controller");var dry_run_agent_events_controller_1=require("./dry-run-agent-events-controller");var CockpitNotifier=function(){function CockpitNotifier(){}CockpitNotifier.notifyStart=function(agentConfig,agentInstanceData,logger,packageJsonFile,backendProxy,tool){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:CockpitNotifier.controller=new agent_events_controller_1.AgentEventsController(agentConfig,agentInstanceData,logger,backendProxy,tool);return[4,CockpitNotifier.controller.submitAgentStartedEvent(packageJsonFile)];case 1:_a.sent();return[2]}})})};CockpitNotifier.notifyShutdown=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:CockpitNotifier.verifyControllerInitialized();return[4,CockpitNotifier.controller.submitAgentShutdownEvent()];case 1:_a.sent();return[2]}})})};CockpitNotifier.sendGenericMessage=function(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitGenericMessage(message)};CockpitNotifier.sendWarning=function(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitWarning(message)};CockpitNotifier.sendError=function(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitError(message)};CockpitNotifier.sendErrorsBatch=function(messages){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitErrorsBatch(messages)};CockpitNotifier.sendEvent=function(code){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitEvent(code)};CockpitNotifier.sendEventOnce=function(code){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitEventOnce(code)};CockpitNotifier.verifyControllerInitialized=function(){if(!CockpitNotifier.controller&&!CockpitNotifier.isDryRunMode){throw new Error("'Agent started' event was not sent. Disabling!")}};CockpitNotifier.reset=function(){CockpitNotifier.controller=undefined;CockpitNotifier.controllerNullLogged=false;CockpitNotifier.isDryRunMode=false};CockpitNotifier.setDryRunMode=function(logger,proxy){CockpitNotifier.isDryRunMode=true;CockpitNotifier.controller=new dry_run_agent_events_controller_1.DryRunAgentEventsController(logger,proxy)};CockpitNotifier.controllerNullLogged=false;return CockpitNotifier}();exports.CockpitNotifier=CockpitNotifier})},{"./agent-events-controller":290,"./dry-run-agent-events-controller":295}],295:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-events-conracts","./agent-events-controller","../config-process/config","../agent-instance-data"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DryRunAgentEventsController=void 0;var agent_events_conracts_1=require("./agent-events-conracts");var agent_events_controller_1=require("./agent-events-controller");var config_1=require("../config-process/config");var agent_instance_data_1=require("../agent-instance-data");var DryRunAgentEventsController=function(_super){__extends(DryRunAgentEventsController,_super);function DryRunAgentEventsController(logger,proxy){return _super.call(this,new config_1.AgentConfig,new agent_instance_data_1.AgentInstanceData(agent_events_conracts_1.AgentType.SLNODEJS,agent_events_conracts_1.Technology.NODEJS),logger,proxy,null)||this}DryRunAgentEventsController.prototype.submitAgentStartedEvent=function(packageJsonFile){return Promise.resolve(undefined)};return DryRunAgentEventsController}(agent_events_controller_1.AgentEventsController);exports.DryRunAgentEventsController=DryRunAgentEventsController})},{"../agent-instance-data":299,"../config-process/config":302,"./agent-events-conracts":289,"./agent-events-controller":290}],296:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","os","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MachineInfoBuilder=void 0;var os=require("os");var system_date_1=require("../system-date");var MachineInfoBuilder=function(){function MachineInfoBuilder(){this.info={}}MachineInfoBuilder.prototype.fillData=function(){var currentDate=system_date_1.getSystemDate();this.info.machineName=os.hostname();this.info.arch=os.arch();this.info.os=os.platform();this.info.localDateTime=currentDate.toString();this.info.localDateTimeUnix_s=currentDate.getTime();this.info.runtime=process.version;this.info.ipAddress=this.extractIpAddresses()};MachineInfoBuilder.prototype.build=function(){this.fillData();return this.info};MachineInfoBuilder.prototype.extractIpAddresses=function(){var ipAddresses=[];var interfaces=os.networkInterfaces();Object.keys(interfaces).forEach(function(key){var addressesArr=interfaces[key];ipAddresses=ipAddresses.concat(addressesArr.map(function(addressObject){return addressObject.address}))});return ipAddresses};return MachineInfoBuilder}();exports.MachineInfoBuilder=MachineInfoBuilder})}).call(this)}).call(this,require("_process"))},{"../system-date":332,_process:179,os:154}],297:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NodejsEnvInfoBuilder=void 0;var NodejsEnvInfoBuilder=function(){function NodejsEnvInfoBuilder(dependencies){this.info={};this.dependencies=dependencies||{}}NodejsEnvInfoBuilder.prototype.fillData=function(){this.info.indexJsonDeps=this.dependencies;this.info.nodeVersion=process.versions.node};NodejsEnvInfoBuilder.prototype.build=function(){this.fillData();return this.info};return NodejsEnvInfoBuilder}();exports.NodejsEnvInfoBuilder=NodejsEnvInfoBuilder})}).call(this)}).call(this,require("_process"))},{_process:179}],298:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isSensitive=void 0;var secretKeysRegexes={"Slack Token":"(xox[p|b|o|a]-[0-9]{12}-[0-9]{12}-[0-9]{12}-[a-z0-9]{32})","RSA private key":"-----BEGIN RSA PRIVATE KEY-----","SSH (DSA) private key":"-----BEGIN DSA PRIVATE KEY-----","SSH (EC) private key":"-----BEGIN EC PRIVATE KEY-----","PGP private key block":"-----BEGIN PGP PRIVATE KEY BLOCK-----","Amazon AWS Access Key ID":"AKIA[0-9A-Z]{16}","Amazon MWS Auth Token":"amzn\\.mws\\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}","AWS API Key":"AKIA[0-9A-Z]{16}","Facebook Access Token":"EAACEdEose0cBA[0-9A-Za-z]+","Facebook OAuth":"[f|F][a|A][c|C][e|E][b|B][o|O][o|O][k|K].*['|\"][0-9a-f]{32}['|\"]",GitHub:"[g|G][i|I][t|T][h|H][u|U][b|B].*['|\"][0-9a-zA-Z]{35,40}['|\"]","Generic API Key":"[a|A][p|P][i|I][_]?[k|K][e|E][y|Y].*['|\"][0-9a-zA-Z]{32,45}['|\"]","Generic Secret":"[s|S][e|E][c|C][r|R][e|E][t|T].*['|\"][0-9a-zA-Z]{32,45}['|\"]","Google API Key":"AIza[0-9A-Za-z\\-_]{35}","Google Cloud Platform API Key":"AIza[0-9A-Za-z\\-_]{35}","Google Cloud Platform OAuth":"[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com","Google Drive API Key":"AIza[0-9A-Za-z\\-_]{35}","Google Drive OAuth":"[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com","Google (GCP) Service-account":'"type": "service_account"',"Google Gmail API Key":"AIza[0-9A-Za-z\\-_]{35}","Google Gmail OAuth":"[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com","Google OAuth Access Token":"ya29\\.[0-9A-Za-z\\-_]+","Google YouTube API Key":"AIza[0-9A-Za-z\\-_]{35}","Google YouTube OAuth":"[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com","Heroku API Key":"[h|H][e|E][r|R][o|O][k|K][u|U].*[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}","MailChimp API Key":"[0-9a-f]{32}-us[0-9]{1,2}","Mailgun API Key":"key-[0-9a-zA-Z]{32}","Password in URL":"[a-zA-Z]{3,10}://[^/\\s:@]{3,20}:[^/\\s:@]{3,20}@.{1,100}[\"'\\s]","PayPal Braintree Access Token":"access_token\\$production\\$[0-9a-z]{16}\\$[0-9a-f]{32}","Picatic API Key":"sk_live_[0-9a-z]{32}","Slack Webhook":"https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}","Stripe API Key":"sk_live_[0-9a-zA-Z]{24}","Stripe Restricted API Key":"rk_live_[0-9a-zA-Z]{24}","Square Access Token":"sq0atp-[0-9A-Za-z\\-_]{22}","Square OAuth Secret":"sq0csp-[0-9A-Za-z\\-_]{43}","Twilio API Key":"SK[0-9a-fA-F]{32}","Twitter Access Token":"[t|T][w|W][i|I][t|T][t|T][e|E][r|R].*[1-9][0-9]+-[0-9a-zA-Z]{40}","Twitter OAuth":"[t|T][w|W][i|I][t|T][t|T][e|E][r|R].*['|\"][0-9a-zA-Z]{35,44}['|\"]"};function isSensitive(envVar,value,logger){for(var _i=0,_a=Object.entries(secretKeysRegexes);_i<_a.length;_i++){var _b=_a[_i],key=_b[0],regex=_b[1];if(new RegExp(regex).test(value)){logger.debug("Value for key "+envVar+" filtered out since it suspected to contains data fpr "+key);return true}}return false}exports.isSensitive=isSensitive})},{}],299:[function(require,module,exports){(function(__dirname){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","uuid","./agent-events/agent-events-conracts","./utils/files-utils","fs","./agent-events/agent-instance-info-builder"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentInstanceData=void 0;var uuid=require("uuid");var agent_events_conracts_1=require("./agent-events/agent-events-conracts");var files_utils_1=require("./utils/files-utils");var fs_1=require("fs");var agent_instance_info_builder_1=require("./agent-events/agent-instance-info-builder");var AgentInstanceData=function(){function AgentInstanceData(agentType,technology){this.agentType=agentType;this.technology=technology;this.agentId=uuid();this.agentVersion=this.resolveAgentVersion()}AgentInstanceData.prototype.resolveAgentVersion=function(){if(this.technology===agent_events_conracts_1.Technology.BROWSER){return this.resolveAgentVersionForBrowserAgent()}var packageJsonFilePath=files_utils_1.FilesUtils.findFileUp("package.json",__dirname);if(packageJsonFilePath){try{var packageJson=fs_1.readFileSync(packageJsonFilePath).toString();var parsed=JSON.parse(packageJson);return parsed.version}catch(e){console.warn("Failed to resolve agent version, Error: '"+e);return null}}return null};AgentInstanceData.prototype.resolveAgentVersionForBrowserAgent=function(){return window&&window[agent_instance_info_builder_1.AgentInstanceInfoBuilder.SEALIGHTS_WINDOW_OBJECT]&&window[agent_instance_info_builder_1.AgentInstanceInfoBuilder.SEALIGHTS_WINDOW_OBJECT].agentVersion||agent_instance_info_builder_1.AgentInstanceInfoBuilder.DEFAULT_BROWSER_AGENT_VERSION};return AgentInstanceData}();exports.AgentInstanceData=AgentInstanceData})}).call(this)}).call(this,"/tsOutputs/common")},{"./agent-events/agent-events-conracts":289,"./agent-events/agent-instance-info-builder":291,"./utils/files-utils":333,fs:69,uuid:506}],300:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./config-system","fs","jwt-decode","./config"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigLoader=void 0;var config_system_1=require("./config-system");var fs=require("fs");var jwtDecode=require("jwt-decode");var config_1=require("./config");var ConfigLoader=function(){function ConfigLoader(logger){this.logger=logger}ConfigLoader.prototype.loadAgentConfiguration=function(initialJsonConfig){var agentCfg=new config_1.AgentConfig;if(process.env.SL_CONFIGURATION){try{var jsonCfg=JSON.parse(process.env.SL_CONFIGURATION);agentCfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(jsonCfg))}catch(e){console.error("Error parsing agent configuration %s",e)}}agentCfg.loadConfiguration(new config_system_1.EnvVariableConfigurationProvider("SL_"));if(initialJsonConfig){agentCfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(initialJsonConfig))}if(!agentCfg.token.hasValue&&agentCfg.tokenFile.hasValue){try{agentCfg.token.value=fs.readFileSync(agentCfg.tokenFile.value).toString()}catch(err){}}if(agentCfg.token.hasValue){this.loadConfigFromToken(agentCfg,agentCfg.token.value)}this.printConfiguration(agentCfg);return agentCfg};ConfigLoader.prototype.printConfiguration=function(agentCfg){if(!this.logger)return;this.logger.info("****************************************************");this.logger.info("Current config");this.logger.info("****************************************************");this.logger.info(agentCfg.toJsonObject())};ConfigLoader.prototype.loadConfigFromToken=function(agentCfg,token){if(!token)return null;try{var tokenData=jwtDecode(token);if(!tokenData["x-sl-server"]){throw new Error("Token Is Invalid. Doesn't Contain Server")}if(!tokenData["subject"]){throw new Error("Token Is Invalid. Doesn't Contain Subject")}var customerId=tokenData["subject"];var subjectParts=tokenData["subject"].split("@");if(subjectParts.length>=1){customerId=subjectParts[0]}if(!agentCfg.server.hasValue){agentCfg.server.value=tokenData["x-sl-server"]}agentCfg.customerId.value=customerId}catch(err){}};return ConfigLoader}();exports.ConfigLoader=ConfigLoader})}).call(this)}).call(this,require("_process"))},{"./config":302,"./config-system":301,_process:179,fs:69,"jwt-decode":440}],301:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","fs"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BaseConfiguration=exports.BooleanConfigKey=exports.NumberConfigKey=exports.StringConfigKey=exports.AgentConfigKey=exports.JsonConfigFileConfigurationProvider=exports.ConfigProviderAggregator=exports.EnvVariableConfigurationProvider=exports.JsonObjectConfigurationProvider=void 0;var fs=require("fs");var JsonObjectConfigurationProvider=function(){function JsonObjectConfigurationProvider(configObject){this.configObject=configObject;this.configObject=configObject||{}}JsonObjectConfigurationProvider.prototype.getAllKeyValues=function(callback){return callback(null,this.configObject)};JsonObjectConfigurationProvider.prototype.getName=function(){return"JSON Object"};return JsonObjectConfigurationProvider}();exports.JsonObjectConfigurationProvider=JsonObjectConfigurationProvider;var EnvVariableConfigurationProvider=function(){function EnvVariableConfigurationProvider(prefix){this.prefix=prefix}EnvVariableConfigurationProvider.prototype.getAllKeyValues=function(callback){if(this.prefix){var ret={};for(var key in process.env){if(key.indexOf(this.prefix)==0){ret[key.substr(this.prefix.length)]=process.env[key]}}callback(null,ret)}else{return callback(null,process.env)}};EnvVariableConfigurationProvider.prototype.getName=function(){return"Environment Variables"};return EnvVariableConfigurationProvider}();exports.EnvVariableConfigurationProvider=EnvVariableConfigurationProvider;var ConfigProviderAggregator=function(){function ConfigProviderAggregator(providers){this.providers=providers;if(!providers)throw new Error("no provider was specified")}ConfigProviderAggregator.prototype.getAllKeyValues=function(callback){var flattenedConfiguration={};var remainingProviders=[].concat(this.providers);var attemptNext=function(){if(remainingProviders.length==0){return callback(null,flattenedConfiguration)}var nextProvider=remainingProviders.shift();nextProvider.getAllKeyValues(function(err,keysAndValues){if(err)return attemptNext();Object.keys(keysAndValues).forEach(function(k){if(!flattenedConfiguration.hasOwnProperty(k))flattenedConfiguration[k]=keysAndValues[k]});return attemptNext()})};attemptNext()};ConfigProviderAggregator.prototype.getName=function(){return"Aggregated config from multiple providers: "+this.providers.map(function(t){return t.getName()})};return ConfigProviderAggregator}();exports.ConfigProviderAggregator=ConfigProviderAggregator;var JsonConfigFileConfigurationProvider=function(){function JsonConfigFileConfigurationProvider(filename){this.filename=filename;if(!filename)throw new Error("filename is required")}JsonConfigFileConfigurationProvider.prototype.getAllKeyValues=function(callback){try{var cfg=JSON.parse(fs.readFileSync(this.filename).toString().trim());return callback(null,cfg)}catch(e){return callback(e,null)}};JsonConfigFileConfigurationProvider.prototype.getName=function(){return"Config filename: "+this.filename};return JsonConfigFileConfigurationProvider}();exports.JsonConfigFileConfigurationProvider=JsonConfigFileConfigurationProvider;var AgentConfigKey=function(){function AgentConfigKey(){}return AgentConfigKey}();exports.AgentConfigKey=AgentConfigKey;var StringConfigKey=function(){function StringConfigKey(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"string"};if(defaultValue!==undefined){this.value=defaultValue}}Object.defineProperty(StringConfigKey.prototype,"value",{get:function(){return this._value},set:function(value){this._value=value;this.hasValue=true},enumerable:false,configurable:true});StringConfigKey.prototype.loadFromRawData=function(s){this.value=s;this.hasValue=true};return StringConfigKey}();exports.StringConfigKey=StringConfigKey;var NumberConfigKey=function(){function NumberConfigKey(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"number"};if(defaultValue!==undefined){this.value=defaultValue}}Object.defineProperty(NumberConfigKey.prototype,"value",{get:function(){return this._value},set:function(value){this._value=value;this.hasValue=true},enumerable:false,configurable:true});NumberConfigKey.prototype.loadFromRawData=function(s){var parsed=parseInt(s);if(isNaN(parsed))throw new Error(s+" is not a valid number");this.value=parsed;this.hasValue=true};return NumberConfigKey}();exports.NumberConfigKey=NumberConfigKey;var BooleanConfigKey=function(){function BooleanConfigKey(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"boolean"};if(defaultValue!==undefined){this.value=defaultValue}}Object.defineProperty(BooleanConfigKey.prototype,"value",{get:function(){return this._value},set:function(value){this._value=value;this.hasValue=true},enumerable:false,configurable:true});BooleanConfigKey.prototype.loadFromRawData=function(s){if(s==null)s="";if(typeof s==="boolean")s=String(s);s=s.toLowerCase();switch(s){case"true":this.value=true;this.hasValue=true;return;case"false":this.value=false;this.hasValue=true;return;case"undefined":this.value=false;this.hasValue=false;return;default:throw new Error("Invalid boolean value: "+s)}};return BooleanConfigKey}();exports.BooleanConfigKey=BooleanConfigKey;var BaseConfiguration=function(){function BaseConfiguration(){}BaseConfiguration.prototype.loadConfigurationFromMultipleProviders=function(configProviders,callback){var provider=new ConfigProviderAggregator(configProviders);this.loadConfiguration(provider,callback)};BaseConfiguration.prototype.loadConfiguration=function(configProvider,callback,dbg){var _this=this;try{configProvider.getAllKeyValues(function(err,keysAndValues){if(err){if(callback){callback(err)}return}keysAndValues=keysAndValues||{};var knownKeys=Object.keys(_this);var hadError=false;var keyWithError="";knownKeys.forEach(function(keyName){if(hadError){console.log("[Sealights Test Listener] - Failed to load configuration due to invalid value in '"+keyWithError+"' field'.");return}var cfgKey=_this[keyName];if(!cfgKey.isConfigKey)return;var rawValue=keysAndValues[keyName];if(cfgKey.metadata.required&&rawValue==undefined){var msg="Required configuration is missing: "+keyName+", provider:"+configProvider.getName();hadError=true;if(callback){callback(new Error(msg))}}if(rawValue==undefined)return;try{cfgKey.loadFromRawData(rawValue)}catch(e){var msg="Invalid configuration for key="+keyName+", value="+rawValue+ +", provider="+configProvider.getName()+": "+e.toString();console.log("[Sealights Test Listener] - "+msg);hadError=true;keyWithError=keyName;if(callback){callback(new Error(msg))}}});if(!hadError){if(callback){callback(null)}return}})}catch(e){if(callback){callback(e)}return}};BaseConfiguration.prototype.toJsonObject=function(){var _this=this;var ret={};var knownKeys=Object.keys(this);knownKeys.forEach(function(keyName){var cfgKey=_this[keyName];if(cfgKey.isConfigKey&&cfgKey.hasValue){ret[keyName]=cfgKey.value}});return ret};BaseConfiguration.prototype.getLowerCaseToKeyMap=function(){var lowerCaseMap={};Object.keys(this).forEach(function(key){lowerCaseMap[key.toLowerCase()]=key});return lowerCaseMap};return BaseConfiguration}();exports.BaseConfiguration=BaseConfiguration})}).call(this)}).call(this,require("_process"))},{_process:179,fs:69}],302:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./config-system"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentConfigWithRuntimeArgs=exports.AgentConfig=void 0;var config_system_1=require("./config-system");var AgentConfig=function(_super){__extends(AgentConfig,_super);function AgentConfig(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.token=new config_system_1.StringConfigKey(false);_this.buildSessionId=new config_system_1.StringConfigKey(false);_this.tokenFile=new config_system_1.StringConfigKey(false);_this.server=new config_system_1.StringConfigKey(false);_this.proxy=new config_system_1.StringConfigKey(false);_this.interval=new config_system_1.NumberConfigKey(false,1e4);_this.testStatusCheckInterval=new config_system_1.NumberConfigKey(false,3e4);_this.enabled=new config_system_1.BooleanConfigKey(false,true);_this.sendFootprints=new config_system_1.BooleanConfigKey(false,true);_this.sendEvents=new config_system_1.BooleanConfigKey(false,true);_this.sendLogs=new config_system_1.BooleanConfigKey(false,false);_this.customerId=new config_system_1.StringConfigKey(false)
29
- ;_this.appName=new config_system_1.StringConfigKey(false);_this.branch=new config_system_1.StringConfigKey(false);_this.build=new config_system_1.StringConfigKey(false);_this.environmentName=new config_system_1.StringConfigKey(false);_this.useBranchCoverage=new config_system_1.BooleanConfigKey(false,false);_this.labId=new config_system_1.StringConfigKey(false);_this.testStage=new config_system_1.StringConfigKey(false);_this.httpServerColoring=new config_system_1.BooleanConfigKey(false,false);_this.httpClientColoring=new config_system_1.BooleanConfigKey(false,false);_this.useInitialColor=new config_system_1.BooleanConfigKey(false,true);_this.gzip=new config_system_1.BooleanConfigKey(false,true);_this.useIstanbul=new config_system_1.BooleanConfigKey(false,false);_this.enableChildProcessPatcher=new config_system_1.BooleanConfigKey(false,false);_this.loggers=new config_system_1.StringConfigKey(false,"");_this.httpListeningPort=new config_system_1.NumberConfigKey(false,0);_this.useFootprintsV3=new config_system_1.BooleanConfigKey(false,true);_this.extendedFootprints=new config_system_1.BooleanConfigKey(false,false);_this.projectRoot=new config_system_1.StringConfigKey(false);_this.enforceFullRun=new config_system_1.BooleanConfigKey(false,false);_this.footprintsEnableV6=new config_system_1.BooleanConfigKey(false,true);_this.footprintsBufferThresholdMb=new config_system_1.NumberConfigKey(false,10);_this.executionQueryIntervalSecs=new config_system_1.NumberConfigKey(false,10);_this.footprintsQueueSize=new config_system_1.NumberConfigKey(false,2);_this.footprintsSendIntervalSecs=new config_system_1.NumberConfigKey(false,10);_this.footprintsCollectIntervalSecs=new config_system_1.NumberConfigKey(false,10);_this.shouldCheckForActiveExecutionOnStartUp=new config_system_1.BooleanConfigKey(false,true);return _this}return AgentConfig}(config_system_1.BaseConfiguration);exports.AgentConfig=AgentConfig;var AgentConfigWithRuntimeArgs=function(_super){__extends(AgentConfigWithRuntimeArgs,_super);function AgentConfigWithRuntimeArgs(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.cfg=new config_system_1.StringConfigKey(false);return _this}return AgentConfigWithRuntimeArgs}(AgentConfig);exports.AgentConfigWithRuntimeArgs=AgentConfigWithRuntimeArgs})},{"./config-system":301}],303:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","events","./config-system","object-assign","jwt-decode"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigProcess=void 0;var events=require("events");var config_system_1=require("./config-system");var assign=require("object-assign");var jwtDecode=require("jwt-decode");var ConfigProcess=function(_super){__extends(ConfigProcess,_super);function ConfigProcess(cfg,watchdog,backendProxy,logger){var _this=_super.call(this)||this;_this.cfg=cfg;_this.watchdog=watchdog;_this.backendProxy=backendProxy;_this.logger=logger;_this.isRunning=false;if(!cfg)throw new Error("cfg is required");_this.initialCfg=assign({},cfg.toJsonObject());if(!watchdog)throw new Error("watchdog is required");if(!backendProxy)throw new Error("backendProxy is required");if(!logger){throw new Error("logger is required")}watchdog.on("alarm",function(){watchdog.stop();_this.reloadConfigFromServer()});_this.initCfg();return _this}ConfigProcess.prototype.reloadConfigFromServer=function(callback){var _this=this;this.backendProxy.getRemoteConfig({appName:this.cfg.appName.value,branch:this.cfg.branch.value,build:this.cfg.build.value,labId:this.cfg.labId.value,testStage:this.cfg.testStage.value},function(err,updatedCfg){if(!err&&updatedCfg){_this.mergeConfigFromServerAndFireEvent(updatedCfg)}_this.watchdog.start();if(callback){callback(err)}})};ConfigProcess.prototype.mergeConfigFromServerAndFireEvent=function(updatedCfgObject){var configChanged=false;this.cfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(this.initialCfg));for(var key in updatedCfgObject){if(this.cfg[key]&&this.cfg[key].isConfigKey&&this.cfg[key].value!=updatedCfgObject[key]){configChanged=true;break}}if(configChanged){this.cfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(updatedCfgObject));this.emit("configuration_changed",this.cfg)}};ConfigProcess.prototype.getConfiguration=function(){return this.cfg};ConfigProcess.prototype.initCfg=function(){if(this.cfg.token.hasValue){try{var tokenData=jwtDecode(this.cfg.token.value);if(!tokenData["x-sl-server"]){throw new Error("Token Is Invalid. Doesn't Contain Server")}if(!this.cfg.server.hasValue)this.cfg.server.value=tokenData["x-sl-server"];if(!tokenData["subject"]){throw new Error("Token Is Invalid. Doesn't Contain Subject")}var customerId=tokenData["subject"];var subjectParts=tokenData["subject"].split("@");customerId=subjectParts[0];this.cfg.customerId.value=this.cfg.customerId.value||customerId}catch(err){this.cfg.enabled.value=false;this.logger.error("Error loading configuration. Agent will be disabled. %s",err)}}};ConfigProcess.prototype.start=function(callback){if(this.isRunning)return;if(!this.cfg.enabled.value)return;if(!this.cfg.server.value||!this.cfg.token.hasValue)return;this.reloadConfigFromServer(callback);this.isRunning=true};ConfigProcess.prototype.stop=function(callback){this.watchdog.stop();this.isRunning=false;return callback()};return ConfigProcess}(events.EventEmitter);exports.ConfigProcess=ConfigProcess})},{"./config-system":301,events:110,"jwt-decode":440,"object-assign":153}],304:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Constants=void 0;var Constants=function(){function Constants(){}var _a;Constants.TRUE="true";Constants.FALSE="false";Constants.BUILD_SESSION_ID="buildSessionId";Constants.REQUEST="request";Constants.FOOTPRINTS_PACKET="footprintsPacket";Constants.TEST_STAGE="testStage";Constants.EXECUTION_BSID="executionBsid";Constants.CALLBACK="callback";Constants.PULL_REQUEST_PARAMS="pullRequestParams";Constants.SL_WINDOW_OBJECT="window.$Sealights";Constants.SKIP_BROWSER_AGENT=Constants.SL_WINDOW_OBJECT+".skipSlAgent";Constants.Messages=(_a=function(){function class_1(){}return class_1}(),_a.CANNOT_BE_NULL_OR_UNDEFINED="cannot be null or undefined.",_a.CANNOT_BE_EMPTY_STRING="cannot be empty string",_a);return Constants}();exports.Constants=Constants})},{}],305:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../utils/parsing-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SlEnvVars=void 0;var parsing_utils_1=require("../utils/parsing-utils");var SlEnvVars=function(){function SlEnvVars(){}SlEnvVars.getHttpTimeout=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.HTTP_TIMEOUT)};SlEnvVars.getHttpMaxAttempts=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.HTTP_MAX_ATTEMPTS)};SlEnvVars.getHttpAttemptInterval=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.HTTP_ATTEMPT_INTERVAL)};SlEnvVars.inProductionListenerMode=function(){return!!process.env[SlEnvVars.PRODUCTION_LISTENER]};SlEnvVars.getProductionListenerModes=function(){return(process.env[SlEnvVars.PRODUCTION_LISTENER]||"").split(",")};SlEnvVars.getFileStorage=function(){return process.env[SlEnvVars.FILE_STORAGE]};SlEnvVars.getBasePath=function(){return process.env[SlEnvVars.BASE_PATH]};SlEnvVars.isUseNewUniqueId=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.NEW_UNIQUE_ID)};SlEnvVars.isUseIstanbul=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.USE_ISTANBUL)};SlEnvVars.enableFootprintsV6=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.ENABLE_FOOTPRINTS_V6)};SlEnvVars.getFootprintsCollectIntervalSecs=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.FOOTPRINTS_COLLECTION_INTERVAL_SECS)};SlEnvVars.getFootprintsSendMaxIntervalSecs=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.FOOTPRINTS_SEND_MAX_INTERVAL_SECS)};SlEnvVars.getFootprintsQueueSize=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.FOOTPRINTS_QUEUE_SIZE)};SlEnvVars.getExecutionQueryIntervalSecs=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.EXECUTION_QUERY_INTERVAL_SEC)};SlEnvVars.getFootprintsBufferThresholdMb=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.FOOTPRINTS_BUFFER_THRESHOLD_MB)};SlEnvVars.blockBrowserHttpTraffic=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.BLOCK_BROWSER_HTTP_TRAFFIC)};SlEnvVars.getDisableHookDependencyGuard=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.DISABLE_HOOK_DEPENDENCY_GUARD)};var _a;SlEnvVars.HTTP_TIMEOUT="SL_httpTimeout";SlEnvVars.HTTP_MAX_ATTEMPTS="SL_HttpMaxAttempts";SlEnvVars.HTTP_ATTEMPT_INTERVAL="SL_HttpAttemptInterval";SlEnvVars.PRODUCTION_LISTENER="SL_production";SlEnvVars.FILE_STORAGE="SL_fileStorage";SlEnvVars.NEW_UNIQUE_ID="SL_newUniqueId";SlEnvVars.BASE_PATH="SL_basePath";SlEnvVars.USE_ISTANBUL="SL_useIstanbul";SlEnvVars.ENABLE_FOOTPRINTS_V6="SL_footprintsEnableV6";SlEnvVars.FOOTPRINTS_COLLECTION_INTERVAL_SECS="SL_footprintsCollectIntervalSecs";SlEnvVars.FOOTPRINTS_SEND_MAX_INTERVAL_SECS="SL_footprintsSendIntervalSecs";SlEnvVars.FOOTPRINTS_QUEUE_SIZE="SL_footprintsQueueSize";SlEnvVars.EXECUTION_QUERY_INTERVAL_SEC="SL_executionQueryIntervalSecs";SlEnvVars.FOOTPRINTS_BUFFER_THRESHOLD_MB="SL_footprintsBufferThresholdMb";SlEnvVars.BLOCK_BROWSER_HTTP_TRAFFIC="SL_blockBrowserHttpTraffic";SlEnvVars.DISABLE_HOOK_DEPENDENCY_GUARD="SL_disableHookDependencyGuard";SlEnvVars.CIA=(_a=function(){function class_1(){}class_1.getFileExtensions=function(){return process.env[SlEnvVars.CIA.FILE_EXTENSIONS]};class_1.getSourceRoot=function(){return process.env[SlEnvVars.CIA.SL_SOURCE_ROOT]};class_1.getSlMappingPath=function(){return process.env[SlEnvVars.CIA.SL_MAPPING_PATH]};class_1.getSlMappingUrl=function(){return process.env[SlEnvVars.CIA.SL_MAPPING_URL]};class_1.reduceInstrumentedFileSize=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.CIA.REDUCE_INSTRUMENTED_FILE_SIZE)};class_1.minifyInstrumentedOutput=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.CIA.MINIFY_INSTRUMENTED_OUTPUT)};class_1.inProcessInstrumentation=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.CIA.IN_PROCESS_INSTRUMENTATION)};class_1.getMaxBuffer=function(){var oneMB=1024*1024;var bufferInBytes=parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.CIA.MAX_BUFFER);if(bufferInBytes!==null){return bufferInBytes*oneMB}return bufferInBytes};return class_1}(),_a.FILE_EXTENSIONS="SL_fileExtensions",_a.SL_SOURCE_ROOT="SL_sourceRoot",_a.SL_MAPPING_PATH="SL_mappingPath",_a.SL_MAPPING_URL="SL_mappingUrl",_a.REDUCE_INSTRUMENTED_FILE_SIZE="SL_reduceInstrumentedFileSize",_a.MINIFY_INSTRUMENTED_OUTPUT="SL_minifyInstrumentedOutput",_a.IN_PROCESS_INSTRUMENTATION="SL_inProcessInstrumentation",_a.MAX_BUFFER="SL_maxBuffer",_a);return SlEnvVars}();exports.SlEnvVars=SlEnvVars})}).call(this)}).call(this,require("_process"))},{"../utils/parsing-utils":334,_process:179}],306:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ElementType=void 0;var ElementType;(function(ElementType){ElementType["METHOD"]="method";ElementType["BRANCH"]="branch"})(ElementType=exports.ElementType||(exports.ElementType={}))})},{}],307:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FileElement=void 0;var validation_utils_1=require("../utils/validation-utils");var FileElement=function(){function FileElement(type,startPosition,endPosition,uniqueIdKey,filename){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(type,"type");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(startPosition,"startPosition");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(endPosition,"endPosition");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(uniqueIdKey,"uniqueIdKey");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(filename,"filename");this._type=type;this._startPosition=startPosition;this._endPosition=endPosition;this._uniqueIdKey=uniqueIdKey;this._filename=filename}Object.defineProperty(FileElement.prototype,"type",{get:function(){return this._type},set:function(value){this._type=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"startPosition",{get:function(){return this._startPosition},set:function(value){this._startPosition=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"endPosition",{get:function(){return this._endPosition},set:function(value){this._endPosition=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"uniqueIdKey",{get:function(){return this._uniqueIdKey},set:function(value){this._uniqueIdKey=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"uniqueIdKey_decl",{get:function(){return this._uniqueIdKey_decl},set:function(value){this._uniqueIdKey_decl=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"filename",{get:function(){return this._filename},set:function(value){this._filename=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"uniqueId",{get:function(){return this._uniqueId},set:function(value){this._uniqueId=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"parentPosition",{get:function(){return this._parentPosition},set:function(value){this._parentPosition=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"index",{get:function(){return this._index},set:function(value){this._index=value},enumerable:false,configurable:true});FileElement.prototype.isStartsAfter=function(fileElement){if(parseInt(this._startPosition.line.toString())<parseInt(fileElement.startPosition.line.toString())){return false}if(parseInt(this._startPosition.line.toString())>parseInt(fileElement.startPosition.line.toString())){return true}if(parseInt(this._startPosition.column.toString())>parseInt(fileElement.startPosition.column.toString())){return true}return false};FileElement.prototype.isStartsBefore=function(fileElement){if(parseInt(this._startPosition.line.toString())>parseInt(fileElement.startPosition.line.toString())){return false}if(parseInt(this._startPosition.line.toString())<parseInt(fileElement.startPosition.line.toString())){return true}if(parseInt(this._startPosition.column.toString())<parseInt(fileElement.startPosition.column.toString())){return true}return false};FileElement.prototype.isEndsAfter=function(fileElement){if(parseInt(this._endPosition.line.toString())<parseInt(fileElement.endPosition.line.toString())){return false}if(parseInt(this._endPosition.line.toString())>parseInt(fileElement.endPosition.line.toString())){return true}if(parseInt(this._endPosition.column.toString())>parseInt(fileElement.endPosition.column.toString())){return true}return false};FileElement.prototype.isEndsBefore=function(fileElement){if(parseInt(this._endPosition.line.toString())>parseInt(fileElement.endPosition.line.toString())){return false}if(parseInt(this._endPosition.line.toString())<parseInt(fileElement.endPosition.line.toString())){return true}if(parseInt(this._endPosition.column.toString())<parseInt(fileElement.endPosition.column.toString())){return true}return false};return FileElement}();exports.FileElement=FileElement})},{"../utils/validation-utils":336}],308:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./contracts","./unique-id-converter"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.IstanbulUniqueIdConverter=void 0;var contracts_1=require("./contracts");var unique_id_converter_1=require("./unique-id-converter");var IstanbulUniqueIdConverter=function(_super){__extends(IstanbulUniqueIdConverter,_super);function IstanbulUniqueIdConverter(filename,logger){return _super.call(this,filename,logger)||this}IstanbulUniqueIdConverter.prototype.createElementsArray=function(file){var _this=this;file.fnMap=file.fnMap||{};file.branchMap=file.branchMap||{};var methodsArr=Object.keys(file.fnMap).map(function(key){return _this.formatMethod(file.fnMap[key])});var branchesArr=this.createBranchElements(file.branchMap);this.fillFileElementsArray(methodsArr,this.methodsArray,contracts_1.ElementType.METHOD);this.fillFileElementsArray(branchesArr,this.branchesArray,contracts_1.ElementType.BRANCH)};IstanbulUniqueIdConverter.prototype.createElementPosition=function(position){return position};IstanbulUniqueIdConverter.prototype.createBranchElements=function(branchesMap){var branchesMapArr=Object.keys(branchesMap).map(function(key){return branchesMap[key]});var branchesArr=[];for(var _i=0,branchesMapArr_1=branchesMapArr;_i<branchesMapArr_1.length;_i++){var branch=branchesMapArr_1[_i];branchesArr=branchesArr.concat(this.extractBranchParts(branch))}return branchesArr};IstanbulUniqueIdConverter.prototype.extractBranchParts=function(branch){var formattedBranches=[];var locations=branch.locations;for(var i=0;i<locations.length;i++){var element={};element.position=locations[i].start;element.endPosition=locations[i].end;element.uniqueId=this.filename+"|"+this.formatLoc(element.position)+"|"+i;formattedBranches.push(element)}return formattedBranches};IstanbulUniqueIdConverter.prototype.formatMethod=function(method){var element={};element.position=method.loc.start;element.endPosition=method.loc.end;element.uniqueId=this.filename+"@"+this.formatLoc(method.loc.start);if(method.decl&&method.decl.start){element.uniqueId_decl=this.filename+"@"+this.formatLoc(method.decl.start);if(method.decl.start.line<method.loc.start.line){element.position=method.decl.start}}return element};IstanbulUniqueIdConverter.prototype.formatLoc=function(loc){return loc.line+","+loc.column};return IstanbulUniqueIdConverter}(unique_id_converter_1.UniqueIdConverter);exports.IstanbulUniqueIdConverter=IstanbulUniqueIdConverter})},{"./contracts":306,"./unique-id-converter":311}],309:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","path","../system-date","../utils/files-utils","./istanbul-unique-id-converter"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.resolveNewId=void 0;var path_1=require("path");var system_date_1=require("../system-date");var files_utils_1=require("../utils/files-utils");var istanbul_unique_id_converter_1=require("./istanbul-unique-id-converter");function resolveNewId(uniqueIdKey,moduleName,relativePath,coverageObject,logger){moduleName=path_1.normalize(moduleName);var moduleData=resolveModule(coverageObject,moduleName,logger);if(!moduleData){return}if(!moduleData.uniqueIdsMap){logger.debug("building uniqueids map for "+moduleData.path);var before_1=system_date_1.getSystemDateValueOf();logger.debug("file "+moduleData.path+" not contains uniqueIdMaps, trying to reload");createSLMapping(moduleData.path,relativePath,coverageObject,logger);var after_1=system_date_1.getSystemDateValueOf();logger.debug("*******************************create unique id map ******************************************");logger.debug(after_1-before_1);logger.debug("*******************************create unique id map ******************************************")}var newUniqueId=moduleData.uniqueIdsMap[uniqueIdKey];if(!newUniqueId){logger.error("could not generate new uniqueId for '"+uniqueIdKey+"'")}return newUniqueId}exports.resolveNewId=resolveNewId;function resolveModule(coverageObject,moduleName,logger){var withLeftSlashes=files_utils_1.FilesUtils.adjustPathSlashes(moduleName);var moduleData=coverageObject[moduleName]||coverageObject[withLeftSlashes];if(!moduleData){logger.warn("Coverage object not contains data for "+moduleName+" or "+withLeftSlashes)}return moduleData}function createSLMapping(fullPath,relativePath,coverageObject,logger){var module=coverageObject[fullPath];var converter=new istanbul_unique_id_converter_1.IstanbulUniqueIdConverter(relativePath,logger);converter.createElementsArray(module);converter.process();coverageObject[fullPath].uniqueIdsMap=converter.uniqueIdsMap}})},{"../system-date":332,"../utils/files-utils":333,"./istanbul-unique-id-converter":308,path:171}],310:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../utils/validation-utils","../utils/files-utils","../source-maps-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.OriginalModuleLoader=void 0;var validation_utils_1=require("../utils/validation-utils");var files_utils_1=require("../utils/files-utils");var source_maps_utils_1=require("../source-maps-utils");var BRANCHES_MAP_KEY="branchMap";var METHODS_MAP_KEY="fnMap";var OriginalModuleLoader=function(){function OriginalModuleLoader(coverageObject,logger){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(coverageObject,"coverageObject");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this.coverageObject=coverageObject;this.logger=logger;this._fileToSourceMapConsumer={}}OriginalModuleLoader.prototype.load=function(){var _this=this;var modules=Object.keys(this.coverageObject);modules.map(function(moduleName){return _this.tryLoadOriginalModule(moduleName)})};OriginalModuleLoader.prototype.tryLoadOriginalModule=function(istanbulModule){if(!this.getSourceMapForFile(istanbulModule)){return}this.readOriginalModule(istanbulModule)};OriginalModuleLoader.prototype.readOriginalModule=function(moduleName){var _this=this;var sourceMapsReader=this.getSourceMapForFile(moduleName);var module=this.coverageObject[moduleName];Object.keys(module.branchMap).forEach(function(key){return _this.resolveAndAddBranch(module.branchMap[key],sourceMapsReader,moduleName)});Object.keys(module.fnMap).map(function(key){return _this.resolveAndAddMethod(module.fnMap[key],sourceMapsReader,moduleName)})};OriginalModuleLoader.prototype.resolveAndAddMethod=function(method,sourceMapsReader,moduleName){var originalMethod=this.createEmptyMethodObject();originalMethod.name=method.name;var originalModuleName=this.loadOriginalDataForElement(sourceMapsReader,method,moduleName,originalMethod);if(originalModuleName){this.addElementToModule(originalModuleName,originalMethod,METHODS_MAP_KEY)}};OriginalModuleLoader.prototype.resolveAndAddBranch=function(branch,sourceMapsReader,moduleName){var _this=this;var originalBranch=this.createEmptyBranchObject();originalBranch.type=branch.type;var originalModuleName=this.loadOriginalDataForElement(sourceMapsReader,branch,moduleName,originalBranch);if(originalModuleName){var originalLocations=branch.locations.map(function(locationElement){return _this.createElementSourceData(locationElement,sourceMapsReader,moduleName)});originalBranch.locations=originalLocations;this.addElementToModule(originalModuleName,originalBranch,BRANCHES_MAP_KEY)}};OriginalModuleLoader.prototype.loadOriginalDataForElement=function(sourceMapsReader,element,moduleName,originalElement){var sourceMapDataForStart=this.readSourceMapData(sourceMapsReader,element.loc.start,moduleName);var sourceMapDataForEnd=this.readSourceMapData(sourceMapsReader,element.loc.end,moduleName);if(!sourceMapDataForStart){return}originalElement.loc.start=sourceMapDataForStart.originalPosition;originalElement.line=sourceMapDataForStart.originalPosition.line;var originalModuleName=sourceMapDataForStart.originalFilename;if(sourceMapDataForEnd){originalElement.loc.end=sourceMapDataForEnd.originalPosition}if(element.decl){originalElement.decl={};var sourceMapDataForDeclStart=this.readSourceMapData(sourceMapsReader,element.decl.start,moduleName);var sourceMapDataForDeclEnd=this.readSourceMapData(sourceMapsReader,element.decl.end,moduleName);if(sourceMapDataForDeclStart){originalElement.decl.start=sourceMapDataForDeclStart.originalPosition}if(sourceMapDataForDeclEnd){originalElement.decl.end=sourceMapDataForDeclEnd.originalPosition}}return originalModuleName};OriginalModuleLoader.prototype.addElementToModule=function(moduleName,element,mapObjectKey){var module=this.getOrCreateIstanbulModule(moduleName);var key=this.createElementKey(element);if(!module[mapObjectKey][key]){module[mapObjectKey][key]=element}};OriginalModuleLoader.prototype.createElementSourceData=function(locationElement,sourceMapsReader,moduleName){var sourceMapDataForStart=this.readSourceMapData(sourceMapsReader,locationElement.start,moduleName);var sourceMapDataForEnd=this.readSourceMapData(sourceMapsReader,locationElement.end,moduleName);if(!sourceMapDataForStart&&!sourceMapDataForEnd){return{}}var sourceLocationElement={start:sourceMapDataForStart.originalPosition,end:sourceMapDataForEnd.originalPosition};return sourceLocationElement};OriginalModuleLoader.prototype.getOrCreateIstanbulModule=function(moduleName){var module=this.coverageObject[moduleName];if(!module){module=this.createIstanbulModule(moduleName);this.coverageObject[moduleName]=module}return module};OriginalModuleLoader.prototype.getSourceMapForFile=function(fullPath){if(!this._fileToSourceMapConsumer[fullPath]){this._fileToSourceMapConsumer[fullPath]=source_maps_utils_1.SourceMapsUtils.readSourceMaps(fullPath);this.logger.debug("Read source maps for file':"+fullPath+"'")}var sourceMap=this._fileToSourceMapConsumer[fullPath];return sourceMap};OriginalModuleLoader.prototype.readSourceMapData=function(sourceMaps,start,fullPath){if(!sourceMaps)return null;try{var originalPosition=sourceMaps.originalPositionFor(start);if(originalPosition&&originalPosition.source&&originalPosition.line!==null&&originalPosition.column!==null){var originalFilename=originalPosition.source;if(originalFilename.indexOf("webpack:///webpack/")===-1&&originalFilename.indexOf("webpack:///external")===-1){if(originalFilename.indexOf("webpack:///")===0){originalFilename=originalFilename.substring(11)}originalFilename=files_utils_1.FilesUtils.resolveOriginalFullFileName(fullPath,originalFilename);var originalPositionObj={line:originalPosition.line,column:originalPosition.column};var result={originalFilename:originalFilename,originalPosition:originalPositionObj};return result}}}catch(e){console.log(e)}return null};OriginalModuleLoader.prototype.createElementKey=function(element){return element.loc.start.line+":"+element.loc.start.column};OriginalModuleLoader.prototype.createEmptyBranchObject=function(){return{loc:{},locations:[],type:"",line:null}};OriginalModuleLoader.prototype.createEmptyMethodObject=function(){return{loc:{},name:"",line:null}};OriginalModuleLoader.prototype.createIstanbulModule=function(path){return{s:{},f:{},b:{},fnMap:{},statementMap:{},branchMap:{},path:path,uniqueIdsMap:null}};Object.defineProperty(OriginalModuleLoader.prototype,"fileToSourceMapConsumer",{get:function(){return this._fileToSourceMapConsumer},set:function(value){this._fileToSourceMapConsumer=value},enumerable:false,configurable:true});return OriginalModuleLoader}();exports.OriginalModuleLoader=OriginalModuleLoader})},{"../source-maps-utils":330,"../utils/files-utils":333,"../utils/validation-utils":336}],311:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./contracts","./file-element"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.UniqueIdConverter=void 0;var contracts_1=require("./contracts");var file_element_1=require("./file-element");var METHOD_DELIMITER="@";var BRANCH_DELIMITER="|";var NULL_PARAM_MESSAGE="cannot be null or undefined";var UniqueIdConverter=function(){function UniqueIdConverter(filename,logger){if(!filename){throw new Error("'filename' "+NULL_PARAM_MESSAGE)}if(!logger){throw new Error("'logger' "+NULL_PARAM_MESSAGE)}this._filename=filename;this.logger=logger;this._uniqueIdsMap={};this._methodsArray=[];this._branchesArray=[]}UniqueIdConverter.prototype.sortElements=function(){this._methodsArray=this._methodsArray.sort(this.comparePosition);this._branchesArray=this._branchesArray.sort(this.comparePosition)};UniqueIdConverter.prototype.createElementsArray=function(file){file.methods=file.methods||[];file.branches=file.branches||[];this.fillFileElementsArray(file.methods,this._methodsArray,contracts_1.ElementType.METHOD);this.fillFileElementsArray(file.branches,this._branchesArray,contracts_1.ElementType.BRANCH)};UniqueIdConverter.prototype.createFileElement=function(element,filename,type){var startPosition=this.createElementPosition(element.position);var endPosition=this.createElementPosition(element.endPosition);var fileElement=new file_element_1.FileElement(type,startPosition,endPosition,element.uniqueId,filename);if(element.uniqueId_decl){fileElement.uniqueIdKey_decl=element.uniqueId_decl}if(element.parentPosition){var index=element.index||0;fileElement.startPosition=this.createElementPosition(element.parentPosition);fileElement.index=index}
30
- return fileElement};UniqueIdConverter.prototype.process=function(){this.removeDuplicateElements(this._methodsArray);this.removeDuplicateElements(this._branchesArray);this.sortElements();this.logger.debug("sorted "+this._branchesArray.length+" branches");this.logger.debug("sorted "+this._methodsArray.length+" methods");this.fillUniqueIdsMap()};UniqueIdConverter.prototype.setAndInitFile=function(file){this.createElementsArray(file)};UniqueIdConverter.prototype.createElementPosition=function(position){var line;var column;if(Array.isArray(position)&&position.length===2){line=parseInt(position[0]);column=parseInt(position[1])}else{throw new Error("element has no correct startPosition array, cannot resolve startPosition")}return{column:column,line:line}};UniqueIdConverter.prototype.fillFileElementsArray=function(elements,array,type){for(var _i=0,elements_1=elements;_i<elements_1.length;_i++){var element=elements_1[_i];array.push(this.createFileElement(element,this._filename,type))}};UniqueIdConverter.prototype.fillUniqueIdsMap=function(){this.createNewUniqueIds(this._methodsArray,METHOD_DELIMITER);this.createNewUniqueIds(this._branchesArray,BRANCH_DELIMITER)};UniqueIdConverter.prototype.createNewUniqueIds=function(array,delimiter){var aggregatedByLine=this.aggregateElementsByLine(array);var lines=Object.keys(aggregatedByLine);for(var _i=0,lines_1=lines;_i<lines_1.length;_i++){var line=lines_1[_i];var indexesArray=aggregatedByLine[line];for(var i=0;i<indexesArray.length;i++){var currentIndex=indexesArray[i];var currentElement=array[currentIndex];currentElement.uniqueId=currentElement.filename+delimiter+line+","+i;this.logger.debug("[UniqueIdConverter] uniqueId "+currentElement.uniqueIdKey+" converted to \n "+currentElement.uniqueId);this._uniqueIdsMap[currentElement.uniqueIdKey]=currentElement.uniqueId;if(currentElement.uniqueIdKey_decl){this._uniqueIdsMap[currentElement.uniqueIdKey_decl]=currentElement.uniqueId}}}};UniqueIdConverter.prototype.comparePosition=function(elm1,elm2){if(elm1.startPosition.line<elm2.startPosition.line){return-1}if(elm1.startPosition.line>elm2.startPosition.line){return 1}if(elm1.startPosition.column<elm2.startPosition.column){return-1}if(elm1.startPosition.column>elm2.startPosition.column){return 1}if(elm1.index<elm2.index){return-1}if(elm1.index>elm2.index){return 1}return 0};Object.defineProperty(UniqueIdConverter.prototype,"uniqueIdsMap",{get:function(){return this._uniqueIdsMap},enumerable:false,configurable:true});Object.defineProperty(UniqueIdConverter.prototype,"methodsArray",{get:function(){return this._methodsArray},set:function(value){this._methodsArray=value},enumerable:false,configurable:true});Object.defineProperty(UniqueIdConverter.prototype,"branchesArray",{get:function(){return this._branchesArray},set:function(value){this._branchesArray=value},enumerable:false,configurable:true});Object.defineProperty(UniqueIdConverter.prototype,"filename",{get:function(){return this._filename},enumerable:false,configurable:true});UniqueIdConverter.prototype.removeDuplicateElements=function(elementsArray){var _this=this;var existedKeys={};elementsArray=elementsArray.filter(function(element){return _this.filterDuplicates(element,existedKeys)})};UniqueIdConverter.prototype.filterDuplicates=function(element,existedKeys){if(existedKeys[element.uniqueIdKey]||element.uniqueIdKey_decl&&existedKeys[element.uniqueIdKey_decl]){return false}existedKeys[element.uniqueIdKey]=true;if(element.uniqueIdKey_decl){existedKeys[element.uniqueIdKey_decl]=true}return true};UniqueIdConverter.prototype.removeBranchesOutOfMethods=function(){var validBranches=[];var methodsIndex=0;for(var _i=0,_a=this._branchesArray;_i<_a.length;_i++){var branch=_a[_i];for(var i=methodsIndex;i<this._methodsArray.length;i++){var currentMethod=this._methodsArray[i];var branchPosition=this.checkBranchPosition(branch,currentMethod);if(branchPosition===0){validBranches.push(branch);break}if(branchPosition===1){methodsIndex++}}}this._branchesArray=validBranches.sort(this.comparePosition)};UniqueIdConverter.prototype.checkBranchPosition=function(branch,method){if(branch.isStartsAfter(method)&&branch.isEndsBefore(method)){return 0}if(branch.isStartsBefore(method)&&branch.isEndsBefore(method)){return-1}if(branch.isStartsAfter(method)&&branch.isEndsAfter(method)){return 1}this.logger.warn("branch started at '"+branch.startPosition.line+","+branch.startPosition.column+"' in file '"+this._filename+"' located across methods, probably some error");return 0};UniqueIdConverter.prototype.aggregateElementsByLine=function(elements){var aggregated={};for(var i=0;i<elements.length;i++){var element=elements[i];var lineNumber=element.startPosition.line;if(!aggregated[lineNumber]){aggregated[lineNumber]=[]}aggregated[lineNumber].push(i)}return aggregated};return UniqueIdConverter}();exports.UniqueIdConverter=UniqueIdConverter})},{"./contracts":306,"./file-element":307}],312:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TestSelectionStatus=exports.EventTypes=void 0;var EventTypes;(function(EventTypes){EventTypes["AgentStarted"]="agentStarted";EventTypes["ExecutionIdStarted"]="executionIdStarted";EventTypes["ExecutionIdEnded"]="executionIdEnded";EventTypes["TestStart"]="testStart";EventTypes["TestEnd"]="testEnd"})(EventTypes=exports.EventTypes||(exports.EventTypes={}));var TestSelectionStatus;(function(TestSelectionStatus){TestSelectionStatus["RECOMMENDED_TESTS"]="recommendedTests";TestSelectionStatus["DISABLED"]="disabled";TestSelectionStatus["DISABLED_BY_CONFIGURATION"]="disabledByConfiguration";TestSelectionStatus["RECOMMENDATIONS_TIMEOUT"]="recommendationsTimeout";TestSelectionStatus["ERROR"]="error"})(TestSelectionStatus=exports.TestSelectionStatus||(exports.TestSelectionStatus={}))})},{}],313:[function(require,module,exports){var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./events-contracts","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EventsCreator=void 0;var events_contracts_1=require("./events-contracts");var system_date_1=require("../system-date");var EventsCreator=function(){function EventsCreator(){}EventsCreator.createTestStartedEvent=function(executionId,framework,testName,duration){var eventBase=this.createEvent(events_contracts_1.EventTypes.TestStart,executionId,framework);var startTimeStamp=system_date_1.getSystemDateValueOf()-duration;eventBase.localTime=startTimeStamp;return __assign(__assign({},eventBase),{testName:testName})};EventsCreator.createTestEndEvent=function(executionId,framework,testName,result,duration){var eventBase=this.createEvent(events_contracts_1.EventTypes.TestEnd,executionId,framework);return __assign(__assign({},eventBase),{result:result,duration:duration,testName:testName})};EventsCreator.createEvent=function(type,executionId,framework){return{type:type,executionId:executionId,framework:framework,localTime:system_date_1.getSystemDateValueOf()}};return EventsCreator}();exports.EventsCreator=EventsCreator})},{"../system-date":332,"./events-contracts":312}],314:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../utils/validation-utils","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EventsProcess=void 0;var validation_utils_1=require("../utils/validation-utils");var system_date_1=require("../system-date");var EventsProcess=function(){function EventsProcess(configuration,agentInstanceData,sendToServerWatchdog,keepAliveWatchdog,environmentDataService,backendProxy,eventsQueue,logger){this._isRunning=false;this.sequence=0;this._onGoingRequests=[];validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(configuration,"configuration");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentInstanceData,"agentInstanceData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(sendToServerWatchdog,"sendToServerWatchdog");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(keepAliveWatchdog,"keepAliveWatchdog");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(environmentDataService,"environmentData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(backendProxy,"backendProxy");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(eventsQueue,"eventsQueue");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this._configuration=configuration;this._agentInstanceData=agentInstanceData;this._sendToServerWatchdog=sendToServerWatchdog;this.keepAliveWatchdog=keepAliveWatchdog;this.environmentData=environmentDataService;this._backendProxy=backendProxy;this._logger=logger;this._eventsQueue=eventsQueue;this.init()}EventsProcess.prototype.enqueueEvent=function(evt){evt.localTime=evt.localTime||system_date_1.getSystemDateValueOf();this._eventsQueue.enqueue(evt);if(this.isRunning&&this.configuration.sendEvents.value&&this.configuration.enabled.value){this.ensureKeepaliveThreadRunning()}};EventsProcess.prototype.start=function(){if(this._isRunning||!this._configuration.enabled.value){return}this._sendToServerWatchdog.start();if(this._eventsQueue.getQueueSize()>0){this.ensureKeepaliveThreadRunning()}this._isRunning=true};EventsProcess.prototype.stop=function(){return __awaiter(this,void 0,void 0,function(){var e_1;return __generator(this,function(_a){switch(_a.label){case 0:this._sendToServerWatchdog.stop();this.keepAliveWatchdog.stop();if(this._configuration.enabled.value===false||this._configuration.sendEvents.value===false){return[2]}_a.label=1;case 1:_a.trys.push([1,4,,5]);return[4,Promise.all(this._onGoingRequests)];case 2:_a.sent();return[4,this.submitEventsSync()];case 3:_a.sent();return[3,5];case 4:e_1=_a.sent();this._logger.warn("Error while stopping EventsProcess: ",e_1);return[3,5];case 5:this._isRunning=false;return[2]}})})};EventsProcess.prototype.getQueueSize=function(){return this._eventsQueue.getQueueSize()};EventsProcess.prototype.submitEvents=function(){var _this=this;if(!this._isRunning||!this._configuration.sendEvents.value||!this._configuration.enabled.value||this._eventsQueue.getQueueSize()==0){return}var items=this._eventsQueue.dequeue(EventsProcess.ITEMS_TO_DEQUE);var packet=this.createEventsPacket(items);var promise=this._backendProxy.submitEventsPromise(packet);this._onGoingRequests.push(promise);promise.then(function(){if(_this._eventsQueue.getQueueSize()>0){_this.submitEvents()}_this.removeRequest(promise)}).catch(function(err){_this._logger.warn("Error while submitting events, "+err);_this._eventsQueue.requeue(items);_this.removeRequest(promise)})};EventsProcess.prototype.submitEventsSync=function(){return __awaiter(this,void 0,void 0,function(){var items,packet,e_2;return __generator(this,function(_a){switch(_a.label){case 0:_a.trys.push([0,4,,5]);_a.label=1;case 1:if(!(this._eventsQueue.getQueueSize()>0))return[3,3];items=this._eventsQueue.dequeue(EventsProcess.ITEMS_TO_DEQUE);packet=this.createEventsPacket(items);return[4,this._backendProxy.submitEventsPromise(packet)];case 2:_a.sent();return[3,1];case 3:return[3,5];case 4:e_2=_a.sent();this._logger.warn("Error while sending events synchronously. "+e_2);return[3,5];case 5:return[2]}})})};EventsProcess.prototype.createEventsPacket=function(items){return{customerId:this._configuration.customerId.value,appName:this._configuration.appName.value,build:this._configuration.build.value,branch:this._configuration.branch.value,environment:this.environmentData,configurationData:this._configuration.toJsonObject,testSelectionStatus:this._testSelectionStatus,events:items,meta:{sequence:++this.sequence,generated:system_date_1.getSystemDateValueOf(),agentId:this._agentInstanceData.agentId}}};EventsProcess.prototype.init=function(){var _this=this;this._sendToServerWatchdog.on("alarm",function(){return _this.submitEvents()});this._eventsQueue.on("full",function(){return _this.submitEvents()});this.keepAliveWatchdog.on("alarm",function(){if(_this.eventsQueue.getQueueSize()==0){_this.keepAliveWatchdog.stop()}})};EventsProcess.prototype.ensureKeepaliveThreadRunning=function(){this.keepAliveWatchdog.start()};EventsProcess.prototype.removeRequest=function(request){var index=this._onGoingRequests.indexOf(request);this._onGoingRequests.splice(index,1)};Object.defineProperty(EventsProcess.prototype,"onGoingRequests",{get:function(){return this._onGoingRequests},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"configuration",{get:function(){return this._configuration},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"logger",{get:function(){return this._logger},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"isRunning",{get:function(){return this._isRunning},set:function(value){this._isRunning=value},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"sendToServerWatchdog",{get:function(){return this._sendToServerWatchdog},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"backendProxy",{get:function(){return this._backendProxy},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"eventsQueue",{get:function(){return this._eventsQueue},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"testSelectionStatus",{get:function(){return this._testSelectionStatus},set:function(testSelectionStatus){this._testSelectionStatus=testSelectionStatus},enumerable:false,configurable:true});EventsProcess.ITEMS_TO_DEQUE=1e3;return EventsProcess}();exports.EventsProcess=EventsProcess})},{"../system-date":332,"../utils/validation-utils":336}],315:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./location-formatter","../../common/footprints-process-v6/hits-converter","../utils/files-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BaseBrowserHitsConverter=void 0;var location_formatter_1=require("./location-formatter");var hits_converter_1=require("../../common/footprints-process-v6/hits-converter");var files_utils_1=require("../utils/files-utils");var BaseBrowserHitsConverter=function(_super){__extends(BaseBrowserHitsConverter,_super);function BaseBrowserHitsConverter(relativePathResolver,buildSessionId,logger){var _this=_super.call(this,relativePathResolver,{},{},logger)||this;_this.buildSessionId=buildSessionId;return _this}BaseBrowserHitsConverter.prototype.getMethodUniqueId=function(startLoc,relativePath,absolutePath){var uniqueId=absolutePath+hits_converter_1.HitsConverter.METHOD_ID_DEL+this.formatLoc(startLoc);return this.tryGetUniqueIdFromSlMapping(uniqueId)};BaseBrowserHitsConverter.prototype.getBranchUniqueId=function(startLoc,relativePath,absolutePath,leaveIndex){var uniqueId=absolutePath+hits_converter_1.HitsConverter.BRANCH_ID_DEL+this.formatLoc(startLoc)+hits_converter_1.HitsConverter.BRANCH_ID_DEL+leaveIndex;return this.tryGetUniqueIdFromSlMapping(uniqueId)};BaseBrowserHitsConverter.prototype.getDeclStart=function(hit){var decl=this.getDecl(hit);return decl.start||decl.st};BaseBrowserHitsConverter.prototype.getDecl=function(hit){return hit.decl||hit.d};BaseBrowserHitsConverter.prototype.getStartLoc=function(hit){var loc=hit.loc||hit.lc;return loc.start||loc.st};BaseBrowserHitsConverter.prototype.getLeaveStartLoc=function(hit,leaveIdx){var locations=hit.branchData.locations||hit.branchData.lcs;return locations[leaveIdx].start||locations[leaveIdx].st};BaseBrowserHitsConverter.prototype.formatLoc=function(loc){return location_formatter_1.formatLocation(loc,this.logger)};BaseBrowserHitsConverter.prototype.tryGetUniqueIdFromSlMapping=function(rawUniqueId){rawUniqueId=files_utils_1.FilesUtils.adjustPathSlashes(rawUniqueId);var mapping=this.getSlMapping()||{};return mapping[rawUniqueId]||rawUniqueId};return BaseBrowserHitsConverter}(hits_converter_1.HitsConverter);exports.BaseBrowserHitsConverter=BaseBrowserHitsConverter})},{"../../common/footprints-process-v6/hits-converter":319,"../utils/files-utils":333,"./location-formatter":321}],316:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BufferSizeHelper=void 0;var BufferSizeHelper=function(){function BufferSizeHelper(){this.uniqueIdsLengthSum=0;this.testNamesCount=0;this.testNamesLengthSum=0;this.hitCount=0;this.indicesCount=0;this.uniqueIdsCount=0}BufferSizeHelper.prototype.calculateBufferSize=function(){var sizeInBytes=this.uniqueIdsCount*BufferSizeHelper.FOUR_BYTES+this.uniqueIdsLengthSum+(this.testNamesCount*BufferSizeHelper.FOUR_BYTES+this.testNamesLengthSum)+this.hitCount*BufferSizeHelper.APPROX_HIT_SIZE+this.indicesCount*BufferSizeHelper.EIGHT_BYTES;return sizeInBytes/BufferSizeHelper.MB};BufferSizeHelper.prototype.incrementSizeCounters=function(testName,methodIndicesSize,branchIndicesSize){this.hitCount++;this.indicesCount+=methodIndicesSize+branchIndicesSize;if(testName){this.testNamesCount++;this.testNamesLengthSum+=testName.length}};BufferSizeHelper.FOUR_BYTES=4;BufferSizeHelper.EIGHT_BYTES=8;BufferSizeHelper.APPROX_HIT_SIZE=128;BufferSizeHelper.MB=1024*1024;return BufferSizeHelper}();exports.BufferSizeHelper=BufferSizeHelper})},{}],317:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../agent-events/cockpit-notifier","../agent-events/agent-events-conracts","events","./buffer-size-helper"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsBuffer=void 0;var cockpit_notifier_1=require("../agent-events/cockpit-notifier");var agent_events_conracts_1=require("../agent-events/agent-events-conracts");var events=require("events");var buffer_size_helper_1=require("./buffer-size-helper");var FootprintsBuffer=function(_super){__extends(FootprintsBuffer,_super);function FootprintsBuffer(agentInstanceData,agentConfig){var _this=_super.call(this)||this;_this.formatVersion="6.0";_this.agentInstanceData=agentInstanceData;_this._agentConfig=agentConfig;_this.currentBufferSize=0;_this.resetState();_this.meta={agentId:_this.agentInstanceData.agentId,intervals:{timedFootprintsCollectionIntervalSeconds:_this._agentConfig.footprintsCollectIntervalSecs.value},labId:_this._agentConfig.labId.value};return _this}FootprintsBuffer.prototype.addHit=function(footprints,collectionInterval,executionId,testName,isInitFootprints,isFinalFootprints){cockpit_notifier_1.CockpitNotifier.sendEventOnce(agent_events_conracts_1.AgentEventCode.FIRST_TIME_COLLECTED_FP);var methodIndices=this.addOrGetIndices(footprints.methods,true);var branchIndices=this.addOrGetIndices(footprints.branches,false);var executionIdx=this.addOrGetExecutionIndex(executionId);this.executions[executionIdx].hits.push({branches:branchIndices,methods:methodIndices,start:collectionInterval.start,end:collectionInterval.end,testName:testName,isInitFootprints:isInitFootprints,isFinalFootprints:isFinalFootprints});this.bufferSizeHelper.incrementSizeCounters(testName,methodIndices.length,branchIndices.length);this.verifyBufferSize()};FootprintsBuffer.prototype.createPacket=function(){var packet=this.toJson();this.resetState();return packet};FootprintsBuffer.prototype.resetState=function(){this.branches=[];this.methods=[];this.executions=[];this.methodIdToIndex=new Map;this.branchIdToIndex=new Map;this.bufferSizeHelper=new buffer_size_helper_1.BufferSizeHelper};FootprintsBuffer.prototype.hasHitsInBuffer=function(){return this.executions.length>0};Object.defineProperty(FootprintsBuffer.prototype,"agentConfig",{get:function(){return this._agentConfig},set:function(value){this._agentConfig=value},enumerable:false,configurable:true});FootprintsBuffer.prototype.toJson=function(){if(!this.executions||!this.executions.length){return null}return{formatVersion:this.formatVersion,branches:this.branches,executions:this.executions,meta:this.meta,methods:this.methods,moduleName:this.moduleName}};FootprintsBuffer.prototype.addOrGetIndices=function(elementIds,isMethods){var _this=this;var map=isMethods?this.methodIdToIndex:this.branchIdToIndex;var arr=isMethods?this.methods:this.branches;var indices=[];elementIds.forEach(function(id){if(!map.get(id)){_this.bufferSizeHelper.uniqueIdsLengthSum+=id.length;_this.bufferSizeHelper.uniqueIdsCount++;var position=arr.push(id);map.set(id,position-1)}indices.push(map.get(id))});return indices};FootprintsBuffer.prototype.addOrGetExecutionIndex=function(executionId){var index=-1;this.executions.every(function(execution,idx){if(executionId==execution.executionId){index=idx;return false}return true});return index!=-1?index:this.executions.push({executionId:executionId,hits:[]})-1};FootprintsBuffer.prototype.verifyBufferSize=function(){if(this.bufferSizeHelper.calculateBufferSize()>=this._agentConfig.footprintsBufferThresholdMb.value){this.emit(FootprintsBuffer.BUFFER_FULL)}};FootprintsBuffer.BUFFER_FULL="bufferFull";return FootprintsBuffer}(events.EventEmitter);exports.FootprintsBuffer=FootprintsBuffer})},{"../agent-events/agent-events-conracts":289,"../agent-events/cockpit-notifier":294,"./buffer-size-helper":316,events:110}],318:[function(require,module,exports){(function(global){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../constants/sl-env-vars","../coverage-elements/original-module-loader"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HitsCollector=void 0;var sl_env_vars_1=require("../constants/sl-env-vars");var original_module_loader_1=require("../coverage-elements/original-module-loader");var GLOBAL_ISTANBUL_CONTAINER_NAMES=["__coverage__"];var HitsCollector=function(){function HitsCollector(logger,globalCoverageObject){this.logger=logger;this._globalCoverageObject=globalCoverageObject;this.latestCoverageSnapshot={}}HitsCollector.prototype.getHitElements=function(){var hitFilesData=[];var globalCoverage=this.getGlobalCoverageObject();if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){new original_module_loader_1.OriginalModuleLoader(globalCoverage,this.logger).load()}for(var filename in globalCoverage){var _a=this.getFileCoverageObjects(filename),fileCoverageSnapshot=_a.fileCoverageSnapshot,currentFileCoverage=_a.currentFileCoverage,shouldResolveRelativePath=_a.shouldResolveRelativePath;var hitMethods=this.getHitMethods(currentFileCoverage,fileCoverageSnapshot);var hitBranches=this.getHitBranches(currentFileCoverage,fileCoverageSnapshot);if(hitMethods.length||hitBranches.length){hitFilesData.push({filename:filename,hitMethods:hitMethods,hitBranches:hitBranches,shouldResolveRelativePath:shouldResolveRelativePath})}}this.updateCoverageSnapshot(globalCoverage);return hitFilesData};Object.defineProperty(HitsCollector.prototype,"latestCoverageSnapshot",{get:function(){return this._latestCoverageSnapshot},set:function(value){this._latestCoverageSnapshot=value},enumerable:false,configurable:true});Object.defineProperty(HitsCollector.prototype,"globalCoverageObject",{get:function(){return this._globalCoverageObject},set:function(value){this._globalCoverageObject=value},enumerable:false,configurable:true});HitsCollector.prototype.getHitMethods=function(currentHits,snapshotHits){var hitMethodsIndices=Object.keys(currentHits.f).filter(function(id){snapshotHits.f[id]=snapshotHits.f[id]||0;return currentHits.f[id]>snapshotHits.f[id]});return hitMethodsIndices.map(function(id){return currentHits.fnMap[id]})};HitsCollector.prototype.dropHits=function(){this.updateCoverageSnapshot(this.getGlobalCoverageObject())};HitsCollector.prototype.getHitLeaves=function(currentLeaveHits,snapshotLeaveHits){var hitLeavesIndices=[];snapshotLeaveHits=snapshotLeaveHits||Array(currentLeaveHits.length).fill(0);currentLeaveHits.forEach(function(leaveHit,leaveIdx){if(currentLeaveHits[leaveIdx]>snapshotLeaveHits[leaveIdx]){hitLeavesIndices.push(leaveIdx)}});return hitLeavesIndices};HitsCollector.prototype.getHitBranches=function(currentHits,fileHitSnapshot){var hitBranches=[];for(var branchIdx in currentHits.b){var hitLeaves=this.getHitLeaves(currentHits.b[branchIdx],fileHitSnapshot.b[branchIdx]);if(hitLeaves.length>0){var branchData=currentHits.branchMap[branchIdx];hitBranches.push({branchData:branchData,hitLeaves:hitLeaves})}}return hitBranches};HitsCollector.prototype.createEmptyIstanbulModule=function(path,useDataKey){if(useDataKey===void 0){useDataKey=false}var emptyModule={f:{},fnMap:{},b:{},branchMap:{},path:path,s:{}};if(useDataKey){return{data:emptyModule}}return emptyModule};HitsCollector.prototype.getFileCoverageObjects=function(filename){var fileCoverageSnapshot=this._latestCoverageSnapshot[filename]||this.createEmptyIstanbulModule(filename);var currentFileCoverage=this._globalCoverageObject[filename];var shouldResolveRelativePath=true;if(!fileCoverageSnapshot.f&&fileCoverageSnapshot.data){fileCoverageSnapshot=fileCoverageSnapshot.data;shouldResolveRelativePath=false}if(!currentFileCoverage.f&&currentFileCoverage.data){currentFileCoverage=currentFileCoverage.data}return{fileCoverageSnapshot:fileCoverageSnapshot,currentFileCoverage:currentFileCoverage,shouldResolveRelativePath:shouldResolveRelativePath}};HitsCollector.prototype.getGlobalCoverageObject=function(){if(this._globalCoverageObject)return this._globalCoverageObject;this._globalCoverageObject=HitsCollector.resolveGlobalCoverageObject();if(!this._globalCoverageObject){this.logger.warn("Coverage object not found")}return this._globalCoverageObject};HitsCollector.resolveGlobalCoverageObject=function(){var re=/^\$\$cov_[0-9]+\$\$$/;var keys=Object.keys(global);for(var i=0;i<keys.length;i++){var k=keys[i];if(re.exec(k)!==null||GLOBAL_ISTANBUL_CONTAINER_NAMES.indexOf(k)>=0){return global[k]}}};HitsCollector.prototype.updateCoverageSnapshot=function(currentCounters){for(var istanbulModule in currentCounters){var useDataKey=currentCounters[istanbulModule].data!==undefined;this._latestCoverageSnapshot[istanbulModule]=this._latestCoverageSnapshot[istanbulModule]||this.createEmptyIstanbulModule(istanbulModule,useDataKey);var f=currentCounters[istanbulModule].f||currentCounters[istanbulModule].data.f;var b=currentCounters[istanbulModule].b||currentCounters[istanbulModule].data.b;for(var funcId in f){this.setFunctionHit(istanbulModule,funcId,f,useDataKey)}for(var branchId in b){this.setBranchHit(b,branchId,istanbulModule,useDataKey)}}};HitsCollector.prototype.setBranchHit=function(b,branchId,istanbulModule,useDataKey){var currentBranchesHits=b[branchId];this._latestCoverageSnapshot[istanbulModule].b[branchId]=this._latestCoverageSnapshot[istanbulModule].b[branchId]||[];for(var i=0;i<currentBranchesHits.length;i++){if(useDataKey){this._latestCoverageSnapshot[istanbulModule].data.b[branchId][i]=currentBranchesHits[i]}else{this._latestCoverageSnapshot[istanbulModule].b[branchId][i]=currentBranchesHits[i]}}};HitsCollector.prototype.setFunctionHit=function(istanbulModule,funcId,f,useDataKey){if(useDataKey){this._latestCoverageSnapshot[istanbulModule].data.f[funcId]=f[funcId]}else{this._latestCoverageSnapshot[istanbulModule].f[funcId]=f[funcId]}};return HitsCollector}();exports.HitsCollector=HitsCollector})}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../constants/sl-env-vars":305,"../coverage-elements/original-module-loader":310}],319:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v
31
- }else if(typeof define==="function"&&define.amd){define(["require","exports","../constants/sl-env-vars","../coverage-elements/original-module-loader","./hits-collector","../coverage-elements/new-id-resolver","../agent-events/cockpit-notifier"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HitsConverter=void 0;var sl_env_vars_1=require("../constants/sl-env-vars");var original_module_loader_1=require("../coverage-elements/original-module-loader");var hits_collector_1=require("./hits-collector");var new_id_resolver_1=require("../coverage-elements/new-id-resolver");var cockpit_notifier_1=require("../agent-events/cockpit-notifier");var HitsConverter=function(){function HitsConverter(relativePathResolver,sourceMapData,projectRoot,logger){this.conversionErrors=[];this.relativePathResolver=relativePathResolver;this.sourceMapData=sourceMapData;this.projectRoot=projectRoot;this.logger=logger}HitsConverter.prototype.convertHits=function(hitFilesData){var _this=this;var methodUniqueIds=[];var branchUniqueIds=[];if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){new original_module_loader_1.OriginalModuleLoader(hits_collector_1.HitsCollector.resolveGlobalCoverageObject(),this.logger).load()}hitFilesData.forEach(function(fileHit){var relativePath=fileHit.filename;if(fileHit.shouldResolveRelativePath){relativePath=_this.relativePathResolver.getRelativePath(fileHit.filename)}methodUniqueIds=methodUniqueIds.concat(_this.createMethodIds(fileHit.hitMethods,relativePath,fileHit.filename));branchUniqueIds=branchUniqueIds.concat(_this.createBranchIds(fileHit.hitBranches,relativePath,fileHit.filename))});this.sendConversionErrors();return{branches:branchUniqueIds,methods:methodUniqueIds}};HitsConverter.prototype.createMethodIds=function(hitFunctions,relativePath,absolutePath){var _this=this;var methodIds=[];hitFunctions.forEach(function(hit){methodIds.push(_this.getMethodUniqueId(_this.getStartLoc(hit),relativePath,absolutePath));if(_this.getDecl(hit)&&_this.getDeclStart(hit)){methodIds.push(_this.getMethodUniqueId(_this.getDeclStart(hit),relativePath,absolutePath))}});return methodIds};HitsConverter.prototype.getDeclStart=function(hit){return hit.decl.start};HitsConverter.prototype.getDecl=function(hit){return hit.decl};HitsConverter.prototype.getStartLoc=function(hit){return hit.loc.start};HitsConverter.prototype.getLeaveStartLoc=function(hit,leaveIdx,absolutePath){var _a;var position=hit.branchData.locations[leaveIdx].start;var parentPosition=(_a=hit.branchData.loc)===null||_a===void 0?void 0:_a.start;if(!parentPosition){if(!sl_env_vars_1.SlEnvVars.isUseIstanbul()){var message="'SL_useIstanbul' was set to 'false' but could not find 'loc' object. branch in file '"+absolutePath+"' at '"+JSON.stringify(position)+"'";this.logger.error(message);this.conversionErrors.push(message)}else{this.logger.debug("Using branch position from 'locations' object due to 'SL_useIstanbul' set to 'true'")}return position}var newInstrumentation=parentPosition.line!=position.line||parentPosition.column!=position.column;if(hit.branchData.type==="if"){var message=newInstrumentation?"Instrumented done by istanbul-lib-instrumenter greater or equal than 5.1.0 enforcing parent positions for the else leave":"Instrumented done by istanbul-lib-instrumenter lower than 5.1.0 using parent positions for the else leave";this.logger.debug(message);return parentPosition}return position};HitsConverter.prototype.createBranchIds=function(hitFunctions,relativePath,absolutePath){var _this=this;var branchIds=[];hitFunctions.forEach(function(hit){hit.hitLeaves.forEach(function(leaveIdx){branchIds.push(_this.getBranchUniqueId(_this.getLeaveStartLoc(hit,leaveIdx,absolutePath),relativePath,absolutePath,leaveIdx))})});return branchIds};HitsConverter.prototype.getMethodUniqueId=function(startLoc,relativePath,absolutePath){var idParts=this.resolveIdParts(startLoc,relativePath,absolutePath);if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){var uniqueIdKey=idParts.relativePath+"@"+this.formatLoc(idParts.start);var uniqueId=new_id_resolver_1.resolveNewId(uniqueIdKey,idParts.absolutePath,idParts.relativePath,hits_collector_1.HitsCollector.resolveGlobalCoverageObject(),this.logger);if(uniqueId){return uniqueId}}return this.buildMethodUniqueId(idParts)};HitsConverter.prototype.getBranchUniqueId=function(startLoc,relativePath,absolutePath,leaveIndex){var uniqueId;var parts=this.resolveIdParts(startLoc,relativePath,absolutePath);if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){var uniqueIdKey=parts.relativePath+"|"+this.formatLoc(parts.start)+"|"+leaveIndex;uniqueId=new_id_resolver_1.resolveNewId(uniqueIdKey,parts.absolutePath,parts.relativePath,hits_collector_1.HitsCollector.resolveGlobalCoverageObject(),this.logger)}if(!uniqueId){uniqueId=parts.relativePath+HitsConverter.BRANCH_ID_DEL+this.formatLoc(parts.start)+HitsConverter.BRANCH_ID_DEL+leaveIndex}return uniqueId};HitsConverter.prototype.resolveIdParts=function(startLoc,relativePath,absolutePath){var sourcePosition=this.sourceMapData.getSourcePosition(relativePath,absolutePath,startLoc,this.projectRoot);return sourcePosition?sourcePosition:{relativePath:relativePath,start:startLoc,absolutePath:absolutePath}};HitsConverter.prototype.buildMethodUniqueId=function(parts){return parts.relativePath+HitsConverter.METHOD_ID_DEL+this.formatLoc(parts.start)};HitsConverter.prototype.sendConversionErrors=function(){if(this.conversionErrors.length>0){cockpit_notifier_1.CockpitNotifier.sendErrorsBatch(this.conversionErrors);this.conversionErrors=[]}};HitsConverter.prototype.formatLoc=function(loc){return loc.line+","+loc.column};HitsConverter.METHOD_ID_DEL="@";HitsConverter.BRANCH_ID_DEL="|";return HitsConverter}();exports.HitsConverter=HitsConverter})},{"../agent-events/cockpit-notifier":294,"../constants/sl-env-vars":305,"../coverage-elements/new-id-resolver":309,"../coverage-elements/original-module-loader":310,"./hits-collector":318}],320:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./footprints-buffer","../footprints-process/collection-interval","../state-tracker","../agent-events/cockpit-notifier","../agent-events/agent-events-conracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsProcess=void 0;var footprints_buffer_1=require("./footprints-buffer");var collection_interval_1=require("../footprints-process/collection-interval");var state_tracker_1=require("../state-tracker");var cockpit_notifier_1=require("../agent-events/cockpit-notifier");var agent_events_conracts_1=require("../agent-events/agent-events-conracts");var FootprintsProcess=function(){function FootprintsProcess(cfg,sendToServerWatchdog,keepaliveWatchdog,logger,hitsCollector,hitsConverter,footprintsBuffer,backendProxy,stateTracker){this.isRunning=false;this.ongoingRequestsCounter=0;this.footprintsEnqueueOnce=false;this.cfg=cfg;this.sendToServerWatchdog=sendToServerWatchdog;this.keepaliveWatchdog=keepaliveWatchdog;this.footprintsBuffer=footprintsBuffer;this.hitsConverter=hitsConverter;this.hitsCollector=hitsCollector;this.backendProxy=backendProxy;this.collectionInterval=new collection_interval_1.CollectionInterval(cfg.interval.value);this.stateTracker=stateTracker;this.logger=logger;this.delegateEvents()}FootprintsProcess.prototype.enqueueCurrentFootprints=function(executionId,testName,executionBsid,isFinalFootprints){if(isFinalFootprints===void 0){isFinalFootprints=false}this.currentExecutionBsid=executionBsid;this.collectionInterval.next();var hitFilesData=this.hitsCollector.getHitElements();if(hitFilesData.length){this.logger.info("Collecting hits for '"+hitFilesData.length+"' files");var convertedHits=this.hitsConverter.convertHits(hitFilesData);this.footprintsBuffer.addHit(convertedHits,this.collectionInterval.toJson(),executionId,testName,this.isInitFootprints(),isFinalFootprints)}else{this.logger.info("No files were hits, not collecting footprints")}if(this.isRunning&&this.cfg.sendFootprints.value&&this.cfg.enabled.value){this.ensureKeepaliveThreadRunning();this.sendToServerWatchdog.start()}this.footprintsEnqueueOnce=true};FootprintsProcess.prototype.updateConfig=function(updatedCfg){this.cfg=updatedCfg;if(updatedCfg.sendFootprints.value===false||updatedCfg.enabled.value===false){cockpit_notifier_1.CockpitNotifier.sendEvent(agent_events_conracts_1.AgentEventCode.AGENT_MUTED);this.footprintsBuffer.resetState();this.stop(function(){})}this.sendToServerWatchdog.setInterval(this.cfg.footprintsSendIntervalSecs.value);this.footprintsBuffer.agentConfig=updatedCfg};FootprintsProcess.prototype.ensureKeepaliveThreadRunning=function(){this.keepaliveWatchdog.start()};FootprintsProcess.prototype.submitQueuedFootprints=function(){return __awaiter(this,void 0,void 0,function(){var packet,e_1;return __generator(this,function(_a){switch(_a.label){case 0:if(!this.shouldSubmitFootprints()){return[2]}packet=this.footprintsBuffer.createPacket();if(!packet)return[3,6];this.ongoingRequestsCounter++;_a.label=1;case 1:_a.trys.push([1,3,4,5]);return[4,this.backendProxy.submitFootprintsV6(packet,this.currentExecutionBsid,this.stateTracker.getTestStage(),this.cfg.buildSessionId.value)];case 2:_a.sent();this.logger.info("Footprints packet submitted successfully. packet contains "+packet.methods.length+" methods, "+packet.branches.length+" branches in "+packet.executions.length+" executions");return[3,5];case 3:e_1=_a.sent();this.logger.error("Error while submitting footprints '"+e_1+"'");cockpit_notifier_1.CockpitNotifier.sendEvent(agent_events_conracts_1.AgentEventCode.FOOTPRINTS_LOSS);return[3,5];case 4:this.ongoingRequestsCounter--;return[7];case 5:return[3,7];case 6:this.logger.info("No hits collected nothing to submit");_a.label=7;case 7:return[2]}})})};FootprintsProcess.prototype.shouldSubmitFootprints=function(){if(!this.isRunning){this.logger.info("Agent is not running, not sending footprints");return false}if(this.cfg.sendFootprints.value===false){this.logger.info("Not sending footprints since agent is configured to not send.");return false}return true};FootprintsProcess.prototype.start=function(){if(this.isRunning)return;if(this.cfg.enabled.value==false)return;this.isRunning=true;this.sendToServerWatchdog.start();if(this.footprintsBuffer.hasHitsInBuffer()){this.ensureKeepaliveThreadRunning()}};FootprintsProcess.prototype.stop=function(callback){var _this=this;this.sendToServerWatchdog.stop();if(!this.shouldSubmitFootprints()){this.isRunning=false;return callback()}this.isRunning=false;this.flushCurrentFootprints(true);var packet=this.footprintsBuffer.createPacket();if(!packet){this.logger.info("No hits collected, nothing to submit");return callback()}this.logger.debug("Start submitting footprints, triggered by stop event.");this.backendProxy.submitFootprintsV6(packet,this.currentExecutionBsid,this.stateTracker.getTestStage(),this.cfg.buildSessionId.value).then(callback).catch(function(err){_this.logger.error(err);return callback()})};FootprintsProcess.prototype.handleTestIdChanged=function(newTestIdentifier,previousTestIdentifier){if(previousTestIdentifier==null){this.logger.info("Test identifier changed, previous identifier wasn't set, meaning that we didn't have active test. Skip enqueuing footprints process.")}else{if(!this.stateTracker.shouldCollectHits()){this.logger.info("Test identifier changed, couldn't find active execution for anonymous footprints. Skip enqueuing footprints process.");return}this.logger.debug("Test identifier changed, start enqueuing footprints process.");var prevTestIdentifierParts=state_tracker_1.StateTracker.splitTestIdToExecutionAndTestName(previousTestIdentifier);this.enqueueCurrentFootprints(this.stateTracker.currentExecution.executionId,prevTestIdentifierParts.testName,this.stateTracker.currentExecution.buildSessionId)}};FootprintsProcess.prototype.delegateEvents=function(){var _this=this;this.sendToServerWatchdog.on(FootprintsProcess.ALARM_FIRED,function(){_this.logger.debug("Start submitting footprints, triggered by send to server watchdog.");_this.submitQueuedFootprints()});this.keepaliveWatchdog.on(FootprintsProcess.ALARM_FIRED,function(){if(!_this.hasOngoingRequests()&&!_this.footprintsBuffer.hasHitsInBuffer()){_this.keepaliveWatchdog.stop()}});this.footprintsBuffer.on(footprints_buffer_1.FootprintsBuffer.BUFFER_FULL,function(){_this.submitQueuedFootprints()});this.stateTracker.on(state_tracker_1.StateTracker.EXECUTION_BSID_CHANGED,function(prevExecution,newBuildSession){_this.logger.warn("Execution points to different build session '"+newBuildSession+"'. Collecting and submitting previous footprints");_this.enqueueAndSubmit(prevExecution)});this.stateTracker.on(state_tracker_1.StateTracker.EXECUTION_ID_CHANGED,function(prevExecution,newExecutionId){_this.logger.warn("Execution id changed to'"+newExecutionId+"'. Collecting previous footprints");_this.enqueueCurrentFootprints(prevExecution.executionId,null,prevExecution.buildSessionId)});this.stateTracker.on(state_tracker_1.StateTracker.TEST_STAGE_CHANGED,function(prevExecution,newTestStage){_this.logger.warn("Execution points to different test stage '"+newTestStage+"'. Collecting and submitting previous footprints");_this.enqueueAndSubmit(prevExecution)})};FootprintsProcess.prototype.enqueueAndSubmit=function(executionData,isFinalFootprints){if(isFinalFootprints===void 0){isFinalFootprints=false}this.enqueueCurrentFootprints(executionData.executionId,null,executionData.buildSessionId,isFinalFootprints);this.submitQueuedFootprints()};FootprintsProcess.prototype.flushCurrentFootprints=function(isFinalFootprints){if(isFinalFootprints===void 0){isFinalFootprints=false}var currentTestIdentifier=this.stateTracker.getCurrentTestIdentifier();if(currentTestIdentifier){var testIdentifierParts=state_tracker_1.StateTracker.splitTestIdToExecutionAndTestName(currentTestIdentifier);this.logger.debug("Enqueue footprints interval - start enqueuing process. currentTestIdentifier: '%s'",currentTestIdentifier);this.enqueueCurrentFootprints(this.stateTracker.currentExecution.executionId,testIdentifierParts.testName,this.stateTracker.currentExecution.buildSessionId,isFinalFootprints)}else if(this.stateTracker.shouldCollectHits()){this.logger.debug("Enqueue footprints interval - start enqueuing process. anonymous footprints");this.enqueueCurrentFootprints(this.stateTracker.currentExecution.executionId,null,this.stateTracker.currentExecution.buildSessionId,isFinalFootprints)}else{this.logger.info("Enqueue footprints interval - no active execution. skip enqueuing process.");this.handleNoExecutionFound()}};FootprintsProcess.prototype.handleNoExecutionFound=function(){if(this.stateTracker.openExecutionFoundOnce){this.logger.debug("No active execution and not in initFootprints mode, updating coverage snapshot");this.hitsCollector.dropHits()}};FootprintsProcess.prototype.isInitFootprints=function(){return this.stateTracker.openExecutionFoundOnce&&!this.footprintsEnqueueOnce};FootprintsProcess.prototype.hasOngoingRequests=function(){return this.ongoingRequestsCounter>0};FootprintsProcess.ALARM_FIRED="alarm";return FootprintsProcess}();exports.FootprintsProcess=FootprintsProcess})},{"../agent-events/agent-events-conracts":289,"../agent-events/cockpit-notifier":294,"../footprints-process/collection-interval":323,"../state-tracker":331,"./footprints-buffer":317}],321:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.formatLocation=void 0;function formatLocation(position,logger){if(position.hasOwnProperty("line")&&position.hasOwnProperty("column")){return position.line+","+position.column}else if(position.hasOwnProperty("l")&&position.hasOwnProperty("c")){return position.l+","+position.c}logger.error("Position is not in a valid format got '"+tryStringifyPosition(position)+"', returning -1 for line and column");return"-1,-1"}exports.formatLocation=formatLocation;function tryStringifyPosition(position){try{return JSON.stringify(position)}catch(e){"failed to stringify position '"+e+"'"}}})},{}],322:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RelativePathResolver=void 0;var RelativePathResolver=function(){function RelativePathResolver(projectRoot){this.absoluteToRelativePath=new Map;this.projectRoot=projectRoot}RelativePathResolver.prototype.getRelativePath=function(absolutePath){if(!this.absoluteToRelativePath.get(absolutePath)){absolutePath=this.adjustPathSlashes(absolutePath);var relativePath=absolutePath.replace(this.resolveProjectRoot(),"");if(relativePath.indexOf("/")===0){relativePath=relativePath.substring(1)}this.absoluteToRelativePath.set(absolutePath,relativePath)}return this.absoluteToRelativePath.get(absolutePath)};RelativePathResolver.prototype.adjustPathSlashes=function(filePath){return(filePath||"").replace(/\\/g,"/")};RelativePathResolver.prototype.resolveProjectRoot=function(){return(this.projectRoot||process.cwd()).replace(/\\/g,"/")};return RelativePathResolver}();exports.RelativePathResolver=RelativePathResolver})}).call(this)}).call(this,require("_process"))},{_process:179}],323:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CollectionInterval=void 0;var system_date_1=require("../system-date");var CollectionInterval=function(){function CollectionInterval(intervalInMS){this.intervalInSeconds=this.toSeconds(intervalInMS);this.start=this.toSeconds(system_date_1.getSystemDateValueOf())}CollectionInterval.prototype.next=function(){if(this.end){this.start=this.end}this.end=this.toSeconds(system_date_1.getSystemDateValueOf());if(this.end-this.start>this.intervalInSeconds){this.start=this.end-this.intervalInSeconds}};CollectionInterval.prototype.toJson=function(){return{start:this.start,end:this.end}};CollectionInterval.prototype.toSeconds=function(time){return Math.floor(time/1e3)};return CollectionInterval}();exports.CollectionInterval=CollectionInterval})},{"../system-date":332}],324:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./contracts","./http-client","./sl-routes","../utils/validation-utils","./entities-mapper","../constants/constants","../constants/sl-env-vars","../utils/timer-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BackendProxy=void 0;var contracts_1=require("./contracts");var http_client_1=require("./http-client");var sl_routes_1=require("./sl-routes");var validation_utils_1=require("../utils/validation-utils");var entities_mapper_1=require("./entities-mapper");var constants_1=require("../constants/constants");var sl_env_vars_1=require("../constants/sl-env-vars");var timer_utils_1=require("../utils/timer-utils");var BackendProxy=function(){function BackendProxy(agentInstanceData,config,logger,httpClient){this.agentInstanceData=agentInstanceData;this.config=config;this.logger=logger;this.client=httpClient||new http_client_1.HttpClient(this.config,this.logger)}BackendProxy.prototype.getBuildSession=function(buildSessionId,callback){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(buildSessionId,constants_1.Constants.BUILD_SESSION_ID);var url=sl_routes_1.SLRoutes.buildSessionV2(buildSessionId);this.client.get(url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.createBuildSessionId=function(request,callback){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.buildSessionV2();this.client.post(request,url,function(err,body){_this.invokeCallback(callback,err,body,entities_mapper_1.EntitiesMapper.toCreateBuildSessionIdResponse)})};BackendProxy.prototype.createBuildSessionIdPromise=function(request){return __awaiter(this,void 0,void 0,function(){var url;var _this=this;return __generator(this,function(_a){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);url=constants_1.Constants.PULL_REQUEST_PARAMS in request?sl_routes_1.SLRoutes.prBuildSession():sl_routes_1.SLRoutes.buildSessionV2();return[2,new Promise(function(resolve,reject){_this.client.post(request,url,function(err,body){if(err){return reject(err)}return resolve(body)})})]})})};BackendProxy.prototype.getRecommendedVersion=function(request){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.recommendedAgentV2(request.componentName,request.customerId,request.appName,request.branchName,request.testStage);return new Promise(function(resolve,reject){_this.client.get(url,function(err,body){if(err){return reject(err)}else if(body&&body.agent&&body.agent){return resolve(body.agent)}else{return reject(new Error("Failed to get recommended version due to unexpected response from the server."))}})})};BackendProxy.prototype.submitBuildMapping=function(request){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.buildMappingV4();return this.submitPostRequestWithRetries(request,url)};BackendProxy.prototype.submitLogs=function(request,callback){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.logSubmissionV2();this.client.post(request,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.getRemoteConfig=function(request,callback){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.configV3(this.agentInstanceData,request.appName,request.branch,request.build,request.testStage,request.labId);this.client.get(url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.getRemoteConfigPromise=function(request){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);return new Promise(function(resolve,reject){var url=sl_routes_1.SLRoutes.configV3(_this.agentInstanceData,request.appName,request.branch,request.build,request.testStage,request.labId);_this.client.get(url,function(err,body){if(err){reject(err)}resolve(body)})})};BackendProxy.prototype.startExecution=function(request,callback){var _this=this;var url=sl_routes_1.SLRoutes.testExecution();this.client.post(request,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.startColoredExecution=function(request){var _this=this;return new Promise(function(resolve,reject){var url=sl_routes_1.SLRoutes.testExecution();_this.client.post(request,url,function(err){if(err){reject(err)}resolve()})})};BackendProxy.prototype.testExecutionV4=function(labId,async,executionId){var _this=this;if(async===void 0){async=true}return new Promise(function(resolve,reject){var url=sl_routes_1.SLRoutes.testExecutionV4(labId);_this.client.get(url,function(err,body){if(err){reject(err)}resolve(body)},false,async)})};BackendProxy.prototype.uploadReport=function(request,callback){var _this=this;var url=sl_routes_1.SLRoutes.externalData();this.client.postMultipart(request,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.externalReport=function(request,callback){var _this=this;var url=sl_routes_1.SLRoutes.externalReport();this.client.post(request,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.endExecution=function(request,callback){var _this=this;var url=sl_routes_1.SLRoutes.endExecution(request.customerId,request.appName,request.buildName,request.branchName,request.environment);var body=request.executionIds?{executionIds:request.executionIds}:null;this.client.delete(body,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.endExecutionPromise=function(request){var _this=this;var url=sl_routes_1.SLRoutes.endExecution(request.customerId,request.appName,request.buildName,request.branchName,request.environment);var body=request.executionIds?{executionIds:request.executionIds}:null;return new Promise(function(resolve,reject){_this.client.delete(body,url,function(err){err?reject(err):resolve()})})};BackendProxy.prototype.submitEvents=function(packetToSend,callback,async){if(async===void 0){async=true}var url=sl_routes_1.SLRoutes.eventsV2();this.client.post(packetToSend,url,callback)};BackendProxy.prototype.submitEventsPromise=function(packetToSend){var _this=this;return new Promise(function(resolve,reject){var url=sl_routes_1.SLRoutes.eventsV2();_this.client.post(packetToSend,url,function(err){if(err){reject(err)}resolve()})})};BackendProxy.prototype.submitBlobAsync=function(body,buildSessionId,blobId){var _this=this;var url=sl_routes_1.SLRoutes.blobs(buildSessionId,blobId);return new Promise(function(res,rej){_this.client.post(body,url,function(error){rej(error)},true,contracts_1.ContentType.OCTET_STREAM);res(null)})};BackendProxy.prototype.submitBlob=function(body,buildSessionId,blobId,callback){var url=sl_routes_1.SLRoutes.blobs(buildSessionId,blobId);this.client.post(body,url,callback,true,contracts_1.ContentType.OCTET_STREAM)};BackendProxy.prototype.getBlobsAsJson=function(buildSessionId){return __awaiter(this,void 0,void 0,function(){var slMapping,url,e_1;return __generator(this,function(_a){switch(_a.label){case 0:slMapping=[];_a.label=1;case 1:_a.trys.push([1,3,,4]);url=sl_routes_1.SLRoutes.blobsForBsidAsJson(buildSessionId);return[4,this.submitGetRequestWithRetries(url)];case 2:slMapping=_a.sent();return[3,4];case 3:e_1=_a.sent();this.logger.error(e_1);return[3,4];case 4:return[2,slMapping]}})})};BackendProxy.prototype.submitAgentEvent=function(body){var _this=this;var url=sl_routes_1.SLRoutes.agentEvents();return new Promise(function(resolve,reject){_this.client.post(body,url,function(error,response){if(error){return reject(error)}return resolve()})})};BackendProxy.prototype.getTestsRecommendation=function(buildSessionId,stage){var url=sl_routes_1.SLRoutes.testsRecommendations(buildSessionId,stage);return this.submitGetRequestWithRetries(url,null,null,[400,404],false)};BackendProxy.prototype.addOrUpdateIntegrationBuildComponents=function(buildSessionId,components,agentId){var url=sl_routes_1.SLRoutes.integrationBuildComponents(buildSessionId);return this.submitPutRequestWithRetries({components:components,agentId:agentId},url)};BackendProxy.prototype.deleteIntegrationBuildComponents=function(buildSessionId,components,agentId){var url=sl_routes_1.SLRoutes.integrationBuildComponents(buildSessionId);return this.submitDelRequestWithRetries({components:components,agentId:agentId},url)};BackendProxy.prototype.buildEnd=function(data){return this.submitPostRequestWithRetries(data,sl_routes_1.SLRoutes.buildEnd())};BackendProxy.prototype.submitFootprintsV6=function(footprintsPacket,executionBsid,testStage,buildSessionId){return __awaiter(this,void 0,void 0,function(){var url;return __generator(this,function(_a){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(footprintsPacket,constants_1.Constants.FOOTPRINTS_PACKET)
32
- ;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(executionBsid,constants_1.Constants.EXECUTION_BSID);validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(testStage,constants_1.Constants.TEST_STAGE);validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(buildSessionId,constants_1.Constants.BUILD_SESSION_ID);url=sl_routes_1.SLRoutes.footprintsV6(executionBsid,testStage,buildSessionId);return[2,this.submitPostRequestWithRetries(footprintsPacket,url,null,null,true,contracts_1.ContentType.OCTET_STREAM)]})})};BackendProxy.prototype.getBuildSessionData=function(buildSessionId){return __awaiter(this,void 0,void 0,function(){var _this=this;return __generator(this,function(_a){return[2,new Promise(function(resolve,reject){_this.getBuildSession(buildSessionId,function(err,response){err?reject(err):resolve(response)})})]})})};BackendProxy.prototype.getRecommendedAgent=function(configuration){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,{}]})})};BackendProxy.prototype.getBuildSessionDataFromLabId=function(labid){return __awaiter(this,void 0,void 0,function(){var url;return __generator(this,function(_a){url=sl_routes_1.SLRoutes.activeBuildSessionId(labid);return[2,this.submitGetRequestWithRetries(url)]})})};BackendProxy.prototype.invokeCallback=function(callback,err,body,map){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(callback,constants_1.Constants.CALLBACK);if(err!=null){return callback(err,body)}if(map==null){return callback(null,body)}var apiResponse=map(body);return callback(null,apiResponse)};BackendProxy.prototype.submitPostRequestWithRetries=function(body,url,retries,delayBetweenRetires,async,contentType){var _this=this;return this.makeRequestWithRetries(function(callback){_this.client.post(body,url,callback,async,contentType)},retries,delayBetweenRetires)};BackendProxy.prototype.submitPutRequestWithRetries=function(body,url,retries,delayBetweenRetires){var _this=this;return this.makeRequestWithRetries(function(callback){_this.client.put(body,url,callback)},retries,delayBetweenRetires)};BackendProxy.prototype.submitDelRequestWithRetries=function(body,url,retries,delayBetweenRetires){var _this=this;return this.makeRequestWithRetries(function(callback){_this.client.delete(body,url,callback)},retries,delayBetweenRetires)};BackendProxy.prototype.submitGetRequestWithRetries=function(url,retries,delayBetweenRetires,statusesForRetry,isNotFoundAcceptable){var _this=this;if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}return this.makeRequestWithRetries(function(callback){_this.client.get(url,callback,isNotFoundAcceptable)},retries,delayBetweenRetires,statusesForRetry)};BackendProxy.prototype.makeRequestWithRetries=function(doSingleRequest,retries,delayBetweenRetires,statusesForRetry){return __awaiter(this,void 0,void 0,function(){var retriesLeft,intervalBetweenRetries,lastError,bodyAndStatusCode,errAndStatusCode_1;return __generator(this,function(_a){switch(_a.label){case 0:retriesLeft=retries||sl_env_vars_1.SlEnvVars.getHttpMaxAttempts()||BackendProxy.DEFAULT_HTTP_MAX_ATTEMPTS;intervalBetweenRetries=delayBetweenRetires||sl_env_vars_1.SlEnvVars.getHttpAttemptInterval()||BackendProxy.DEFAULT_HTTP_ATTEMPT_INTERVAL;lastError=undefined;_a.label=1;case 1:_a.trys.push([1,3,,4]);retriesLeft--;return[4,new Promise(function(resolve,reject){doSingleRequest(function(err,body,statusCode){err?reject({err:err,statusCode:statusCode}):resolve({body:body,statusCode:statusCode})})})];case 2:bodyAndStatusCode=_a.sent();return[2,bodyAndStatusCode.body];case 3:errAndStatusCode_1=_a.sent();this.logger.info(errAndStatusCode_1);lastError=errAndStatusCode_1.err;if(!this.shouldRetryRequest(errAndStatusCode_1.statusCode,statusesForRetry)){return[3,7]}return[3,4];case 4:return[4,timer_utils_1.TimerUtils.sleep(intervalBetweenRetries)];case 5:_a.sent();_a.label=6;case 6:if(retriesLeft>0)return[3,1];_a.label=7;case 7:throw lastError}})})};BackendProxy.prototype.shouldRetryRequest=function(statusCode,statusesForRetry){if(statusesForRetry===void 0){statusesForRetry=[]}if(statusCode>=500||statusCode&&statusesForRetry.includes(statusCode))return true;return false};BackendProxy.DEFAULT_HTTP_MAX_ATTEMPTS=6;BackendProxy.DEFAULT_HTTP_ATTEMPT_INTERVAL=5*1e3;return BackendProxy}();exports.BackendProxy=BackendProxy})},{"../constants/constants":304,"../constants/sl-env-vars":305,"../utils/timer-utils":335,"../utils/validation-utils":336,"./contracts":325,"./entities-mapper":326,"./http-client":327,"./sl-routes":329}],325:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ContentType=exports.RecommendationSetStatus=exports.RecommendedTestReason=exports.UploadReportsBody=exports.EnvironmentData=exports.AgentData=exports.UploadReportRequest=exports.EndExecutionRequest=exports.StartExecutionRequest=exports.BaseRequest=exports.SubmitLogsRequest=exports.GetRemoteConfigRequest=exports.FileData=exports.DependencyData=exports.BuildMappingRequest=exports.VersionMetaQuery=exports.VersionMeta=exports.AgentInfo=exports.GetVersionResponse=exports.GetVersionRequest=exports.CreateBuildSessionIdResponse=exports.HttpClientConfigData=void 0;var system_date_1=require("../system-date");var HttpClientConfigData=function(){function HttpClientConfigData(){}return HttpClientConfigData}();exports.HttpClientConfigData=HttpClientConfigData;var CreateBuildSessionIdResponse=function(){function CreateBuildSessionIdResponse(){}return CreateBuildSessionIdResponse}();exports.CreateBuildSessionIdResponse=CreateBuildSessionIdResponse;var GetVersionRequest=function(){function GetVersionRequest(){}return GetVersionRequest}();exports.GetVersionRequest=GetVersionRequest;var GetVersionResponse=function(){function GetVersionResponse(){}return GetVersionResponse}();exports.GetVersionResponse=GetVersionResponse;var AgentInfo=function(){function AgentInfo(){}return AgentInfo}();exports.AgentInfo=AgentInfo;var VersionMeta=function(){function VersionMeta(){}return VersionMeta}();exports.VersionMeta=VersionMeta;var VersionMetaQuery=function(){function VersionMetaQuery(){}return VersionMetaQuery}();exports.VersionMetaQuery=VersionMetaQuery;var BuildMappingRequest=function(){function BuildMappingRequest(){}return BuildMappingRequest}();exports.BuildMappingRequest=BuildMappingRequest;var DependencyData=function(){function DependencyData(){}return DependencyData}();exports.DependencyData=DependencyData;var FileData=function(){function FileData(){}return FileData}();exports.FileData=FileData;var GetRemoteConfigRequest=function(){function GetRemoteConfigRequest(){}return GetRemoteConfigRequest}();exports.GetRemoteConfigRequest=GetRemoteConfigRequest;var SubmitLogsRequest=function(){function SubmitLogsRequest(){this.creationTime=system_date_1.getSystemDateValueOf()}return SubmitLogsRequest}();exports.SubmitLogsRequest=SubmitLogsRequest;var BaseRequest=function(){function BaseRequest(){}return BaseRequest}();exports.BaseRequest=BaseRequest;var StartExecutionRequest=function(_super){__extends(StartExecutionRequest,_super);function StartExecutionRequest(){return _super!==null&&_super.apply(this,arguments)||this}return StartExecutionRequest}(BaseRequest);exports.StartExecutionRequest=StartExecutionRequest;var EndExecutionRequest=function(_super){__extends(EndExecutionRequest,_super);function EndExecutionRequest(){return _super!==null&&_super.apply(this,arguments)||this}return EndExecutionRequest}(BaseRequest);exports.EndExecutionRequest=EndExecutionRequest;var UploadReportRequest=function(_super){__extends(UploadReportRequest,_super);function UploadReportRequest(){return _super!==null&&_super.apply(this,arguments)||this}return UploadReportRequest}(BaseRequest);exports.UploadReportRequest=UploadReportRequest;var AgentData=function(){function AgentData(){}return AgentData}();exports.AgentData=AgentData;var EnvironmentData=function(){function EnvironmentData(){}return EnvironmentData}();exports.EnvironmentData=EnvironmentData;var UploadReportsBody=function(){function UploadReportsBody(){}return UploadReportsBody}();exports.UploadReportsBody=UploadReportsBody;var RecommendedTestReason;(function(RecommendedTestReason){RecommendedTestReason["PINNED"]="pinned";RecommendedTestReason["IMPACTED"]="impacted";RecommendedTestReason["FAILED"]="failed"})(RecommendedTestReason=exports.RecommendedTestReason||(exports.RecommendedTestReason={}));var RecommendationSetStatus;(function(RecommendationSetStatus){RecommendationSetStatus["NOT_READY"]="notReady";RecommendationSetStatus["READY"]="ready";RecommendationSetStatus["NO_HISTORY"]="noHistory";RecommendationSetStatus["ERROR"]="error"})(RecommendationSetStatus=exports.RecommendationSetStatus||(exports.RecommendationSetStatus={}));var ContentType;(function(ContentType){ContentType["OCTET_STREAM"]="application/octet-stream";ContentType["JSON"]="application/json"})(ContentType=exports.ContentType||(exports.ContentType={}))})},{"../system-date":332}],326:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EntitiesMapper=void 0;var contracts_1=require("./contracts");var EntitiesMapper=function(){function EntitiesMapper(){}EntitiesMapper.toCreateBuildSessionIdResponse=function(body){if(body==null)return null;var response=new contracts_1.CreateBuildSessionIdResponse;response.buildSessionId=body;return response};return EntitiesMapper}();exports.EntitiesMapper=EntitiesMapper})},{"./contracts":325}],327:[function(require,module,exports){(function(process,Buffer){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./contracts","request","zlib","uuid/v1","../constants/sl-env-vars","./http-verb","../utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpClient=void 0;var contracts_1=require("./contracts");var request=require("request");var zlib=require("zlib");var uuid=require("uuid/v1");var sl_env_vars_1=require("../constants/sl-env-vars");var http_verb_1=require("./http-verb");var validation_utils_1=require("../utils/validation-utils");var HttpClient=function(){function HttpClient(cfg,logger){this.cfg=cfg;this.logger=logger;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(cfg,"cfg");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this.defaultTimeout=this.getDefaultTimeout()}HttpClient.prototype.get=function(urlPath,callback,isNotFoundAcceptable){if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}this.invokeHttpRequest(http_verb_1.HttpVerb.GET,urlPath,callback,null,null,null,isNotFoundAcceptable)};HttpClient.prototype.delete=function(body,urlPath,callback){this.invokeHttpRequest(http_verb_1.HttpVerb.DELETE,urlPath,callback,null,body)};HttpClient.prototype.put=function(requestData,urlPath,callback,async,contentType){return this.submitRequestWithBody(http_verb_1.HttpVerb.PUT,requestData,urlPath,callback,async,contentType)};HttpClient.prototype.post=function(requestData,urlPath,callback,async,contentType){return this.submitRequestWithBody(http_verb_1.HttpVerb.POST,requestData,urlPath,callback,async,contentType)};HttpClient.prototype.postMultipart=function(requestData,urlPath,callback){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(requestData,"requestData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(requestData.agentData,"requestData.agentData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(requestData.reportFile,"requestData.reportFile");var agentData=requestData.agentData;var reportFile=requestData.reportFile;try{var opts=this.createDefaultOptions(urlPath);var id=uuid();var onRequestCallback=this.createOnRequestCallback(http_verb_1.HttpVerb.POST,id,callback);this.logger.info("Sending "+http_verb_1.HttpVerb.POST+" request. Url: '"+opts.url+"', requestId: '"+id+"'");var req=request.post(opts,onRequestCallback);var form=req.form();form.append("file",JSON.stringify(agentData),{filename:"agentData",contentType:"multipart/form-data"});form.append("file",reportFile.buffer.toString(),{filename:"report",contentType:"multipart/form-data"})}catch(err){this.logger.error("Failed sending Http "+http_verb_1.HttpVerb.POST+" request to:'"+urlPath+"'. Error: '"+err+"'");return callback(err,null,null)}};HttpClient.prototype.submitRequestWithBody=function(verb,requestData,urlPath,callback,async,contentType){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(requestData,"requestData");var bufferToSend=Buffer.from(JSON.stringify(requestData));var shouldZip=this.cfg.compressRequests!=null?this.cfg.compressRequests:true;this.logger.debug("Sending buffer:"+bufferToSend.toString());if(shouldZip){zlib.gzip(bufferToSend,function(err,compressedBuf){if(err){_this.logger.warn("Failed while trying to compress the request data. Sending uncompressed data instead. Error: ",err);_this.invokeHttpRequest(verb,urlPath,callback,null,bufferToSend,contentType)}else{_this.invokeHttpRequest(verb,urlPath,callback,{"Content-Encoding":"gzip"},compressedBuf,contentType)}})}else{this.invokeHttpRequest(verb,urlPath,callback,null,bufferToSend,contentType)}};HttpClient.prototype.invokeHttpRequest=function(httpVerb,urlPath,callback,additionalHeaders,buffer,contentType,isNotFoundAcceptable){if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(httpVerb,"httpVerb");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(urlPath,"urlPath");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(callback,"callback");try{var opts=this.createDefaultOptions(urlPath,contentType);if(additionalHeaders){for(var header in additionalHeaders){opts.headers[header]=additionalHeaders[header]}}var id=uuid();var onRequestCallback=this.createOnRequestCallback(httpVerb,id,callback,isNotFoundAcceptable);this.logger.info("Sending "+httpVerb+" request. Url: '"+opts.url+"', requestId: '"+id+"'");if(httpVerb===http_verb_1.HttpVerb.GET){opts.json=true;request.get(opts,onRequestCallback)}else if(httpVerb===http_verb_1.HttpVerb.DELETE){if(buffer)opts.body=buffer;opts.json=true;request.delete(opts,onRequestCallback)}else if(httpVerb===http_verb_1.HttpVerb.POST){opts.body=buffer;request.post(opts,onRequestCallback)}else if(httpVerb===http_verb_1.HttpVerb.PUT){opts.body=buffer;request.put(opts,onRequestCallback)}else{new Error(httpVerb+" is not implemented yet.")}}catch(err){this.logger.error("Failed sending Http "+httpVerb+" request to:'"+urlPath+"'. Error: '"+err+"'");return callback(err,null,null)}};HttpClient.prototype.createOnRequestCallback=function(httpVerb,requestId,callback,isNotFoundAcceptable){var _this=this;if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}var handler=function(err,requestResponse,body){var txId=requestResponse&&requestResponse.headers&&requestResponse.headers["x-sl-txid"];if(err||requestResponse!=null&&(requestResponse.statusCode<200||requestResponse.statusCode>=400)){var statusCode=-1;if(requestResponse!=null){statusCode=requestResponse.statusCode;_this.logger.warn("Got "+statusCode+" in '"+httpVerb+"' request. Request id:'"+requestId+"', Transaction ID:'"+txId+"'.")}if(err){err=new Error("HttpClient failed. Error: "+err.message+", StatusCode: "+statusCode+", Stack: "+err.stack)}else if(statusCode===404&&isNotFoundAcceptable){err=null}else{var errorMessage="Server returned: "+statusCode+" status code in '"+httpVerb+"' request. Transaction ID:'"+txId+"'.";if(body)errorMessage+=Object.entries(JSON.parse(body)).map(function(_a){var key=_a[0],val=_a[1];return"\n\t"+key+": "+val}).join("");err=new Error(errorMessage)}return callback(err,body,statusCode)}_this.logger.debug("'"+httpVerb+"' request was completed successfully. Request id:'"+requestId+"'. statusCode: "+requestResponse.statusCode+" body: "+body+", Transaction ID: "+txId);if(body&&body.length>0&&typeof body=="string"){body=JSON.parse(body)}return callback(null,body,requestResponse.statusCode)};return handler};HttpClient.prototype.allowUntrustedCertificates=function(){process.env["NODE_TLS_REJECT_UNAUTHORIZED"]="0"};HttpClient.prototype.createDefaultOptions=function(urlPath,contentType){if(contentType===void 0){contentType=contracts_1.ContentType.JSON}var opts={url:this.cfg.server+urlPath,headers:{"Content-Type":contentType,Authorization:"Bearer "+this.cfg.token},timeout:this.defaultTimeout};opts["compressed"]=true;if(this.cfg.proxy!=null){opts.proxy=this.cfg.proxy;this.allowUntrustedCertificates()}return opts};HttpClient.prototype.getDefaultTimeout=function(){var timeout=sl_env_vars_1.SlEnvVars.getHttpTimeout();if(timeout==null){timeout=60*1e3*2}timeout=Number(timeout);this.logger.debug("Http timeout value is '"+timeout+"'.");return timeout};return HttpClient}();exports.HttpClient=HttpClient})}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{"../constants/sl-env-vars":305,"../utils/validation-utils":336,"./contracts":325,"./http-verb":328,_process:179,buffer:71,request:453,"uuid/v1":509,zlib:68}],328:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpVerb=void 0;var HttpVerb;(function(HttpVerb){HttpVerb["GET"]="GET";HttpVerb["POST"]="POST";HttpVerb["DELETE"]="DELETE";HttpVerb["PUT"]="PUT"})(HttpVerb=exports.HttpVerb||(exports.HttpVerb={}))})},{}],329:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../constants/constants","../utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SLRoutes=void 0;var constants_1=require("../constants/constants");var validation_utils_1=require("../utils/validation-utils");var SLRoutes=function(){function SLRoutes(){}SLRoutes.agentsV1=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV2=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V2)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV3=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV4=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V4)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV5=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V5)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV6=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V6)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.testExecution=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.toUri(SLRoutes.TEST_EXECUTION)};SLRoutes.testExecutionV4=function(labId,executionId){var url=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V4)+SLRoutes.toUri(SLRoutes.TEST_EXECUTION)+SLRoutes.toUri(labId);if(executionId){url+=SLRoutes.buildQueryParams({executionId:executionId})}return url};SLRoutes.endExecution=function(customerId,appName,buildName,branchName,environment){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(appName,"appName");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(customerId,"customerId");var result=SLRoutes.testExecution();var query={customerId:customerId,appName:appName,buildName:buildName,branchName:branchName,environment:environment};result+=SLRoutes.buildQueryParams(query);return result};SLRoutes.externalData=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.toUri(SLRoutes.EXTERNAL_DATA)};SLRoutes.externalReport=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.EXTERNAL_REPORT)};SLRoutes.configV3=function(agentInstanceData,appName,branchName,buildName,testStage,labId){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentInstanceData,"agentInstanceData");var result=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.CONFIG;var query={agentType:agentInstanceData.agentType,agentVersion:agentInstanceData.agentVersion,agentId:agentInstanceData.agentId};if(appName)query.appName=appName;if(branchName)query.branchName=branchName;if(buildName)query.buildName=buildName;if(testStage)query.testStage=testStage;if(labId)query.labId=labId;result+=SLRoutes.buildQueryParams(query);return result};SLRoutes.buildSessionV2=function(buildSessionId){var result=SLRoutes.agentsV2()+SLRoutes.toUri(SLRoutes.BUILD_SESSION_ID)+SLRoutes.toUri(buildSessionId);return result};SLRoutes.prBuildSession=function(){return SLRoutes.buildSessionV2()+SLRoutes.toUri(SLRoutes.PULL_REQUEST)};SLRoutes.logSubmissionV2=function(){var result=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V2)+SLRoutes.LOG_SUBMISSION;return result};SLRoutes.buildMappingV4=function(){var result=SLRoutes.agentsV4()+SLRoutes.toUri(SLRoutes.BUILD_MAPPING);return result};SLRoutes.footprintsV5=function(){var result=SLRoutes.agentsV5()+SLRoutes.toUri(SLRoutes.FOOTPRINTS);return result};SLRoutes.footprintsV6=function(executionBsid,testStage,buildSessionId){return SLRoutes.agentsV6()+SLRoutes.toUri(executionBsid)+SLRoutes.toUri(SLRoutes.FOOTPRINTS)+SLRoutes.toUri(testStage)+SLRoutes.toUri(buildSessionId)};SLRoutes.eventsV2=function(){return SLRoutes.agentsV2()+SLRoutes.toUri(SLRoutes.EVENTS)};SLRoutes.productionV1=function(buildSessionId){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(buildSessionId,"buildSessionId");var result=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.AGENTS)+SLRoutes.toUri(SLRoutes.PRODUCTION)+SLRoutes.toUri(SLRoutes.BSID)+SLRoutes.toUri(buildSessionId);return result};SLRoutes.recommendedAgentV2=function(component,customerId,appName,branchName,testStage){if(!component){throw new Error("'component' "+constants_1.Constants.Messages.CANNOT_BE_NULL_OR_UNDEFINED+".")}var result=SLRoutes.agentsV2()+SLRoutes.toUri(component)+SLRoutes.toUri(SLRoutes.RECOMMENDED_VERSION);var query={customerId:customerId,appName:appName,branch:branchName,envName:testStage};result+=SLRoutes.buildQueryParams(query);return result};SLRoutes.blobs=function(buildSessionId,blobId){return SLRoutes.agentsV1()+SLRoutes.toUri(SLRoutes.BLOBS)+SLRoutes.toUri(buildSessionId)+SLRoutes.toUri(blobId)};SLRoutes.blobsForBsidAsJson=function(buildSessionId){var url=SLRoutes.agentsV1()+SLRoutes.toUri(SLRoutes.BLOBS)+SLRoutes.toUri(buildSessionId);url=url.slice(0,-1);return url+SLRoutes.buildQueryParams({view:"concatJson"})};SLRoutes.agentEvents=function(){return SLRoutes.agentsV3()+SLRoutes.toUri(SLRoutes.AGENT_EVENTS)};SLRoutes.testsRecommendations=function(buildSessionId,stage){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V2)+SLRoutes.toUri(SLRoutes.TEST_EXCLUSIONS)+SLRoutes.toUri(buildSessionId)+SLRoutes.toUri(stage)};SLRoutes.integrationBuildComponents=function(buildSessionId){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.AGENTS+SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.INTEGRATION_BUILDS)+SLRoutes.toUri(buildSessionId)+SLRoutes.COMPONENTS};SLRoutes.buildEnd=function(){return SLRoutes.agentsV3()+SLRoutes.toUri(SLRoutes.BUILD_END)};SLRoutes.activeBuildSessionId=function(labid){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.LAB_IDS)+SLRoutes.toUri(labid)+SLRoutes.toUri(SLRoutes.BUILD_SESSIONS)+SLRoutes.toUri(SLRoutes.ACTIVE)};SLRoutes.toUri=function(uri){if(uri==null||uri.length==null||uri.length===0){return""}return encodeURIComponent(uri)+SLRoutes.SLASH};SLRoutes.buildQueryParams=function(paramsMap){if(!paramsMap){throw new Error("'paramsMap' cannot be null or undefined.")}var queryString="";for(var key in paramsMap){var value=paramsMap[key];queryString+=SLRoutes.addQueryStringValue(key,value)}queryString="?"+queryString;queryString=queryString.substring(0,queryString.length-1);return queryString};SLRoutes.addQueryStringValue=function(key,value){if(!key&&!value)return"";if(!value){value=""}var paramString="";paramString+=encodeURIComponent(key);paramString+="=";paramString+=encodeURIComponent(value);paramString+="&";return paramString};SLRoutes.SLASH="/";SLRoutes.V1="v1";SLRoutes.V2="v2";SLRoutes.V3="v3";SLRoutes.V4="v4";SLRoutes.V5="v5";SLRoutes.V6="v6";SLRoutes.AGENTS="agents";SLRoutes.EVENTS="events";SLRoutes.PRODUCTION="productiondata";SLRoutes.BSID="bsid";SLRoutes.BUILD_SESSION_ID="buildsession";SLRoutes.BUILD_MAPPING="buildmapping";SLRoutes.RECOMMENDED_VERSION="recommended";SLRoutes.CONFIG="config";SLRoutes.LOG_SUBMISSION="logsubmission";SLRoutes.FOOTPRINTS="footprints";SLRoutes.TEST_EXECUTION="testExecution";SLRoutes.EXTERNAL_DATA="externaldata";SLRoutes.EXTERNAL_REPORT="externalreport";SLRoutes.BLOBS="blobs";SLRoutes.AGENT_EVENTS="agent-events";SLRoutes.PULL_REQUEST="pull-request";SLRoutes.TEST_EXCLUSIONS="test-exclusions";SLRoutes.INTEGRATION_BUILDS="integration-builds";SLRoutes.COMPONENTS="components";SLRoutes.BUILD_END="buildend";SLRoutes.LAB_IDS="lab-ids";SLRoutes.BUILD_SESSIONS="build-sessions";SLRoutes.ACTIVE="active";return SLRoutes}();exports.SLRoutes=SLRoutes})},{"../constants/constants":304,"../utils/validation-utils":336}],330:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","fs","source-map"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SourceMapsUtils=void 0;var fs=require("fs");var sourceMap=require("source-map");var SourceMapsUtils=function(){function SourceMapsUtils(){}SourceMapsUtils.readSourceMaps=function(fullFilename){if(!fullFilename)return;var sourceMapsFilename=fullFilename+".map";var contents,rawSourceMapJsonData,consumer;try{contents=fs.readFileSync(sourceMapsFilename).toString()}catch(e){return null}try{rawSourceMapJsonData=JSON.parse(contents)}catch(e){console.error("[Sealights] Ignoring invalid source map: "+sourceMapsFilename);return null}try{consumer=new sourceMap.SourceMapConsumer(rawSourceMapJsonData);return consumer}catch(e){console.error("[Sealights] Error processing source maps for file: "+sourceMapsFilename);return null}};return SourceMapsUtils}();exports.SourceMapsUtils=SourceMapsUtils})},{fs:69,"source-map":228}],331:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","events","./constants/sl-env-vars","./utils/validation-utils","./agent-events/cockpit-notifier","./agent-events/agent-events-conracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StateTracker=void 0;var events=require("events");var sl_env_vars_1=require("./constants/sl-env-vars");var validation_utils_1=require("./utils/validation-utils");var cockpit_notifier_1=require("./agent-events/cockpit-notifier");var agent_events_conracts_1=require("./agent-events/agent-events-conracts");var INITIAL_COLOR="00000000-0000-0000-0000-000000000000/__init";var StateTracker=function(_super){__extends(StateTracker,_super);function StateTracker(cfg,configProcess,checkTestStatusWatchdog,backendProxy,logger){var _this=_super.call(this)||this;_this.currentTestIdentifier=null;_this.isRunning=false;_this._openExecutionFoundOnce=false;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(cfg,"agentConfig");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(configProcess,"configProcess");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(checkTestStatusWatchdog,"watchdog");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(backendProxy,"backendProxy");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");_this.cfg=cfg;_this.configProcess=configProcess;_this.checkTestStatusWatchdog=checkTestStatusWatchdog;_this.backendProxy=backendProxy;_this.logger=logger;if(_this.cfg.useInitialColor.value&&_this.currentTestIdentifier==null){_this.switchToAnonFootprints()}configProcess.on("configuration_changed",function(newCfg){
33
- if(newCfg.useInitialColor.value&&_this.currentTestIdentifier==null){_this.switchToAnonFootprints()}_this.cfg=newCfg;_this.checkTestStatusWatchdog.setInterval(newCfg.executionQueryIntervalSecs.value)});_this.startCheckingTestStatusAtServer();return _this}StateTracker.prototype.startCheckingTestStatusAtServer=function(){var _this=this;if(sl_env_vars_1.SlEnvVars.inProductionListenerMode()){this.logger.debug("In production listener, no need to check test status in server");return}this.checkTestStatusWatchdog.on("alarm",function(){_this.checkTestStatusAtServer()});if(this.cfg.shouldCheckForActiveExecutionOnStartUp.value){this.checkTestStatusAtServer(false)}};StateTracker.prototype.checkTestStatusAtServer=function(async){var _this=this;if(async===void 0){async=true}if(!this.currentTestIdentifier){this.logger.info("'currentTestIdentifier' is null. That means that footprints will not be sent.")}else{this.backendProxy.testExecutionV4(this.cfg.labId.value,async,this.getExecutionIdForQuery()).then(function(response){_this.fireExecutionEvents(response.execution);_this.notifyCockpit(response.execution);_this._currentExecution=response.execution}).catch(function(err){_this.logger.warn("Error while checking test execution status "+err)})}};StateTracker.prototype.getExecutionIdForQuery=function(){if(this.isAnonymousColor(this.currentTestIdentifier)||!this.currentExecution){return null}return this.currentExecution.executionId};StateTracker.prototype.hasMappingAtServer=function(){return this._currentExecution!=null};StateTracker.prototype.shouldCollectHits=function(){return this.hasMappingAtServer()};Object.defineProperty(StateTracker.prototype,"currentExecution",{get:function(){return this._currentExecution},set:function(value){this._currentExecution=value},enumerable:false,configurable:true});Object.defineProperty(StateTracker.prototype,"openExecutionFoundOnce",{get:function(){return this._openExecutionFoundOnce},enumerable:false,configurable:true});StateTracker.prototype.isAnonymousColor=function(testIdentifier){return INITIAL_COLOR==testIdentifier};StateTracker.prototype.switchToAnonFootprints=function(){this.logger.info("Switching to anonymous footprints.");this.setTestIdentifier(INITIAL_COLOR,false)};StateTracker.prototype.getCurrentTestIdentifier=function(){return this.currentTestIdentifier};StateTracker.prototype.setTestIdentifier=function(newTestIdentifier,silent){this.logger.info("setting test identifier: "+newTestIdentifier);if(this.currentTestIdentifier==null&&newTestIdentifier!=null||this.currentTestIdentifier!=null&&this.currentTestIdentifier!=newTestIdentifier&&newTestIdentifier!=INITIAL_COLOR){var previousTestIdentifier=this.currentTestIdentifier;this.currentTestIdentifier=newTestIdentifier;if(this.isRunning){if(!silent){this.emit("test_identifier_changed",this.currentTestIdentifier,previousTestIdentifier)}else{this.logger.info("Test identifier changed, running in silent mode not enqueuing footprints")}this.checkTestStatusWatchdog.reset()}}else{this.logger.info("Not setting the color. newTestIdentifier is '"+newTestIdentifier+"' "+"and currentTestIdentifier is '"+this.currentTestIdentifier+"'")}};StateTracker.prototype.setCurrentTestIdentifier=function(newTestIdentifier){this.setTestIdentifier(newTestIdentifier)};StateTracker.prototype.start=function(){if(!this.isRunning){this.checkTestStatusWatchdog.start();this.isRunning=true}};StateTracker.prototype.stop=function(callback){try{if(!this.isRunning){return callback()}this.checkTestStatusWatchdog.stop();this.isRunning=false;callback()}catch(err){this.logger.error("Error while stopping StateTracker. '"+err+"'");return callback()}};StateTracker.prototype.getTestStage=function(){return this.currentExecution&&this.currentExecution.testStage||this.cfg.testStage.value};StateTracker.splitTestIdToExecutionAndTestName=function(testId){testId=testId||"";var executionId=testId.split("/")[0];var testName=testId.indexOf("/")==-1?"":testId.substring(executionId.length+1);if(!executionId){testName=""}return{executionId:executionId,testName:testName}};StateTracker.combineExecutionIdAndTestName=function(executionId,testName){testName=testName||"";if(!executionId){return""}return executionId+"/"+testName};StateTracker.prototype.startColoredExecution=function(executionId){return __awaiter(this,void 0,void 0,function(){var request,e_1;return __generator(this,function(_a){switch(_a.label){case 0:_a.trys.push([0,2,,3]);request={appName:this.cfg.appName.value,branchName:this.cfg.branch.value,buildName:this.cfg.build.value,labId:this.cfg.labId.value,testStage:this.cfg.testStage.value,executionId:executionId};return[4,this.backendProxy.startColoredExecution(request)];case 1:_a.sent();this.currentExecution=__assign(__assign({},request),{buildSessionId:this.cfg.buildSessionId.value,status:StateTracker.EXECUTION_STATUS_CREATED});return[3,3];case 2:e_1=_a.sent();this.logger.error("Failed to create execution, error '"+e_1+"'. Footprints will not be sent");return[3,3];case 3:return[2]}})})};StateTracker.prototype.fireExecutionEvents=function(executionData){if(!executionData){return}if(!this.currentExecution){return}if(this.currentExecution.buildSessionId!=executionData.buildSessionId){this.emit(StateTracker.EXECUTION_BSID_CHANGED,this.currentExecution,executionData.buildSessionId);return}if(this.currentExecution.executionId!=executionData.executionId){this.emit(StateTracker.EXECUTION_ID_CHANGED,this.currentExecution,executionData.buildSessionId);return}if(this.currentExecution.testStage!=executionData.testStage){this.emit(StateTracker.TEST_STAGE_CHANGED,this.currentExecution,executionData.testStage);return}};StateTracker.prototype.notifyCockpit=function(execution){if(!execution){cockpit_notifier_1.CockpitNotifier.sendEventOnce(agent_events_conracts_1.AgentEventCode.FIRST_TIME_NO_EXECUTION)}else{cockpit_notifier_1.CockpitNotifier.sendEventOnce(agent_events_conracts_1.AgentEventCode.FIRST_TIME_HAS_EXECUTION);this._openExecutionFoundOnce=true}};StateTracker.EXECUTION_ENDS="executionEnds";StateTracker.EXECUTION_BSID_CHANGED="executionBsidChanged";StateTracker.EXECUTION_ID_CHANGED="executionIdChanged";StateTracker.TEST_STAGE_CHANGED="testStageChanged";StateTracker.EXECUTION_STATUS_CREATED="created";StateTracker.EXECUTION_STATUS_PENDING_DELETE="pendingDelete";return StateTracker}(events.EventEmitter);exports.StateTracker=StateTracker})},{"./agent-events/agent-events-conracts":289,"./agent-events/cockpit-notifier":294,"./constants/sl-env-vars":305,"./utils/validation-utils":336,events:110}],332:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getSystemDateValueOf=exports.getSystemDate=void 0;var SystemDate=Date;var SystemDateValueOf=Date.prototype.valueOf;function getSystemDate(){return new SystemDate}exports.getSystemDate=getSystemDate;function getSystemDateValueOf(){var date=getSystemDate();return SystemDateValueOf.call(date)}exports.getSystemDateValueOf=getSystemDateValueOf})},{}],333:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","path","fs"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FilesUtils=void 0;var path=require("path");var fs=require("fs");var FilesUtils=function(){function FilesUtils(){}FilesUtils.resolveOriginalFullFileName=function(fullPath,originalFilename){if(path.isAbsolute(originalFilename)){return originalFilename}var generatedDir=path.dirname(fullPath);originalFilename=path.resolve(generatedDir,originalFilename);return originalFilename};FilesUtils.prototype.fixPathAndSpecialChar=function(path){if(path){if(path[0]==="/"||path[0]==="\\"){return path.substr(1).split("\\").join("/")}return path.split("\\").join("/")}return path};FilesUtils.adjustPathSlashes=function(filePath){filePath=(filePath||"").replace(/\\/g,"/");return filePath};FilesUtils.findFileUp=function(file,folder){var parsed=path.parse(folder);var filePath=path.join(folder,file);if(fs.existsSync(filePath)){return filePath}if(path.resolve(folder)===parsed.root||folder==="."){return null}var parentFolder=path.join(folder,"..");parentFolder=path.normalize(parentFolder);return FilesUtils.findFileUp(file,parentFolder)};return FilesUtils}();exports.FilesUtils=FilesUtils})},{fs:69,path:171}],334:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ParsingUtils=void 0;var ParsingUtils=function(){function ParsingUtils(){}ParsingUtils.parseNumber=function(key){var valueFromEnv=process.env[key];if(valueFromEnv!=null){var valueAsNumber=Number.parseFloat(valueFromEnv);if(!isNaN(valueAsNumber)){valueFromEnv=valueAsNumber}else{valueFromEnv=null}}return valueFromEnv};ParsingUtils.parseBoolean=function(key){var valueFromEnv=process.env[key];if(valueFromEnv!=null&&typeof valueFromEnv=="string"){valueFromEnv=valueFromEnv.toLowerCase()}return valueFromEnv=="true"};return ParsingUtils}();exports.ParsingUtils=ParsingUtils})}).call(this)}).call(this,require("_process"))},{_process:179}],335:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TimerUtils=void 0;var TimerUtils=function(){function TimerUtils(){}TimerUtils.sleep=function(timeout){return new Promise(function(resolve){setTimeout(resolve,timeout)})};return TimerUtils}();exports.TimerUtils=TimerUtils})},{}],336:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../constants/constants"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ValidationUtils=void 0;var constants_1=require("../constants/constants");var ValidationUtils=function(){function ValidationUtils(){}ValidationUtils.verifyNotNullOrEmpty=function(value,paramName){if(value===undefined||value===null){throw new Error(paramName+" "+constants_1.Constants.Messages.CANNOT_BE_NULL_OR_UNDEFINED+".")}if(typeof value==="string"&&value.length===0){throw new Error(paramName+" "+constants_1.Constants.Messages.CANNOT_BE_EMPTY_STRING+".")}};return ValidationUtils}();exports.ValidationUtils=ValidationUtils})},{"../constants/constants":304}],337:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","events"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Watchdog=exports.WatchdogOptions=void 0;var events=require("events");var WatchdogOptions=function(){function WatchdogOptions(){}return WatchdogOptions}();exports.WatchdogOptions=WatchdogOptions;var Watchdog=function(_super){__extends(Watchdog,_super);function Watchdog(options,timers){var _this=_super.call(this)||this;_this.options=options;_this.timers=timers;_this.handle=null;_this.pendingAlarmDuringSuspended=false;_this.suspended=false;_this.stopped=true;if(!options){throw new Error("options is required")}if(!timers){throw new Error("timers is required")}return _this}Watchdog.prototype.abort=function(){if(this.handle){this.timers.clearTimeout(this.handle);this.handle=null;this.pendingAlarmDuringSuspended=false}};Watchdog.prototype.reset=function(){this.abort();if(!this.stopped){this.handle=this.timers.setTimeout(this.fireAlarm.bind(this),this.options.interval);if(this.options.unref&&this.handle.unref){this.handle.unref()}}};Watchdog.prototype.stop=function(){this.stopped=true;this.abort()};Watchdog.prototype.start=function(){this.stopped=false;this.reset()};Watchdog.prototype.getStatus=function(){return{pendingAlarmDuringSuspended:this.pendingAlarmDuringSuspended,running:!this.stopped,suspended:this.suspended}};Watchdog.prototype.suspend=function(){this.suspended=true};Watchdog.prototype.resume=function(){this.suspended=false;if(this.pendingAlarmDuringSuspended){this.pendingAlarmDuringSuspended=false;this.fireAlarm()}};Watchdog.prototype.fireAlarm=function(){this.handle=null;if(this.suspended){this.pendingAlarmDuringSuspended=true}else{try{this.emit("alarm",this)}catch(err){}}if(this.options.autoReset){this.reset()}};Watchdog.prototype.setInterval=function(newInterval){if(newInterval<=0)throw new Error("Invalid value for interval: "+newInterval);this.options.interval=newInterval};Watchdog.prototype.getInterval=function(){return this.options.interval};return Watchdog}(events.EventEmitter);exports.Watchdog=Watchdog})},{events:110}],338:[function(require,module,exports){"use strict";var compileSchema=require("./compile"),resolve=require("./compile/resolve"),Cache=require("./cache"),SchemaObject=require("./compile/schema_obj"),stableStringify=require("fast-json-stable-stringify"),formats=require("./compile/formats"),rules=require("./compile/rules"),$dataMetaSchema=require("./data"),util=require("./compile/util");module.exports=Ajv;Ajv.prototype.validate=validate;Ajv.prototype.compile=compile;Ajv.prototype.addSchema=addSchema;Ajv.prototype.addMetaSchema=addMetaSchema;Ajv.prototype.validateSchema=validateSchema;Ajv.prototype.getSchema=getSchema;Ajv.prototype.removeSchema=removeSchema;Ajv.prototype.addFormat=addFormat;Ajv.prototype.errorsText=errorsText;Ajv.prototype._addSchema=_addSchema;Ajv.prototype._compile=_compile;Ajv.prototype.compileAsync=require("./compile/async");var customKeyword=require("./keyword");Ajv.prototype.addKeyword=customKeyword.add;Ajv.prototype.getKeyword=customKeyword.get;Ajv.prototype.removeKeyword=customKeyword.remove;Ajv.prototype.validateKeyword=customKeyword.validate;var errorClasses=require("./compile/error_classes");Ajv.ValidationError=errorClasses.Validation;Ajv.MissingRefError=errorClasses.MissingRef;Ajv.$dataMetaSchema=$dataMetaSchema;var META_SCHEMA_ID="http://json-schema.org/draft-07/schema";var META_IGNORE_OPTIONS=["removeAdditional","useDefaults","coerceTypes","strictDefaults"];var META_SUPPORT_DATA=["/properties"];function Ajv(opts){if(!(this instanceof Ajv))return new Ajv(opts);opts=this._opts=util.copy(opts)||{};setLogger(this);this._schemas={};this._refs={};this._fragments={};this._formats=formats(opts.format);this._cache=opts.cache||new Cache;this._loadingSchemas={};this._compilations=[];this.RULES=rules();this._getId=chooseGetId(opts);opts.loopRequired=opts.loopRequired||Infinity;if(opts.errorDataPath=="property")opts._errorDataPathProperty=true;if(opts.serialize===undefined)opts.serialize=stableStringify;this._metaOpts=getMetaSchemaOptions(this);if(opts.formats)addInitialFormats(this);if(opts.keywords)addInitialKeywords(this);addDefaultMetaSchema(this);if(typeof opts.meta=="object")this.addMetaSchema(opts.meta);if(opts.nullable)this.addKeyword("nullable",{metaSchema:{type:"boolean"}});addInitialSchemas(this)}function validate(schemaKeyRef,data){var v;if(typeof schemaKeyRef=="string"){v=this.getSchema(schemaKeyRef);if(!v)throw new Error('no schema with key or ref "'+schemaKeyRef+'"')}else{var schemaObj=this._addSchema(schemaKeyRef);v=schemaObj.validate||this._compile(schemaObj)}var valid=v(data);if(v.$async!==true)this.errors=v.errors;return valid}function compile(schema,_meta){var schemaObj=this._addSchema(schema,undefined,_meta);return schemaObj.validate||this._compile(schemaObj)}function addSchema(schema,key,_skipValidation,_meta){if(Array.isArray(schema)){for(var i=0;i<schema.length;i++)this.addSchema(schema[i],undefined,_skipValidation,_meta);return this}var id=this._getId(schema);if(id!==undefined&&typeof id!="string")throw new Error("schema id must be string");key=resolve.normalizeId(key||id);checkUnique(this,key);this._schemas[key]=this._addSchema(schema,_skipValidation,_meta,true);return this}function addMetaSchema(schema,key,skipValidation){this.addSchema(schema,key,skipValidation,true);return this}function validateSchema(schema,throwOrLogError){var $schema=schema.$schema;if($schema!==undefined&&typeof $schema!="string")throw new Error("$schema must be a string");$schema=$schema||this._opts.defaultMeta||defaultMeta(this);if(!$schema){this.logger.warn("meta-schema not available");this.errors=null;return true}var valid=this.validate($schema,schema);if(!valid&&throwOrLogError){var message="schema is invalid: "+this.errorsText();if(this._opts.validateSchema=="log")this.logger.error(message);else throw new Error(message)}return valid}function defaultMeta(self){var meta=self._opts.meta;self._opts.defaultMeta=typeof meta=="object"?self._getId(meta)||meta:self.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:undefined;return self._opts.defaultMeta}function getSchema(keyRef){var schemaObj=_getSchemaObj(this,keyRef);switch(typeof schemaObj){case"object":return schemaObj.validate||this._compile(schemaObj);case"string":return this.getSchema(schemaObj);case"undefined":return _getSchemaFragment(this,keyRef)}}function _getSchemaFragment(self,ref){var res=resolve.schema.call(self,{schema:{}},ref);if(res){var schema=res.schema,root=res.root,baseId=res.baseId;var v=compileSchema.call(self,schema,root,undefined,baseId);self._fragments[ref]=new SchemaObject({ref:ref,fragment:true,schema:schema,root:root,baseId:baseId,validate:v});return v}}function _getSchemaObj(self,keyRef){keyRef=resolve.normalizeId(keyRef);return self._schemas[keyRef]||self._refs[keyRef]||self._fragments[keyRef]}function removeSchema(schemaKeyRef){if(schemaKeyRef instanceof RegExp){_removeAllSchemas(this,this._schemas,schemaKeyRef);_removeAllSchemas(this,this._refs,schemaKeyRef);return this}switch(typeof schemaKeyRef){case"undefined":_removeAllSchemas(this,this._schemas);_removeAllSchemas(this,this._refs);this._cache.clear();return this;case"string":var schemaObj=_getSchemaObj(this,schemaKeyRef);if(schemaObj)this._cache.del(schemaObj.cacheKey);delete this._schemas[schemaKeyRef];delete this._refs[schemaKeyRef];return this;case"object":var serialize=this._opts.serialize;var cacheKey=serialize?serialize(schemaKeyRef):schemaKeyRef;this._cache.del(cacheKey);var id=this._getId(schemaKeyRef);if(id){id=resolve.normalizeId(id);delete this._schemas[id];delete this._refs[id]}}return this}function _removeAllSchemas(self,schemas,regex){for(var keyRef in schemas){var schemaObj=schemas[keyRef];if(!schemaObj.meta&&(!regex||regex.test(keyRef))){self._cache.del(schemaObj.cacheKey);delete schemas[keyRef]}}}function _addSchema(schema,skipValidation,meta,shouldAddSchema){if(typeof schema!="object"&&typeof schema!="boolean")throw new Error("schema should be object or boolean");var serialize=this._opts.serialize;var cacheKey=serialize?serialize(schema):schema;var cached=this._cache.get(cacheKey);if(cached)return cached;shouldAddSchema=shouldAddSchema||this._opts.addUsedSchema!==false;var id=resolve.normalizeId(this._getId(schema));if(id&&shouldAddSchema)checkUnique(this,id);var willValidate=this._opts.validateSchema!==false&&!skipValidation;var recursiveMeta;if(willValidate&&!(recursiveMeta=id&&id==resolve.normalizeId(schema.$schema)))this.validateSchema(schema,true);var localRefs=resolve.ids.call(this,schema);var schemaObj=new SchemaObject({id:id,schema:schema,localRefs:localRefs,cacheKey:cacheKey,meta:meta});if(id[0]!="#"&&shouldAddSchema)this._refs[id]=schemaObj;this._cache.put(cacheKey,schemaObj);if(willValidate&&recursiveMeta)this.validateSchema(schema,true);return schemaObj}function _compile(schemaObj,root){if(schemaObj.compiling){schemaObj.validate=callValidate;callValidate.schema=schemaObj.schema;callValidate.errors=null;callValidate.root=root?root:callValidate;if(schemaObj.schema.$async===true)callValidate.$async=true;return callValidate}schemaObj.compiling=true;var currentOpts;if(schemaObj.meta){currentOpts=this._opts;this._opts=this._metaOpts}var v;try{v=compileSchema.call(this,schemaObj.schema,root,schemaObj.localRefs)}catch(e){delete schemaObj.validate;throw e}finally{schemaObj.compiling=false;if(schemaObj.meta)this._opts=currentOpts}schemaObj.validate=v;schemaObj.refs=v.refs;schemaObj.refVal=v.refVal;schemaObj.root=v.root;return v;function callValidate(){var _validate=schemaObj.validate;var result=_validate.apply(this,arguments);callValidate.errors=_validate.errors;return result}}function chooseGetId(opts){switch(opts.schemaId){case"auto":return _get$IdOrId;case"id":return _getId;default:return _get$Id}}function _getId(schema){if(schema.$id)this.logger.warn("schema $id ignored",schema.$id);return schema.id}function _get$Id(schema){if(schema.id)this.logger.warn("schema id ignored",schema.id);return schema.$id}function _get$IdOrId(schema){if(schema.$id&&schema.id&&schema.$id!=schema.id)throw new Error("schema $id is different from id");return schema.$id||schema.id}function errorsText(errors,options){errors=errors||this.errors;if(!errors)return"No errors";options=options||{};var separator=options.separator===undefined?", ":options.separator;var dataVar=options.dataVar===undefined?"data":options.dataVar;var text="";for(var i=0;i<errors.length;i++){var e=errors[i];if(e)text+=dataVar+e.dataPath+" "+e.message+separator}return text.slice(0,-separator.length)}function addFormat(name,format){if(typeof format=="string")format=new RegExp(format);this._formats[name]=format;return this}function addDefaultMetaSchema(self){var $dataSchema;if(self._opts.$data){$dataSchema=require("./refs/data.json");self.addMetaSchema($dataSchema,$dataSchema.$id,true)}if(self._opts.meta===false)return;var metaSchema=require("./refs/json-schema-draft-07.json");if(self._opts.$data)metaSchema=$dataMetaSchema(metaSchema,META_SUPPORT_DATA);self.addMetaSchema(metaSchema,META_SCHEMA_ID,true);self._refs["http://json-schema.org/schema"]=META_SCHEMA_ID}function addInitialSchemas(self){var optsSchemas=self._opts.schemas;if(!optsSchemas)return;if(Array.isArray(optsSchemas))self.addSchema(optsSchemas);else for(var key in optsSchemas)self.addSchema(optsSchemas[key],key)}function addInitialFormats(self){for(var name in self._opts.formats){var format=self._opts.formats[name];self.addFormat(name,format)}}function addInitialKeywords(self){for(var name in self._opts.keywords){var keyword=self._opts.keywords[name];self.addKeyword(name,keyword)}}function checkUnique(self,id){if(self._schemas[id]||self._refs[id])throw new Error('schema with key or id "'+id+'" already exists')}function getMetaSchemaOptions(self){var metaOpts=util.copy(self._opts);for(var i=0;i<META_IGNORE_OPTIONS.length;i++)delete metaOpts[META_IGNORE_OPTIONS[i]];return metaOpts}function setLogger(self){var logger=self._opts.logger;if(logger===false){self.logger={log:noop,warn:noop,error:noop}}else{if(logger===undefined)logger=console;if(!(typeof logger=="object"&&logger.log&&logger.warn&&logger.error))throw new Error("logger must implement log, warn and error methods");self.logger=logger}}function noop(){}},{"./cache":339,"./compile":343,"./compile/async":340,"./compile/error_classes":341,"./compile/formats":342,"./compile/resolve":344,"./compile/rules":345,"./compile/schema_obj":346,"./compile/util":348,"./data":349,"./keyword":377,"./refs/data.json":378,"./refs/json-schema-draft-07.json":380,"fast-json-stable-stringify":402}],339:[function(require,module,exports){"use strict";var Cache=module.exports=function Cache(){this._cache={}};Cache.prototype.put=function Cache_put(key,value){this._cache[key]=value};Cache.prototype.get=function Cache_get(key){return this._cache[key]};Cache.prototype.del=function Cache_del(key){delete this._cache[key]};Cache.prototype.clear=function Cache_clear(){this._cache={}}},{}],340:[function(require,module,exports){"use strict";var MissingRefError=require("./error_classes").MissingRef;module.exports=compileAsync;function compileAsync(schema,meta,callback){var self=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");if(typeof meta=="function"){callback=meta;meta=undefined}var p=loadMetaSchemaOf(schema).then(function(){var schemaObj=self._addSchema(schema,undefined,meta);return schemaObj.validate||_compileAsync(schemaObj)});if(callback){p.then(function(v){callback(null,v)},callback)}return p;function loadMetaSchemaOf(sch){var $schema=sch.$schema;return $schema&&!self.getSchema($schema)?compileAsync.call(self,{$ref:$schema},true):Promise.resolve()}function _compileAsync(schemaObj){try{return self._compile(schemaObj)}catch(e){if(e instanceof MissingRefError)return loadMissingSchema(e);throw e}function loadMissingSchema(e){var ref=e.missingSchema;if(added(ref))throw new Error("Schema "+ref+" is loaded but "+e.missingRef+" cannot be resolved");var schemaPromise=self._loadingSchemas[ref];if(!schemaPromise){schemaPromise=self._loadingSchemas[ref]=self._opts.loadSchema(ref);schemaPromise.then(removePromise,removePromise)}return schemaPromise.then(function(sch){if(!added(ref)){return loadMetaSchemaOf(sch).then(function(){if(!added(ref))self.addSchema(sch,ref,undefined,meta)})}}).then(function(){return _compileAsync(schemaObj)});function removePromise(){delete self._loadingSchemas[ref]}function added(ref){return self._refs[ref]||self._schemas[ref]}}}}},{"./error_classes":341}],341:[function(require,module,exports){"use strict";var resolve=require("./resolve");module.exports={Validation:errorSubclass(ValidationError),MissingRef:errorSubclass(MissingRefError)};function ValidationError(errors){this.message="validation failed";this.errors=errors;this.ajv=this.validation=true}MissingRefError.message=function(baseId,ref){return"can't resolve reference "+ref+" from id "+baseId};function MissingRefError(baseId,ref,message){this.message=message||MissingRefError.message(baseId,ref);this.missingRef=resolve.url(baseId,ref);this.missingSchema=resolve.normalizeId(resolve.fullPath(this.missingRef))}function errorSubclass(Subclass){Subclass.prototype=Object.create(Error.prototype);Subclass.prototype.constructor=Subclass;return Subclass}},{"./resolve":344}],342:[function(require,module,exports){"use strict";var util=require("./util");var DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;var DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31];var TIME=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;var HOSTNAME=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i;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;var URIREF=/^(?:[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;var URITEMPLATE=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#.\/;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;var URL=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i
34
- ;var UUID=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;var JSON_POINTER=/^(?:\/(?:[^~\/]|~0|~1)*)*$/;var JSON_POINTER_URI_FRAGMENT=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;var RELATIVE_JSON_POINTER=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~\/]|~0|~1)*)*)$/;module.exports=formats;function formats(mode){mode=mode=="full"?"full":"fast";return util.copy(formats[mode])}formats.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":URITEMPLATE,url:URL,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,hostname:HOSTNAME,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,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,regex:regex,uuid:UUID,"json-pointer":JSON_POINTER,"json-pointer-uri-fragment":JSON_POINTER_URI_FRAGMENT,"relative-json-pointer":RELATIVE_JSON_POINTER};formats.full={date:date,time:time,"date-time":date_time,uri:uri,"uri-reference":URIREF,"uri-template":URITEMPLATE,url:URL,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,hostname:HOSTNAME,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,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,regex:regex,uuid:UUID,"json-pointer":JSON_POINTER,"json-pointer-uri-fragment":JSON_POINTER_URI_FRAGMENT,"relative-json-pointer":RELATIVE_JSON_POINTER};function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}function date(str){var matches=str.match(DATE);if(!matches)return false;var year=+matches[1];var month=+matches[2];var day=+matches[3];return month>=1&&month<=12&&day>=1&&day<=(month==2&&isLeapYear(year)?29:DAYS[month])}function time(str,full){var matches=str.match(TIME);if(!matches)return false;var hour=matches[1];var minute=matches[2];var second=matches[3];var timeZone=matches[5];return(hour<=23&&minute<=59&&second<=59||hour==23&&minute==59&&second==60)&&(!full||timeZone)}var DATE_TIME_SEPARATOR=/t|\s/i;function date_time(str){var dateTime=str.split(DATE_TIME_SEPARATOR);return dateTime.length==2&&date(dateTime[0])&&time(dateTime[1],true)}var NOT_URI_FRAGMENT=/\/|:/;function uri(str){return NOT_URI_FRAGMENT.test(str)&&URI.test(str)}var Z_ANCHOR=/[^\\]\\Z/;function regex(str){if(Z_ANCHOR.test(str))return false;try{new RegExp(str);return true}catch(e){return false}}},{"./util":348}],343:[function(require,module,exports){"use strict";var resolve=require("./resolve"),util=require("./util"),errorClasses=require("./error_classes"),stableStringify=require("fast-json-stable-stringify");var validateGenerator=require("../dotjs/validate");var ucs2length=util.ucs2length;var equal=require("fast-deep-equal");var ValidationError=errorClasses.Validation;module.exports=compile;function compile(schema,root,localRefs,baseId){var self=this,opts=this._opts,refVal=[undefined],refs={},patterns=[],patternsHash={},defaults=[],defaultsHash={},customRules=[];root=root||{schema:schema,refVal:refVal,refs:refs};var c=checkCompiling.call(this,schema,root,baseId);var compilation=this._compilations[c.index];if(c.compiling)return compilation.callValidate=callValidate;var formats=this._formats;var RULES=this.RULES;try{var v=localCompile(schema,root,localRefs,baseId);compilation.validate=v;var cv=compilation.callValidate;if(cv){cv.schema=v.schema;cv.errors=null;cv.refs=v.refs;cv.refVal=v.refVal;cv.root=v.root;cv.$async=v.$async;if(opts.sourceCode)cv.source=v.source}return v}finally{endCompiling.call(this,schema,root,baseId)}function callValidate(){var validate=compilation.validate;var result=validate.apply(this,arguments);callValidate.errors=validate.errors;return result}function localCompile(_schema,_root,localRefs,baseId){var isRoot=!_root||_root&&_root.schema==_schema;if(_root.schema!=root.schema)return compile.call(self,_schema,_root,localRefs,baseId);var $async=_schema.$async===true;var sourceCode=validateGenerator({isTop:true,schema:_schema,isRoot:isRoot,baseId:baseId,root:_root,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:errorClasses.MissingRef,RULES:RULES,validate:validateGenerator,util:util,resolve:resolve,resolveRef:resolveRef,usePattern:usePattern,useDefault:useDefault,useCustomRule:useCustomRule,opts:opts,formats:formats,logger:self.logger,self:self});sourceCode=vars(refVal,refValCode)+vars(patterns,patternCode)+vars(defaults,defaultCode)+vars(customRules,customRuleCode)+sourceCode;if(opts.processCode)sourceCode=opts.processCode(sourceCode,_schema);var validate;try{var makeValidate=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",sourceCode);validate=makeValidate(self,RULES,formats,root,refVal,defaults,customRules,equal,ucs2length,ValidationError);refVal[0]=validate}catch(e){self.logger.error("Error compiling schema, function code:",sourceCode);throw e}validate.schema=_schema;validate.errors=null;validate.refs=refs;validate.refVal=refVal;validate.root=isRoot?validate:_root;if($async)validate.$async=true;if(opts.sourceCode===true){validate.source={code:sourceCode,patterns:patterns,defaults:defaults}}return validate}function resolveRef(baseId,ref,isRoot){ref=resolve.url(baseId,ref);var refIndex=refs[ref];var _refVal,refCode;if(refIndex!==undefined){_refVal=refVal[refIndex];refCode="refVal["+refIndex+"]";return resolvedRef(_refVal,refCode)}if(!isRoot&&root.refs){var rootRefId=root.refs[ref];if(rootRefId!==undefined){_refVal=root.refVal[rootRefId];refCode=addLocalRef(ref,_refVal);return resolvedRef(_refVal,refCode)}}refCode=addLocalRef(ref);var v=resolve.call(self,localCompile,root,ref);if(v===undefined){var localSchema=localRefs&&localRefs[ref];if(localSchema){v=resolve.inlineRef(localSchema,opts.inlineRefs)?localSchema:compile.call(self,localSchema,root,localRefs,baseId)}}if(v===undefined){removeLocalRef(ref)}else{replaceLocalRef(ref,v);return resolvedRef(v,refCode)}}function addLocalRef(ref,v){var refId=refVal.length;refVal[refId]=v;refs[ref]=refId;return"refVal"+refId}function removeLocalRef(ref){delete refs[ref]}function replaceLocalRef(ref,v){var refId=refs[ref];refVal[refId]=v}function resolvedRef(refVal,code){return typeof refVal=="object"||typeof refVal=="boolean"?{code:code,schema:refVal,inline:true}:{code:code,$async:refVal&&!!refVal.$async}}function usePattern(regexStr){var index=patternsHash[regexStr];if(index===undefined){index=patternsHash[regexStr]=patterns.length;patterns[index]=regexStr}return"pattern"+index}function useDefault(value){switch(typeof value){case"boolean":case"number":return""+value;case"string":return util.toQuotedString(value);case"object":if(value===null)return"null";var valueStr=stableStringify(value);var index=defaultsHash[valueStr];if(index===undefined){index=defaultsHash[valueStr]=defaults.length;defaults[index]=value}return"default"+index}}function useCustomRule(rule,schema,parentSchema,it){if(self._opts.validateSchema!==false){var deps=rule.definition.dependencies;if(deps&&!deps.every(function(keyword){return Object.prototype.hasOwnProperty.call(parentSchema,keyword)}))throw new Error("parent schema must have all required keywords: "+deps.join(","));var validateSchema=rule.definition.validateSchema;if(validateSchema){var valid=validateSchema(schema);if(!valid){var message="keyword schema is invalid: "+self.errorsText(validateSchema.errors);if(self._opts.validateSchema=="log")self.logger.error(message);else throw new Error(message)}}}var compile=rule.definition.compile,inline=rule.definition.inline,macro=rule.definition.macro;var validate;if(compile){validate=compile.call(self,schema,parentSchema,it)}else if(macro){validate=macro.call(self,schema,parentSchema,it);if(opts.validateSchema!==false)self.validateSchema(validate,true)}else if(inline){validate=inline.call(self,it,rule.keyword,schema,parentSchema)}else{validate=rule.definition.validate;if(!validate)return}if(validate===undefined)throw new Error('custom keyword "'+rule.keyword+'"failed to compile');var index=customRules.length;customRules[index]=validate;return{code:"customRule"+index,validate:validate}}}function checkCompiling(schema,root,baseId){var index=compIndex.call(this,schema,root,baseId);if(index>=0)return{index:index,compiling:true};index=this._compilations.length;this._compilations[index]={schema:schema,root:root,baseId:baseId};return{index:index,compiling:false}}function endCompiling(schema,root,baseId){var i=compIndex.call(this,schema,root,baseId);if(i>=0)this._compilations.splice(i,1)}function compIndex(schema,root,baseId){for(var i=0;i<this._compilations.length;i++){var c=this._compilations[i];if(c.schema==schema&&c.root==root&&c.baseId==baseId)return i}return-1}function patternCode(i,patterns){return"var pattern"+i+" = new RegExp("+util.toQuotedString(patterns[i])+");"}function defaultCode(i){return"var default"+i+" = defaults["+i+"];"}function refValCode(i,refVal){return refVal[i]===undefined?"":"var refVal"+i+" = refVal["+i+"];"}function customRuleCode(i){return"var customRule"+i+" = customRules["+i+"];"}function vars(arr,statement){if(!arr.length)return"";var code="";for(var i=0;i<arr.length;i++)code+=statement(i,arr);return code}},{"../dotjs/validate":376,"./error_classes":341,"./resolve":344,"./util":348,"fast-deep-equal":401,"fast-json-stable-stringify":402}],344:[function(require,module,exports){"use strict";var URI=require("uri-js"),equal=require("fast-deep-equal"),util=require("./util"),SchemaObject=require("./schema_obj"),traverse=require("json-schema-traverse");module.exports=resolve;resolve.normalizeId=normalizeId;resolve.fullPath=getFullPath;resolve.url=resolveUrl;resolve.ids=resolveIds;resolve.inlineRef=inlineRef;resolve.schema=resolveSchema;function resolve(compile,root,ref){var refVal=this._refs[ref];if(typeof refVal=="string"){if(this._refs[refVal])refVal=this._refs[refVal];else return resolve.call(this,compile,root,refVal)}refVal=refVal||this._schemas[ref];if(refVal instanceof SchemaObject){return inlineRef(refVal.schema,this._opts.inlineRefs)?refVal.schema:refVal.validate||this._compile(refVal)}var res=resolveSchema.call(this,root,ref);var schema,v,baseId;if(res){schema=res.schema;root=res.root;baseId=res.baseId}if(schema instanceof SchemaObject){v=schema.validate||compile.call(this,schema.schema,root,undefined,baseId)}else if(schema!==undefined){v=inlineRef(schema,this._opts.inlineRefs)?schema:compile.call(this,schema,root,undefined,baseId)}return v}function resolveSchema(root,ref){var p=URI.parse(ref),refPath=_getFullPath(p),baseId=getFullPath(this._getId(root.schema));if(Object.keys(root.schema).length===0||refPath!==baseId){var id=normalizeId(refPath);var refVal=this._refs[id];if(typeof refVal=="string"){return resolveRecursive.call(this,root,refVal,p)}else if(refVal instanceof SchemaObject){if(!refVal.validate)this._compile(refVal);root=refVal}else{refVal=this._schemas[id];if(refVal instanceof SchemaObject){if(!refVal.validate)this._compile(refVal);if(id==normalizeId(ref))return{schema:refVal,root:root,baseId:baseId};root=refVal}else{return}}if(!root.schema)return;baseId=getFullPath(this._getId(root.schema))}return getJsonPointer.call(this,p,baseId,root.schema,root)}function resolveRecursive(root,ref,parsedRef){var res=resolveSchema.call(this,root,ref);if(res){var schema=res.schema;var baseId=res.baseId;root=res.root;var id=this._getId(schema);if(id)baseId=resolveUrl(baseId,id);return getJsonPointer.call(this,parsedRef,baseId,schema,root)}}var PREVENT_SCOPE_CHANGE=util.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function getJsonPointer(parsedRef,baseId,schema,root){parsedRef.fragment=parsedRef.fragment||"";if(parsedRef.fragment.slice(0,1)!="/")return;var parts=parsedRef.fragment.split("/");for(var i=1;i<parts.length;i++){var part=parts[i];if(part){part=util.unescapeFragment(part);schema=schema[part];if(schema===undefined)break;var id;if(!PREVENT_SCOPE_CHANGE[part]){id=this._getId(schema);if(id)baseId=resolveUrl(baseId,id);if(schema.$ref){var $ref=resolveUrl(baseId,schema.$ref);var res=resolveSchema.call(this,root,$ref);if(res){schema=res.schema;root=res.root;baseId=res.baseId}}}}}if(schema!==undefined&&schema!==root.schema)return{schema:schema,root:root,baseId:baseId}}var SIMPLE_INLINED=util.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function inlineRef(schema,limit){if(limit===false)return false;if(limit===undefined||limit===true)return checkNoRef(schema);else if(limit)return countKeys(schema)<=limit}function checkNoRef(schema){var item;if(Array.isArray(schema)){for(var i=0;i<schema.length;i++){item=schema[i];if(typeof item=="object"&&!checkNoRef(item))return false}}else{for(var key in schema){if(key=="$ref")return false;item=schema[key];if(typeof item=="object"&&!checkNoRef(item))return false}}return true}function countKeys(schema){var count=0,item;if(Array.isArray(schema)){for(var i=0;i<schema.length;i++){item=schema[i];if(typeof item=="object")count+=countKeys(item);if(count==Infinity)return Infinity}}else{for(var key in schema){if(key=="$ref")return Infinity;if(SIMPLE_INLINED[key]){count++}else{item=schema[key];if(typeof item=="object")count+=countKeys(item)+1;if(count==Infinity)return Infinity}}}return count}function getFullPath(id,normalize){if(normalize!==false)id=normalizeId(id);var p=URI.parse(id);return _getFullPath(p)}function _getFullPath(p){return URI.serialize(p).split("#")[0]+"#"}var TRAILING_SLASH_HASH=/#\/?$/;function normalizeId(id){return id?id.replace(TRAILING_SLASH_HASH,""):""}function resolveUrl(baseId,id){id=normalizeId(id);return URI.resolve(baseId,id)}function resolveIds(schema){var schemaId=normalizeId(this._getId(schema));var baseIds={"":schemaId};var fullPaths={"":getFullPath(schemaId,false)};var localRefs={};var self=this;traverse(schema,{allKeys:true},function(sch,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex){if(jsonPtr==="")return;var id=self._getId(sch);var baseId=baseIds[parentJsonPtr];var fullPath=fullPaths[parentJsonPtr]+"/"+parentKeyword;if(keyIndex!==undefined)fullPath+="/"+(typeof keyIndex=="number"?keyIndex:util.escapeFragment(keyIndex));if(typeof id=="string"){id=baseId=normalizeId(baseId?URI.resolve(baseId,id):id);var refVal=self._refs[id];if(typeof refVal=="string")refVal=self._refs[refVal];if(refVal&&refVal.schema){if(!equal(sch,refVal.schema))throw new Error('id "'+id+'" resolves to more than one schema')}else if(id!=normalizeId(fullPath)){if(id[0]=="#"){if(localRefs[id]&&!equal(sch,localRefs[id]))throw new Error('id "'+id+'" resolves to more than one schema');localRefs[id]=sch}else{self._refs[id]=fullPath}}}baseIds[jsonPtr]=baseId;fullPaths[jsonPtr]=fullPath});return localRefs}},{"./schema_obj":346,"./util":348,"fast-deep-equal":401,"json-schema-traverse":434,"uri-js":505}],345:[function(require,module,exports){"use strict";var ruleModules=require("../dotjs"),toHash=require("./util").toHash;module.exports=function rules(){var RULES=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}];var ALL=["type","$comment"];var KEYWORDS=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"];var TYPES=["number","integer","string","array","object","boolean","null"];RULES.all=toHash(ALL);RULES.types=toHash(TYPES);RULES.forEach(function(group){group.rules=group.rules.map(function(keyword){var implKeywords;if(typeof keyword=="object"){var key=Object.keys(keyword)[0];implKeywords=keyword[key];keyword=key;implKeywords.forEach(function(k){ALL.push(k);RULES.all[k]=true})}ALL.push(keyword);var rule=RULES.all[keyword]={keyword:keyword,code:ruleModules[keyword],implements:implKeywords};return rule});RULES.all.$comment={keyword:"$comment",code:ruleModules.$comment};if(group.type)RULES.types[group.type]=group});RULES.keywords=toHash(ALL.concat(KEYWORDS));RULES.custom={};return RULES}},{"../dotjs":365,"./util":348}],346:[function(require,module,exports){"use strict";var util=require("./util");module.exports=SchemaObject;function SchemaObject(obj){util.copy(obj,this)}},{"./util":348}],347:[function(require,module,exports){"use strict";module.exports=function ucs2length(str){var length=0,len=str.length,pos=0,value;while(pos<len){length++;value=str.charCodeAt(pos++);if(value>=55296&&value<=56319&&pos<len){value=str.charCodeAt(pos);if((value&64512)==56320)pos++}}return length}},{}],348:[function(require,module,exports){"use strict";module.exports={copy:copy,checkDataType:checkDataType,checkDataTypes:checkDataTypes,coerceToTypes:coerceToTypes,toHash:toHash,getProperty:getProperty,escapeQuotes:escapeQuotes,equal:require("fast-deep-equal"),ucs2length:require("./ucs2length"),varOccurences:varOccurences,varReplace:varReplace,schemaHasRules:schemaHasRules,schemaHasRulesExcept:schemaHasRulesExcept,schemaUnknownRules:schemaUnknownRules,toQuotedString:toQuotedString,getPathExpr:getPathExpr,getPath:getPath,getData:getData,unescapeFragment:unescapeFragment,unescapeJsonPointer:unescapeJsonPointer,escapeFragment:escapeFragment,escapeJsonPointer:escapeJsonPointer};function copy(o,to){to=to||{};for(var key in o)to[key]=o[key];return to}function checkDataType(dataType,data,strictNumbers,negate){var EQUAL=negate?" !== ":" === ",AND=negate?" || ":" && ",OK=negate?"!":"",NOT=negate?"":"!";switch(dataType){case"null":return data+EQUAL+"null";case"array":return OK+"Array.isArray("+data+")";case"object":return"("+OK+data+AND+"typeof "+data+EQUAL+'"object"'+AND+NOT+"Array.isArray("+data+"))";case"integer":return"(typeof "+data+EQUAL+'"number"'+AND+NOT+"("+data+" % 1)"+AND+data+EQUAL+data+(strictNumbers?AND+OK+"isFinite("+data+")":"")+")";case"number":return"(typeof "+data+EQUAL+'"'+dataType+'"'+(strictNumbers?AND+OK+"isFinite("+data+")":"")+")";default:return"typeof "+data+EQUAL+'"'+dataType+'"'}}function checkDataTypes(dataTypes,data,strictNumbers){switch(dataTypes.length){case 1:return checkDataType(dataTypes[0],data,strictNumbers,true);default:var code="";var types=toHash(dataTypes);if(types.array&&types.object){code=types.null?"(":"(!"+data+" || ";code+="typeof "+data+' !== "object")';delete types.null;delete types.array;delete types.object}if(types.number)delete types.integer;for(var t in types)code+=(code?" && ":"")+checkDataType(t,data,strictNumbers,true);return code}}var COERCE_TO_TYPES=toHash(["string","number","integer","boolean","null"]);function coerceToTypes(optionCoerceTypes,dataTypes){if(Array.isArray(dataTypes)){var types=[];for(var i=0;i<dataTypes.length;i++){var t=dataTypes[i];if(COERCE_TO_TYPES[t])types[types.length]=t;else if(optionCoerceTypes==="array"&&t==="array")types[types.length]=t}if(types.length)return types}else if(COERCE_TO_TYPES[dataTypes]){return[dataTypes]}else if(optionCoerceTypes==="array"&&dataTypes==="array"){return["array"]}}function toHash(arr){var hash={};for(var i=0;i<arr.length;i++)hash[arr[i]]=true;return hash}var IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var SINGLE_QUOTE=/'|\\/g;function getProperty(key){return typeof key=="number"?"["+key+"]":IDENTIFIER.test(key)?"."+key:"['"+escapeQuotes(key)+"']"}function escapeQuotes(str){return str.replace(SINGLE_QUOTE,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function varOccurences(str,dataVar){dataVar+="[^0-9]";var matches=str.match(new RegExp(dataVar,"g"));return matches?matches.length:0}function varReplace(str,dataVar,expr){dataVar+="([^0-9])";expr=expr.replace(/\$/g,"$$$$");return str.replace(new RegExp(dataVar,"g"),expr+"$1")}function schemaHasRules(schema,rules){if(typeof schema=="boolean")return!schema;for(var key in schema)if(rules[key])return true}function schemaHasRulesExcept(schema,rules,exceptKeyword){if(typeof schema=="boolean")return!schema&&exceptKeyword!="not";for(var key in schema)if(key!=exceptKeyword&&rules[key])return true}function schemaUnknownRules(schema,rules){if(typeof schema=="boolean")return;for(var key in schema)if(!rules[key])return key}function toQuotedString(str){return"'"+escapeQuotes(str)+"'"}function getPathExpr(currentPath,expr,jsonPointers,isNumber){var path=jsonPointers?"'/' + "+expr+(isNumber?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):isNumber?"'[' + "+expr+" + ']'":"'[\\'' + "+expr+" + '\\']'";return joinPaths(currentPath,path)}function getPath(currentPath,prop,jsonPointers){var path=jsonPointers?toQuotedString("/"+escapeJsonPointer(prop)):toQuotedString(getProperty(prop));return joinPaths(currentPath,path)}var JSON_POINTER=/^\/(?:[^~]|~0|~1)*$/;var RELATIVE_JSON_POINTER=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function getData($data,lvl,paths){var up,jsonPointer,data,matches;if($data==="")return"rootData";if($data[0]=="/"){if(!JSON_POINTER.test($data))throw new Error("Invalid JSON-pointer: "+$data);jsonPointer=$data;data="rootData"}else{matches=$data.match(RELATIVE_JSON_POINTER);if(!matches)throw new Error("Invalid JSON-pointer: "+$data);up=+matches[1];jsonPointer=matches[2];if(jsonPointer=="#"){if(up>=lvl)throw new Error("Cannot access property/index "+up+" levels up, current level is "+lvl);return paths[lvl-up]}if(up>lvl)throw new Error("Cannot access data "+up+" levels up, current level is "+lvl);data="data"+(lvl-up||"");if(!jsonPointer)return data}var expr=data;var segments=jsonPointer.split("/");for(var i=0;i<segments.length;i++){var segment=segments[i];if(segment){data+=getProperty(unescapeJsonPointer(segment));expr+=" && "+data}}return expr}function joinPaths(a,b){if(a=='""')return b;return(a+" + "+b).replace(/([^\\])' \+ '/g,"$1")}function unescapeFragment(str){return unescapeJsonPointer(decodeURIComponent(str))}function escapeFragment(str){return encodeURIComponent(escapeJsonPointer(str))}function escapeJsonPointer(str){return str.replace(/~/g,"~0").replace(/\//g,"~1")}function unescapeJsonPointer(str){return str.replace(/~1/g,"/").replace(/~0/g,"~")}},{"./ucs2length":347,"fast-deep-equal":401}],349:[function(require,module,exports){"use strict";var KEYWORDS=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];module.exports=function(metaSchema,keywordsJsonPointers){for(var i=0;i<keywordsJsonPointers.length;i++){metaSchema=JSON.parse(JSON.stringify(metaSchema));var segments=keywordsJsonPointers[i].split("/");var keywords=metaSchema;var j;for(j=1;j<segments.length;j++)keywords=keywords[segments[j]];for(j=0;j<KEYWORDS.length;j++){var key=KEYWORDS[j];var schema=keywords[key];if(schema){keywords[key]={anyOf:[schema,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}}}}return metaSchema}},{}],350:[function(require,module,exports){"use strict";var metaSchema=require("./refs/json-schema-draft-07.json");module.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:metaSchema.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:metaSchema.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}}},{"./refs/json-schema-draft-07.json":380}],351:[function(require,module,exports){"use strict";module.exports=function generate__limit(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $isMax=$keyword=="maximum",$exclusiveKeyword=$isMax?"exclusiveMaximum":"exclusiveMinimum",$schemaExcl=it.schema[$exclusiveKeyword],$isDataExcl=it.opts.$data&&$schemaExcl&&$schemaExcl.$data,$op=$isMax?"<":">",$notOp=$isMax?">":"<",$errorKeyword=undefined;if(!($isData||typeof $schema=="number"||$schema===undefined)){throw new Error($keyword+" must be number")}if(!($isDataExcl||$schemaExcl===undefined||typeof $schemaExcl=="number"||typeof $schemaExcl=="boolean")){throw new Error($exclusiveKeyword+" must be number or boolean")}if($isDataExcl){var $schemaValueExcl=it.util.getData($schemaExcl.$data,$dataLvl,it.dataPathArr),$exclusive="exclusive"+$lvl,$exclType="exclType"+$lvl,$exclIsNumber="exclIsNumber"+$lvl,$opExpr="op"+$lvl,$opStr="' + "+$opExpr+" + '";out+=" var schemaExcl"+$lvl+" = "+$schemaValueExcl+"; ";$schemaValueExcl="schemaExcl"+$lvl;out+=" var "+$exclusive+"; var "+$exclType+" = typeof "+$schemaValueExcl+"; if ("+$exclType+" != 'boolean' && "+$exclType+" != 'undefined' && "+$exclType+" != 'number') { ";var $errorKeyword=$exclusiveKeyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: '"+$exclusiveKeyword+" should be boolean' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } else if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}out+=" "+$exclType+" == 'number' ? ( ("+$exclusive+" = "+$schemaValue+" === undefined || "+$schemaValueExcl+" "+$op+"= "+$schemaValue+") ? "+$data+" "+$notOp+"= "+$schemaValueExcl+" : "+$data+" "+$notOp+" "+$schemaValue+" ) : ( ("+$exclusive+" = "+$schemaValueExcl+" === true) ? "+$data+" "+$notOp+"= "+$schemaValue+" : "+$data+" "+$notOp+" "+$schemaValue+" ) || "+$data+" !== "+$data+") { var op"+$lvl+" = "+$exclusive+" ? '"+$op+"' : '"+$op+"='; ";if($schema===undefined){$errorKeyword=$exclusiveKeyword;$errSchemaPath=it.errSchemaPath+"/"+$exclusiveKeyword;$schemaValue=$schemaValueExcl;$isData=$isDataExcl}}else{var $exclIsNumber=typeof $schemaExcl=="number",$opStr=$op;if($exclIsNumber&&$isData){var $opExpr="'"+$opStr+"'";out+=" if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}out+=" ( "+$schemaValue+" === undefined || "+$schemaExcl+" "+$op+"= "+$schemaValue+" ? "+$data+" "+$notOp+"= "+$schemaExcl+" : "+$data+" "+$notOp+" "+$schemaValue+" ) || "+$data+" !== "+$data+") { "}else{if($exclIsNumber&&$schema===undefined){$exclusive=true;$errorKeyword=$exclusiveKeyword;$errSchemaPath=it.errSchemaPath+"/"+$exclusiveKeyword;$schemaValue=$schemaExcl;$notOp+="="}else{if($exclIsNumber)$schemaValue=Math[$isMax?"min":"max"]($schemaExcl,$schema);if($schemaExcl===($exclIsNumber?$schemaValue:true)){$exclusive=true;$errorKeyword=$exclusiveKeyword;$errSchemaPath=it.errSchemaPath+"/"+$exclusiveKeyword;$notOp+="="}else{$exclusive=false;$opStr+="="}}var $opExpr="'"+$opStr+"'";out+=" if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}out+=" "+$data+" "+$notOp+" "+$schemaValue+" || "+$data+" !== "+$data+") { "}}$errorKeyword=$errorKeyword||$keyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"_limit")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { comparison: "+$opExpr+", limit: "+$schemaValue+", exclusive: "+$exclusive+" } ";if(it.opts.messages!==false){out+=" , message: 'should be "+$opStr+" ";if($isData){out+="' + "+$schemaValue}else{out+=""+$schemaValue+"'"}}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{
35
- out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } ";if($breakOnError){out+=" else { "}return out}},{}],352:[function(require,module,exports){"use strict";module.exports=function generate__limitItems(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(!($isData||typeof $schema=="number")){throw new Error($keyword+" must be number")}var $op=$keyword=="maxItems"?">":"<";out+="if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}out+=" "+$data+".length "+$op+" "+$schemaValue+") { ";var $errorKeyword=$keyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"_limitItems")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { limit: "+$schemaValue+" } ";if(it.opts.messages!==false){out+=" , message: 'should NOT have ";if($keyword=="maxItems"){out+="more"}else{out+="fewer"}out+=" than ";if($isData){out+="' + "+$schemaValue+" + '"}else{out+=""+$schema}out+=" items' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+="} ";if($breakOnError){out+=" else { "}return out}},{}],353:[function(require,module,exports){"use strict";module.exports=function generate__limitLength(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(!($isData||typeof $schema=="number")){throw new Error($keyword+" must be number")}var $op=$keyword=="maxLength"?">":"<";out+="if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}if(it.opts.unicode===false){out+=" "+$data+".length "}else{out+=" ucs2length("+$data+") "}out+=" "+$op+" "+$schemaValue+") { ";var $errorKeyword=$keyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"_limitLength")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { limit: "+$schemaValue+" } ";if(it.opts.messages!==false){out+=" , message: 'should NOT be ";if($keyword=="maxLength"){out+="longer"}else{out+="shorter"}out+=" than ";if($isData){out+="' + "+$schemaValue+" + '"}else{out+=""+$schema}out+=" characters' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+="} ";if($breakOnError){out+=" else { "}return out}},{}],354:[function(require,module,exports){"use strict";module.exports=function generate__limitProperties(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(!($isData||typeof $schema=="number")){throw new Error($keyword+" must be number")}var $op=$keyword=="maxProperties"?">":"<";out+="if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}out+=" Object.keys("+$data+").length "+$op+" "+$schemaValue+") { ";var $errorKeyword=$keyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"_limitProperties")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { limit: "+$schemaValue+" } ";if(it.opts.messages!==false){out+=" , message: 'should NOT have ";if($keyword=="maxProperties"){out+="more"}else{out+="fewer"}out+=" than ";if($isData){out+="' + "+$schemaValue+" + '"}else{out+=""+$schema}out+=" properties' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+="} ";if($breakOnError){out+=" else { "}return out}},{}],355:[function(require,module,exports){"use strict";module.exports=function generate_allOf(it,$keyword,$ruleType){var out=" ";var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $currentBaseId=$it.baseId,$allSchemasEmpty=true;var arr1=$schema;if(arr1){var $sch,$i=-1,l1=arr1.length-1;while($i<l1){$sch=arr1[$i+=1];if(it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)){$allSchemasEmpty=false;$it.schema=$sch;$it.schemaPath=$schemaPath+"["+$i+"]";$it.errSchemaPath=$errSchemaPath+"/"+$i;out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}}}if($breakOnError){if($allSchemasEmpty){out+=" if (true) { "}else{out+=" "+$closingBraces.slice(0,-1)+" "}}return out}},{}],356:[function(require,module,exports){"use strict";module.exports=function generate_anyOf(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $noEmptySchema=$schema.every(function($sch){return it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)});if($noEmptySchema){var $currentBaseId=$it.baseId;out+=" var "+$errs+" = errors; var "+$valid+" = false; ";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;var arr1=$schema;if(arr1){var $sch,$i=-1,l1=arr1.length-1;while($i<l1){$sch=arr1[$i+=1];$it.schema=$sch;$it.schemaPath=$schemaPath+"["+$i+"]";$it.errSchemaPath=$errSchemaPath+"/"+$i;out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;out+=" "+$valid+" = "+$valid+" || "+$nextValid+"; if (!"+$valid+") { ";$closingBraces+="}"}}it.compositeRule=$it.compositeRule=$wasComposite;out+=" "+$closingBraces+" if (!"+$valid+") { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"anyOf"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: 'should match some schema in anyOf' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(vErrors); "}else{out+=" validate.errors = vErrors; return false; "}}out+=" } else { errors = "+$errs+"; if (vErrors !== null) { if ("+$errs+") vErrors.length = "+$errs+"; else vErrors = null; } ";if(it.opts.allErrors){out+=" } "}}else{if($breakOnError){out+=" if (true) { "}}return out}},{}],357:[function(require,module,exports){"use strict";module.exports=function generate_comment(it,$keyword,$ruleType){var out=" ";var $schema=it.schema[$keyword];var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $comment=it.util.toQuotedString($schema);if(it.opts.$comment===true){out+=" console.log("+$comment+");"}else if(typeof it.opts.$comment=="function"){out+=" self._opts.$comment("+$comment+", "+it.util.toQuotedString($errSchemaPath)+", validate.root.schema);"}return out}},{}],358:[function(require,module,exports){"use strict";module.exports=function generate_const(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(!$isData){out+=" var schema"+$lvl+" = validate.schema"+$schemaPath+";"}out+="var "+$valid+" = equal("+$data+", schema"+$lvl+"); if (!"+$valid+") { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"const"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { allowedValue: schema"+$lvl+" } ";if(it.opts.messages!==false){out+=" , message: 'should be equal to constant' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" }";if($breakOnError){out+=" else { "}return out}},{}],359:[function(require,module,exports){"use strict";module.exports=function generate_contains(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $idx="i"+$lvl,$dataNxt=$it.dataLevel=it.dataLevel+1,$nextData="data"+$dataNxt,$currentBaseId=it.baseId,$nonEmptySchema=it.opts.strictKeywords?typeof $schema=="object"&&Object.keys($schema).length>0||$schema===false:it.util.schemaHasRules($schema,it.RULES.all);out+="var "+$errs+" = errors;var "+$valid+";";if($nonEmptySchema){var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;$it.schema=$schema;$it.schemaPath=$schemaPath;$it.errSchemaPath=$errSchemaPath;out+=" var "+$nextValid+" = false; for (var "+$idx+" = 0; "+$idx+" < "+$data+".length; "+$idx+"++) { ";$it.errorPath=it.util.getPathExpr(it.errorPath,$idx,it.opts.jsonPointers,true);var $passData=$data+"["+$idx+"]";$it.dataPathArr[$dataNxt]=$idx;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}out+=" if ("+$nextValid+") break; } ";it.compositeRule=$it.compositeRule=$wasComposite;out+=" "+$closingBraces+" if (!"+$nextValid+") {"}else{out+=" if ("+$data+".length == 0) {"}var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"contains"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: 'should contain a valid item' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } else { ";if($nonEmptySchema){out+=" errors = "+$errs+"; if (vErrors !== null) { if ("+$errs+") vErrors.length = "+$errs+"; else vErrors = null; } "}if(it.opts.allErrors){out+=" } "}return out}},{}],360:[function(require,module,exports){"use strict";module.exports=function generate_custom(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $rule=this,$definition="definition"+$lvl,$rDef=$rule.definition,$closingBraces="";var $compile,$inline,$macro,$ruleValidate,$validateCode;if($isData&&$rDef.$data){$validateCode="keywordValidate"+$lvl;var $validateSchema=$rDef.validateSchema;out+=" var "+$definition+" = RULES.custom['"+$keyword+"'].definition; var "+$validateCode+" = "+$definition+".validate;"}else{$ruleValidate=it.useCustomRule($rule,$schema,it.schema,it);if(!$ruleValidate)return;$schemaValue="validate.schema"+$schemaPath;$validateCode=$ruleValidate.code;$compile=$rDef.compile;$inline=$rDef.inline;$macro=$rDef.macro}var $ruleErrs=$validateCode+".errors",$i="i"+$lvl,$ruleErr="ruleErr"+$lvl,$asyncKeyword=$rDef.async;if($asyncKeyword&&!it.async)throw new Error("async keyword in sync schema");if(!($inline||$macro)){out+=""+$ruleErrs+" = null;"}out+="var "+$errs+" = errors;var "+$valid+";";if($isData&&$rDef.$data){$closingBraces+="}";out+=" if ("+$schemaValue+" === undefined) { "+$valid+" = true; } else { ";if($validateSchema){$closingBraces+="}";out+=" "+$valid+" = "+$definition+".validateSchema("+$schemaValue+"); if ("+$valid+") { "}}if($inline){if($rDef.statements){out+=" "+$ruleValidate.validate+" "}else{out+=" "+$valid+" = "+$ruleValidate.validate+"; "}}else if($macro){var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;$it.schema=$ruleValidate.validate;$it.schemaPath="";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;var $code=it.validate($it).replace(/validate\.schema/g,$validateCode);it.compositeRule=$it.compositeRule=$wasComposite;out+=" "+$code}else{var $$outStack=$$outStack||[];$$outStack.push(out);out="";out+=" "+$validateCode+".call( ";if(it.opts.passContext){out+="this"}else{out+="self"}if($compile||$rDef.schema===false){out+=" , "+$data+" "}else{out+=" , "+$schemaValue+" , "+$data+" , validate.schema"+it.schemaPath+" "}out+=" , (dataPath || '')";if(it.errorPath!='""'){out+=" + "+it.errorPath}var $parentData=$dataLvl?"data"+($dataLvl-1||""):"parentData",$parentDataProperty=$dataLvl?it.dataPathArr[$dataLvl]:"parentDataProperty";out+=" , "+$parentData+" , "+$parentDataProperty+" , rootData ) ";var def_callRuleValidate=out;out=$$outStack.pop();if($rDef.errors===false){out+=" "+$valid+" = ";if($asyncKeyword){out+="await "}out+=""+def_callRuleValidate+"; "}else{if($asyncKeyword){$ruleErrs="customErrors"+$lvl;out+=" var "+$ruleErrs+" = null; try { "+$valid+" = await "+def_callRuleValidate+"; } catch (e) { "+$valid+" = false; if (e instanceof ValidationError) "+$ruleErrs+" = e.errors; else throw e; } "}else{out+=" "+$ruleErrs+" = null; "+$valid+" = "+def_callRuleValidate+"; "}}}if($rDef.modifying){out+=" if ("+$parentData+") "+$data+" = "+$parentData+"["+$parentDataProperty+"];"}out+=""+$closingBraces;if($rDef.valid){if($breakOnError){out+=" if (true) { "}}else{out+=" if ( ";if($rDef.valid===undefined){out+=" !";if($macro){out+=""+$nextValid}else{out+=""+$valid}}else{out+=" "+!$rDef.valid+" "}out+=") { ";$errorKeyword=$rule.keyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"custom")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { keyword: '"+$rule.keyword+"' } ";if(it.opts.messages!==false){out+=" , message: 'should pass \""+$rule.keyword+"\" keyword validation' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}var def_customError=out;out=$$outStack.pop();if($inline){if($rDef.errors){if($rDef.errors!="full"){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+'"; } ';if(it.opts.verbose){out+=" "+$ruleErr+".schema = "+$schemaValue+"; "+$ruleErr+".data = "+$data+"; "}out+=" } "}}else{if($rDef.errors===false){out+=" "+def_customError+" "}else{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+'"; } ';if(it.opts.verbose){out+=" "+$ruleErr+".schema = "+$schemaValue+"; "+$ruleErr+".data = "+$data+"; "}out+=" } } "}}}else if($macro){out+=" var err = ";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"custom")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { keyword: '"+$rule.keyword+"' } ";if(it.opts.messages!==false){out+=" , message: 'should pass \""+$rule.keyword+"\" keyword validation' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(vErrors); "}else{out+=" validate.errors = vErrors; return false; "}}}else{if($rDef.errors===false){out+=" "+def_customError+" "}else{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+'"; ';if(it.opts.verbose){out+=" "+$ruleErr+".schema = "+$schemaValue+"; "+$ruleErr+".data = "+$data+"; "}out+=" } } else { "+def_customError+" } "}}out+=" } ";if($breakOnError){out+=" else { "}}return out}},{}],361:[function(require,module,exports){"use strict";module.exports=function generate_dependencies(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $schemaDeps={},$propertyDeps={},$ownProperties=it.opts.ownProperties;for($property in $schema){if($property=="__proto__")continue;var $sch=$schema[$property];var $deps=Array.isArray($sch)?$propertyDeps:$schemaDeps;$deps[$property]=$sch}out+="var "+$errs+" = errors;";var $currentErrorPath=it.errorPath;out+="var missing"+$lvl+";";for(var $property in $propertyDeps){$deps=$propertyDeps[$property];if($deps.length){out+=" if ( "+$data+it.util.getProperty($property)+" !== undefined ";if($ownProperties){out+=" && Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($property)+"') "}if($breakOnError){out+=" && ( ";var arr1=$deps;if(arr1){var $propertyKey,$i=-1,l1=arr1.length-1;while($i<l1){$propertyKey=arr1[$i+=1];if($i){out+=" || "}var $prop=it.util.getProperty($propertyKey),$useData=$data+$prop;out+=" ( ( "+$useData+" === undefined ";if($ownProperties){out+=" || ! Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($propertyKey)+"') "}out+=") && (missing"+$lvl+" = "+it.util.toQuotedString(it.opts.jsonPointers?$propertyKey:$prop)+") ) "}}out+=")) { ";var $propertyPath="missing"+$lvl,$missingProperty="' + "+$propertyPath+" + '";if(it.opts._errorDataPathProperty){it.errorPath=it.opts.jsonPointers?it.util.getPathExpr($currentErrorPath,$propertyPath,true):$currentErrorPath+" + "+$propertyPath}var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"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(", "))+"' } ";if(it.opts.messages!==false){out+=" , message: 'should have ";if($deps.length==1){out+="property "+it.util.escapeQuotes($deps[0])}else{out+="properties "+it.util.escapeQuotes($deps.join(", "))}out+=" when property "+it.util.escapeQuotes($property)+" is present' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}}else{out+=" ) { ";var arr2=$deps;if(arr2){var $propertyKey,i2=-1,l2=arr2.length-1;while(i2<l2){$propertyKey=arr2[i2+=1];var $prop=it.util.getProperty($propertyKey),$missingProperty=it.util.escapeQuotes($propertyKey),$useData=$data+$prop;if(it.opts._errorDataPathProperty){it.errorPath=it.util.getPath($currentErrorPath,$propertyKey,it.opts.jsonPointers)}out+=" if ( "+$useData+" === undefined ";if($ownProperties){out+=" || ! Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($propertyKey)+"') "}out+=") { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"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(", "))+"' } ";if(it.opts.messages!==false){out+=" , message: 'should have ";if($deps.length==1){out+="property "+it.util.escapeQuotes($deps[0])}else{out+="properties "+it.util.escapeQuotes($deps.join(", "))}out+=" when property "+it.util.escapeQuotes($property)+" is present' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}}out+=" } ";if($breakOnError){$closingBraces+="}";out+=" else { "}}}it.errorPath=$currentErrorPath;var $currentBaseId=$it.baseId;for(var $property in $schemaDeps){var $sch=$schemaDeps[$property];if(it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)){out+=" "+$nextValid+" = true; if ( "+$data+it.util.getProperty($property)+" !== undefined ";if($ownProperties){out+=" && Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($property)+"') "}out+=") { ";$it.schema=$sch;$it.schemaPath=$schemaPath+it.util.getProperty($property);$it.errSchemaPath=$errSchemaPath+"/"+it.util.escapeFragment($property);out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;out+=" } ";if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}}if($breakOnError){out+=" "+$closingBraces+" if ("+$errs+" == errors) {"}return out}},{}],362:[function(require,module,exports){"use strict";module.exports=function generate_enum(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $i="i"+$lvl,$vSchema="schema"+$lvl;if(!$isData){out+=" var "+$vSchema+" = validate.schema"+$schemaPath+";"}out+="var "+$valid+";";if($isData){out+=" if (schema"+$lvl+" === undefined) "+$valid+" = true; else if (!Array.isArray(schema"+$lvl+")) "+$valid+" = false; else {"}out+=""+$valid+" = false;for (var "+$i+"=0; "+$i+"<"+$vSchema+".length; "+$i+"++) if (equal("+$data+", "+$vSchema+"["+$i+"])) { "+$valid+" = true; break; }";if($isData){out+=" } "}out+=" if (!"+$valid+") { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"enum"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { allowedValues: schema"+$lvl+" } ";if(it.opts.messages!==false){out+=" , message: 'should be equal to one of the allowed values' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" }";if($breakOnError){out+=" else { "}return out}},{}],363:[function(require,module,exports){"use strict";module.exports=function generate_format(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");if(it.opts.format===false){if($breakOnError){out+=" if (true) { "}return out}var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $unknownFormats=it.opts.unknownFormats,$allowUnknown=Array.isArray($unknownFormats);if($isData){var $format="format"+$lvl,$isObject="isObject"+$lvl,$formatType="formatType"+$lvl;out+=" var "+$format+" = formats["+$schemaValue+"]; var "+$isObject+" = typeof "+$format+" == 'object' && !("+$format+" instanceof RegExp) && "+$format+".validate; var "+$formatType+" = "+$isObject+" && "+$format+".type || 'string'; if ("+$isObject+") { ";if(it.async){out+=" var async"+$lvl+" = "+$format+".async; "}out+=" "+$format+" = "+$format+".validate; } if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'string') || "}out+=" (";if($unknownFormats!="ignore"){out+=" ("+$schemaValue+" && !"+$format+" ";if($allowUnknown){out+=" && self._opts.unknownFormats.indexOf("+$schemaValue+") == -1 "}out+=") || "}out+=" ("+$format+" && "+$formatType+" == '"+$ruleType+"' && !(typeof "+$format+" == 'function' ? ";if(it.async){out+=" (async"+$lvl+" ? await "+$format+"("+$data+") : "+$format+"("+$data+")) "}else{out+=" "+$format+"("+$data+") "}out+=" : "+$format+".test("+$data+"))))) {"}else{var $format=it.formats[$schema];if(!$format){if($unknownFormats=="ignore"){it.logger.warn('unknown format "'+$schema+'" ignored in schema at path "'+it.errSchemaPath+'"');if($breakOnError){out+=" if (true) { "}return out}else if($allowUnknown&&$unknownFormats.indexOf($schema)>=0){if($breakOnError){out+=" if (true) { "}return out}else{throw new Error('unknown format "'+$schema+'" is used in schema at path "'+it.errSchemaPath+'"')}}var $isObject=typeof $format=="object"&&!($format instanceof RegExp)&&$format.validate;var $formatType=$isObject&&$format.type||"string";if($isObject){var $async=$format.async===true;$format=$format.validate}if($formatType!=$ruleType){if($breakOnError){out+=" if (true) { "}return out}if($async){if(!it.async)throw new Error("async format in sync schema");var $formatRef="formats"+it.util.getProperty($schema)+".validate";out+=" if (!(await "+$formatRef+"("+$data+"))) { "}else{out+=" if (! ";var $formatRef="formats"+it.util.getProperty($schema);if($isObject)$formatRef+=".validate";if(typeof $format=="function"){out+=" "+$formatRef+"("+$data+") "}else{out+=" "+$formatRef+".test("+$data+") "}out+=") { "}}var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){
36
- out+=" { keyword: '"+"format"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { format: ";if($isData){out+=""+$schemaValue}else{out+=""+it.util.toQuotedString($schema)}out+=" } ";if(it.opts.messages!==false){out+=" , message: 'should match format \"";if($isData){out+="' + "+$schemaValue+" + '"}else{out+=""+it.util.escapeQuotes($schema)}out+="\"' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+it.util.toQuotedString($schema)}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } ";if($breakOnError){out+=" else { "}return out}},{}],364:[function(require,module,exports){"use strict";module.exports=function generate_if(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $it=it.util.copy(it);$it.level++;var $nextValid="valid"+$it.level;var $thenSch=it.schema["then"],$elseSch=it.schema["else"],$thenPresent=$thenSch!==undefined&&(it.opts.strictKeywords?typeof $thenSch=="object"&&Object.keys($thenSch).length>0||$thenSch===false:it.util.schemaHasRules($thenSch,it.RULES.all)),$elsePresent=$elseSch!==undefined&&(it.opts.strictKeywords?typeof $elseSch=="object"&&Object.keys($elseSch).length>0||$elseSch===false:it.util.schemaHasRules($elseSch,it.RULES.all)),$currentBaseId=$it.baseId;if($thenPresent||$elsePresent){var $ifClause;$it.createErrors=false;$it.schema=$schema;$it.schemaPath=$schemaPath;$it.errSchemaPath=$errSchemaPath;out+=" var "+$errs+" = errors; var "+$valid+" = true; ";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;$it.createErrors=true;out+=" errors = "+$errs+"; if (vErrors !== null) { if ("+$errs+") vErrors.length = "+$errs+"; else vErrors = null; } ";it.compositeRule=$it.compositeRule=$wasComposite;if($thenPresent){out+=" if ("+$nextValid+") { ";$it.schema=it.schema["then"];$it.schemaPath=it.schemaPath+".then";$it.errSchemaPath=it.errSchemaPath+"/then";out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;out+=" "+$valid+" = "+$nextValid+"; ";if($thenPresent&&$elsePresent){$ifClause="ifClause"+$lvl;out+=" var "+$ifClause+" = 'then'; "}else{$ifClause="'then'"}out+=" } ";if($elsePresent){out+=" else { "}}else{out+=" if (!"+$nextValid+") { "}if($elsePresent){$it.schema=it.schema["else"];$it.schemaPath=it.schemaPath+".else";$it.errSchemaPath=it.errSchemaPath+"/else";out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;out+=" "+$valid+" = "+$nextValid+"; ";if($thenPresent&&$elsePresent){$ifClause="ifClause"+$lvl;out+=" var "+$ifClause+" = 'else'; "}else{$ifClause="'else'"}out+=" } "}out+=" if (!"+$valid+") { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"if"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { failingKeyword: "+$ifClause+" } ";if(it.opts.messages!==false){out+=" , message: 'should match \"' + "+$ifClause+" + '\" schema' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(vErrors); "}else{out+=" validate.errors = vErrors; return false; "}}out+=" } ";if($breakOnError){out+=" else { "}}else{if($breakOnError){out+=" if (true) { "}}return out}},{}],365:[function(require,module,exports){"use strict";module.exports={$ref:require("./ref"),allOf:require("./allOf"),anyOf:require("./anyOf"),$comment:require("./comment"),const:require("./const"),contains:require("./contains"),dependencies:require("./dependencies"),enum:require("./enum"),format:require("./format"),if:require("./if"),items:require("./items"),maximum:require("./_limit"),minimum:require("./_limit"),maxItems:require("./_limitItems"),minItems:require("./_limitItems"),maxLength:require("./_limitLength"),minLength:require("./_limitLength"),maxProperties:require("./_limitProperties"),minProperties:require("./_limitProperties"),multipleOf:require("./multipleOf"),not:require("./not"),oneOf:require("./oneOf"),pattern:require("./pattern"),properties:require("./properties"),propertyNames:require("./propertyNames"),required:require("./required"),uniqueItems:require("./uniqueItems"),validate:require("./validate")}},{"./_limit":351,"./_limitItems":352,"./_limitLength":353,"./_limitProperties":354,"./allOf":355,"./anyOf":356,"./comment":357,"./const":358,"./contains":359,"./dependencies":361,"./enum":362,"./format":363,"./if":364,"./items":366,"./multipleOf":367,"./not":368,"./oneOf":369,"./pattern":370,"./properties":371,"./propertyNames":372,"./ref":373,"./required":374,"./uniqueItems":375,"./validate":376}],366:[function(require,module,exports){"use strict";module.exports=function generate_items(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $idx="i"+$lvl,$dataNxt=$it.dataLevel=it.dataLevel+1,$nextData="data"+$dataNxt,$currentBaseId=it.baseId;out+="var "+$errs+" = errors;var "+$valid+";";if(Array.isArray($schema)){var $additionalItems=it.schema.additionalItems;if($additionalItems===false){out+=" "+$valid+" = "+$data+".length <= "+$schema.length+"; ";var $currErrSchemaPath=$errSchemaPath;$errSchemaPath=it.errSchemaPath+"/additionalItems";out+=" if (!"+$valid+") { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"additionalItems"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { limit: "+$schema.length+" } ";if(it.opts.messages!==false){out+=" , message: 'should NOT have more than "+$schema.length+" items' "}if(it.opts.verbose){out+=" , schema: false , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } ";$errSchemaPath=$currErrSchemaPath;if($breakOnError){$closingBraces+="}";out+=" else { "}}var arr1=$schema;if(arr1){var $sch,$i=-1,l1=arr1.length-1;while($i<l1){$sch=arr1[$i+=1];if(it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)){out+=" "+$nextValid+" = true; if ("+$data+".length > "+$i+") { ";var $passData=$data+"["+$i+"]";$it.schema=$sch;$it.schemaPath=$schemaPath+"["+$i+"]";$it.errSchemaPath=$errSchemaPath+"/"+$i;$it.errorPath=it.util.getPathExpr(it.errorPath,$i,it.opts.jsonPointers,true);$it.dataPathArr[$dataNxt]=$i;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}out+=" } ";if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}}}if(typeof $additionalItems=="object"&&(it.opts.strictKeywords?typeof $additionalItems=="object"&&Object.keys($additionalItems).length>0||$additionalItems===false:it.util.schemaHasRules($additionalItems,it.RULES.all))){$it.schema=$additionalItems;$it.schemaPath=it.schemaPath+".additionalItems";$it.errSchemaPath=it.errSchemaPath+"/additionalItems";out+=" "+$nextValid+" = true; if ("+$data+".length > "+$schema.length+") { for (var "+$idx+" = "+$schema.length+"; "+$idx+" < "+$data+".length; "+$idx+"++) { ";$it.errorPath=it.util.getPathExpr(it.errorPath,$idx,it.opts.jsonPointers,true);var $passData=$data+"["+$idx+"]";$it.dataPathArr[$dataNxt]=$idx;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}if($breakOnError){out+=" if (!"+$nextValid+") break; "}out+=" } } ";if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}}else if(it.opts.strictKeywords?typeof $schema=="object"&&Object.keys($schema).length>0||$schema===false:it.util.schemaHasRules($schema,it.RULES.all)){$it.schema=$schema;$it.schemaPath=$schemaPath;$it.errSchemaPath=$errSchemaPath;out+=" for (var "+$idx+" = "+0+"; "+$idx+" < "+$data+".length; "+$idx+"++) { ";$it.errorPath=it.util.getPathExpr(it.errorPath,$idx,it.opts.jsonPointers,true);var $passData=$data+"["+$idx+"]";$it.dataPathArr[$dataNxt]=$idx;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}if($breakOnError){out+=" if (!"+$nextValid+") break; "}out+=" }"}if($breakOnError){out+=" "+$closingBraces+" if ("+$errs+" == errors) {"}return out}},{}],367:[function(require,module,exports){"use strict";module.exports=function generate_multipleOf(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(!($isData||typeof $schema=="number")){throw new Error($keyword+" must be number")}out+="var division"+$lvl+";if (";if($isData){out+=" "+$schemaValue+" !== undefined && ( typeof "+$schemaValue+" != 'number' || "}out+=" (division"+$lvl+" = "+$data+" / "+$schemaValue+", ";if(it.opts.multipleOfPrecision){out+=" Math.abs(Math.round(division"+$lvl+") - division"+$lvl+") > 1e-"+it.opts.multipleOfPrecision+" "}else{out+=" division"+$lvl+" !== parseInt(division"+$lvl+") "}out+=" ) ";if($isData){out+=" ) "}out+=" ) { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"multipleOf"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { multipleOf: "+$schemaValue+" } ";if(it.opts.messages!==false){out+=" , message: 'should be multiple of ";if($isData){out+="' + "+$schemaValue}else{out+=""+$schemaValue+"'"}}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+="} ";if($breakOnError){out+=" else { "}return out}},{}],368:[function(require,module,exports){"use strict";module.exports=function generate_not(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $errs="errs__"+$lvl;var $it=it.util.copy(it);$it.level++;var $nextValid="valid"+$it.level;if(it.opts.strictKeywords?typeof $schema=="object"&&Object.keys($schema).length>0||$schema===false:it.util.schemaHasRules($schema,it.RULES.all)){$it.schema=$schema;$it.schemaPath=$schemaPath;$it.errSchemaPath=$errSchemaPath;out+=" var "+$errs+" = errors; ";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;$it.createErrors=false;var $allErrorsOption;if($it.opts.allErrors){$allErrorsOption=$it.opts.allErrors;$it.opts.allErrors=false}out+=" "+it.validate($it)+" ";$it.createErrors=true;if($allErrorsOption)$it.opts.allErrors=$allErrorsOption;it.compositeRule=$it.compositeRule=$wasComposite;out+=" if ("+$nextValid+") { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"not"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: 'should NOT be valid' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } else { errors = "+$errs+"; if (vErrors !== null) { if ("+$errs+") vErrors.length = "+$errs+"; else vErrors = null; } ";if(it.opts.allErrors){out+=" } "}}else{out+=" var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"not"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: 'should NOT be valid' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if($breakOnError){out+=" if (false) { "}}return out}},{}],369:[function(require,module,exports){"use strict";module.exports=function generate_oneOf(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $currentBaseId=$it.baseId,$prevValid="prevValid"+$lvl,$passingSchemas="passingSchemas"+$lvl;out+="var "+$errs+" = errors , "+$prevValid+" = false , "+$valid+" = false , "+$passingSchemas+" = null; ";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;var arr1=$schema;if(arr1){var $sch,$i=-1,l1=arr1.length-1;while($i<l1){$sch=arr1[$i+=1];if(it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)){$it.schema=$sch;$it.schemaPath=$schemaPath+"["+$i+"]";$it.errSchemaPath=$errSchemaPath+"/"+$i;out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId}else{out+=" var "+$nextValid+" = true; "}if($i){out+=" if ("+$nextValid+" && "+$prevValid+") { "+$valid+" = false; "+$passingSchemas+" = ["+$passingSchemas+", "+$i+"]; } else { ";$closingBraces+="}"}out+=" if ("+$nextValid+") { "+$valid+" = "+$prevValid+" = true; "+$passingSchemas+" = "+$i+"; }"}}it.compositeRule=$it.compositeRule=$wasComposite;out+=""+$closingBraces+"if (!"+$valid+") { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"oneOf"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { passingSchemas: "+$passingSchemas+" } ";if(it.opts.messages!==false){out+=" , message: 'should match exactly one schema in oneOf' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(vErrors); "}else{out+=" validate.errors = vErrors; return false; "}}out+="} else { errors = "+$errs+"; if (vErrors !== null) { if ("+$errs+") vErrors.length = "+$errs+"; else vErrors = null; }";if(it.opts.allErrors){out+=" } "}return out}},{}],370:[function(require,module,exports){"use strict";module.exports=function generate_pattern(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $regexp=$isData?"(new RegExp("+$schemaValue+"))":it.usePattern($schema);out+="if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'string') || "}out+=" !"+$regexp+".test("+$data+") ) { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"pattern"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { pattern: ";if($isData){out+=""+$schemaValue}else{out+=""+it.util.toQuotedString($schema)}out+=" } ";if(it.opts.messages!==false){out+=" , message: 'should match pattern \"";if($isData){out+="' + "+$schemaValue+" + '"}else{out+=""+it.util.escapeQuotes($schema)}out+="\"' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+it.util.toQuotedString($schema)}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+="} ";if($breakOnError){out+=" else { "}return out}},{}],371:[function(require,module,exports){"use strict";module.exports=function generate_properties(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $key="key"+$lvl,$idx="idx"+$lvl,$dataNxt=$it.dataLevel=it.dataLevel+1,$nextData="data"+$dataNxt,$dataProperties="dataProperties"+$lvl;var $schemaKeys=Object.keys($schema||{}).filter(notProto),$pProperties=it.schema.patternProperties||{},$pPropertyKeys=Object.keys($pProperties).filter(notProto),$aProperties=it.schema.additionalProperties,$someProperties=$schemaKeys.length||$pPropertyKeys.length,$noAdditional=$aProperties===false,$additionalIsSchema=typeof $aProperties=="object"&&Object.keys($aProperties).length,$removeAdditional=it.opts.removeAdditional,$checkAdditional=$noAdditional||$additionalIsSchema||$removeAdditional,$ownProperties=it.opts.ownProperties,$currentBaseId=it.baseId;var $required=it.schema.required;if($required&&!(it.opts.$data&&$required.$data)&&$required.length<it.opts.loopRequired){var $requiredHash=it.util.toHash($required)}function notProto(p){return p!=="__proto__"}out+="var "+$errs+" = errors;var "+$nextValid+" = true;";if($ownProperties){out+=" var "+$dataProperties+" = undefined;"}if($checkAdditional){if($ownProperties){out+=" "+$dataProperties+" = "+$dataProperties+" || Object.keys("+$data+"); for (var "+$idx+"=0; "+$idx+"<"+$dataProperties+".length; "+$idx+"++) { var "+$key+" = "+$dataProperties+"["+$idx+"]; "}else{out+=" for (var "+$key+" in "+$data+") { "}if($someProperties){out+=" var isAdditional"+$lvl+" = !(false ";if($schemaKeys.length){if($schemaKeys.length>8){out+=" || validate.schema"+$schemaPath+".hasOwnProperty("+$key+") "}else{var arr1=$schemaKeys;if(arr1){var $propertyKey,i1=-1,l1=arr1.length-1;while(i1<l1){$propertyKey=arr1[i1+=1];out+=" || "+$key+" == "+it.util.toQuotedString($propertyKey)+" "}}}}if($pPropertyKeys.length){var arr2=$pPropertyKeys;if(arr2){var $pProperty,$i=-1,l2=arr2.length-1;while($i<l2){$pProperty=arr2[$i+=1];out+=" || "+it.usePattern($pProperty)+".test("+$key+") "}}}out+=" ); if (isAdditional"+$lvl+") { "}if($removeAdditional=="all"){out+=" delete "+$data+"["+$key+"]; "}else{var $currentErrorPath=it.errorPath;var $additionalProperty="' + "+$key+" + '";if(it.opts._errorDataPathProperty){it.errorPath=it.util.getPathExpr(it.errorPath,$key,it.opts.jsonPointers)}if($noAdditional){if($removeAdditional){out+=" delete "+$data+"["+$key+"]; "}else{out+=" "+$nextValid+" = false; ";var $currErrSchemaPath=$errSchemaPath;$errSchemaPath=it.errSchemaPath+"/additionalProperties";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"additionalProperties"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { additionalProperty: '"+$additionalProperty+"' } ";if(it.opts.messages!==false){out+=" , message: '";if(it.opts._errorDataPathProperty){out+="is an invalid additional property"}else{out+="should NOT have additional properties"}out+="' "}if(it.opts.verbose){out+=" , schema: false , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}$errSchemaPath=$currErrSchemaPath;if($breakOnError){out+=" break; "}}}else if($additionalIsSchema){if($removeAdditional=="failing"){out+=" var "+$errs+" = errors; ";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;$it.schema=$aProperties;$it.schemaPath=it.schemaPath+".additionalProperties";$it.errSchemaPath=it.errSchemaPath+"/additionalProperties";$it.errorPath=it.opts._errorDataPathProperty?it.errorPath:it.util.getPathExpr(it.errorPath,$key,it.opts.jsonPointers);var $passData=$data+"["+$key+"]";$it.dataPathArr[$dataNxt]=$key;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}out+=" if (!"+$nextValid+") { errors = "+$errs+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+$data+"["+$key+"]; } ";it.compositeRule=$it.compositeRule=$wasComposite}else{$it.schema=$aProperties;$it.schemaPath=it.schemaPath+".additionalProperties";$it.errSchemaPath=it.errSchemaPath+"/additionalProperties";$it.errorPath=it.opts._errorDataPathProperty?it.errorPath:it.util.getPathExpr(it.errorPath,$key,it.opts.jsonPointers);var $passData=$data+"["+$key+"]";$it.dataPathArr[$dataNxt]=$key;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}if($breakOnError){out+=" if (!"+$nextValid+") break; "}}}it.errorPath=$currentErrorPath}if($someProperties){out+=" } "}out+=" } ";if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}var $useDefaults=it.opts.useDefaults&&!it.compositeRule;if($schemaKeys.length){var arr3=$schemaKeys;if(arr3){var $propertyKey,i3=-1,l3=arr3.length-1;while(i3<l3){$propertyKey=arr3[i3+=1];var $sch=$schema[$propertyKey];if(it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)){var $prop=it.util.getProperty($propertyKey),$passData=$data+$prop,$hasDefault=$useDefaults&&$sch.default!==undefined;$it.schema=$sch;$it.schemaPath=$schemaPath+$prop;$it.errSchemaPath=$errSchemaPath+"/"+it.util.escapeFragment($propertyKey);$it.errorPath=it.util.getPath(it.errorPath,$propertyKey,it.opts.jsonPointers);$it.dataPathArr[$dataNxt]=it.util.toQuotedString($propertyKey);var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){$code=it.util.varReplace($code,$nextData,$passData);var $useData=$passData}else{var $useData=$nextData;out+=" var "+$nextData+" = "+$passData+"; "}if($hasDefault){out+=" "+$code+" "}else{if($requiredHash&&$requiredHash[$propertyKey]){out+=" if ( "+$useData+" === undefined ";if($ownProperties){out+=" || ! Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($propertyKey)+"') "}out+=") { "+$nextValid+" = false; ";var $currentErrorPath=it.errorPath,$currErrSchemaPath=$errSchemaPath,$missingProperty=it.util.escapeQuotes($propertyKey);if(it.opts._errorDataPathProperty){it.errorPath=it.util.getPath($currentErrorPath,$propertyKey,it.opts.jsonPointers)}$errSchemaPath=it.errSchemaPath+"/required";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { missingProperty: '"+$missingProperty+"' } ";if(it.opts.messages!==false){out+=" , message: '";if(it.opts._errorDataPathProperty){out+="is a required property"}else{out+="should have required property \\'"+$missingProperty+"\\'"}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}$errSchemaPath=$currErrSchemaPath;it.errorPath=$currentErrorPath;out+=" } else { "}else{if($breakOnError){out+=" if ( "+$useData+" === undefined ";if($ownProperties){out+=" || ! Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($propertyKey)+"') "}out+=") { "+$nextValid+" = true; } else { "}else{out+=" if ("+$useData+" !== undefined ";if($ownProperties){out+=" && Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($propertyKey)+"') "}out+=" ) { "}}out+=" "+$code+" } "}}if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}}}if($pPropertyKeys.length){var arr4=$pPropertyKeys;if(arr4){var $pProperty,i4=-1,l4=arr4.length-1;while(i4<l4){$pProperty=arr4[i4+=1];var $sch=$pProperties[$pProperty];if(it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)){$it.schema=$sch;$it.schemaPath=it.schemaPath+".patternProperties"+it.util.getProperty($pProperty);$it.errSchemaPath=it.errSchemaPath+"/patternProperties/"+it.util.escapeFragment($pProperty);if($ownProperties){out+=" "+$dataProperties+" = "+$dataProperties+" || Object.keys("+$data+"); for (var "+$idx+"=0; "+$idx+"<"+$dataProperties+".length; "+$idx+"++) { var "+$key+" = "+$dataProperties+"["+$idx+"]; "}else{out+=" for (var "+$key+" in "+$data+") { "}out+=" if ("+it.usePattern($pProperty)+".test("+$key+")) { ";$it.errorPath=it.util.getPathExpr(it.errorPath,$key,it.opts.jsonPointers);var $passData=$data+"["+$key+"]";$it.dataPathArr[$dataNxt]=$key;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}if($breakOnError){out+=" if (!"+$nextValid+") break; "}out+=" } ";if($breakOnError){out+=" else "+$nextValid+" = true; "}out+=" } ";if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}}}}if($breakOnError){out+=" "+$closingBraces+" if ("+$errs+" == errors) {"}return out}},{}],372:[function(require,module,exports){"use strict";module.exports=function generate_propertyNames(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;out+="var "+$errs+" = errors;";if(it.opts.strictKeywords?typeof $schema=="object"&&Object.keys($schema).length>0||$schema===false:it.util.schemaHasRules($schema,it.RULES.all)){$it.schema=$schema;$it.schemaPath=$schemaPath;$it.errSchemaPath=$errSchemaPath;var $key="key"+$lvl,$idx="idx"+$lvl,$i="i"+$lvl,$invalidName="' + "+$key+" + '",$dataNxt=$it.dataLevel=it.dataLevel+1,$nextData="data"+$dataNxt,$dataProperties="dataProperties"+$lvl,$ownProperties=it.opts.ownProperties,$currentBaseId=it.baseId;if($ownProperties){out+=" var "+$dataProperties+" = undefined; "}if($ownProperties){out+=" "+$dataProperties+" = "+$dataProperties+" || Object.keys("+$data+"); for (var "+$idx+"=0; "+$idx+"<"+$dataProperties+".length; "+$idx+"++) { var "+$key+" = "+$dataProperties+"["+$idx+"]; "}else{out+=" for (var "+$key+" in "+$data+") { "}out+=" var startErrs"+$lvl+" = errors; ";var $passData=$key;var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}it.compositeRule=$it.compositeRule=$wasComposite;out+=" if (!"+$nextValid+") { for (var "+$i+"=startErrs"+$lvl+"; "+$i+"<errors; "+$i+"++) { vErrors["+$i+"].propertyName = "+$key+"; } var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"propertyNames"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { propertyName: '"+$invalidName+"' } ";if(it.opts.messages!==false){out+=" , message: 'property name \\'"+$invalidName+"\\' is invalid' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(vErrors); "}else{out+=" validate.errors = vErrors; return false; "}}if($breakOnError){out+=" break; "}out+=" } }"}if($breakOnError){
37
- out+=" "+$closingBraces+" if ("+$errs+" == errors) {"}return out}},{}],373:[function(require,module,exports){"use strict";module.exports=function generate_ref(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $async,$refCode;if($schema=="#"||$schema=="#/"){if(it.isRoot){$async=it.async;$refCode="validate"}else{$async=it.root.schema.$async===true;$refCode="root.refVal[0]"}}else{var $refVal=it.resolveRef(it.baseId,$schema,it.isRoot);if($refVal===undefined){var $message=it.MissingRefError.message(it.baseId,$schema);if(it.opts.missingRefs=="fail"){it.logger.error($message);var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"$ref"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { ref: '"+it.util.escapeQuotes($schema)+"' } ";if(it.opts.messages!==false){out+=" , message: 'can\\'t resolve reference "+it.util.escapeQuotes($schema)+"' "}if(it.opts.verbose){out+=" , schema: "+it.util.toQuotedString($schema)+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}if($breakOnError){out+=" if (false) { "}}else if(it.opts.missingRefs=="ignore"){it.logger.warn($message);if($breakOnError){out+=" if (true) { "}}else{throw new it.MissingRefError(it.baseId,$schema,$message)}}else if($refVal.inline){var $it=it.util.copy(it);$it.level++;var $nextValid="valid"+$it.level;$it.schema=$refVal.schema;$it.schemaPath="";$it.errSchemaPath=$schema;var $code=it.validate($it).replace(/validate\.schema/g,$refVal.code);out+=" "+$code+" ";if($breakOnError){out+=" if ("+$nextValid+") { "}}else{$async=$refVal.$async===true||it.async&&$refVal.$async!==false;$refCode=$refVal.code}}if($refCode){var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.opts.passContext){out+=" "+$refCode+".call(this, "}else{out+=" "+$refCode+"( "}out+=" "+$data+", (dataPath || '')";if(it.errorPath!='""'){out+=" + "+it.errorPath}var $parentData=$dataLvl?"data"+($dataLvl-1||""):"parentData",$parentDataProperty=$dataLvl?it.dataPathArr[$dataLvl]:"parentDataProperty";out+=" , "+$parentData+" , "+$parentDataProperty+", rootData) ";var __callValidate=out;out=$$outStack.pop();if($async){if(!it.async)throw new Error("async schema referenced by sync schema");if($breakOnError){out+=" var "+$valid+"; "}out+=" try { await "+__callValidate+"; ";if($breakOnError){out+=" "+$valid+" = true; "}out+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ";if($breakOnError){out+=" "+$valid+" = false; "}out+=" } ";if($breakOnError){out+=" if ("+$valid+") { "}}else{out+=" if (!"+__callValidate+") { if (vErrors === null) vErrors = "+$refCode+".errors; else vErrors = vErrors.concat("+$refCode+".errors); errors = vErrors.length; } ";if($breakOnError){out+=" else { "}}}return out}},{}],374:[function(require,module,exports){"use strict";module.exports=function generate_required(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $vSchema="schema"+$lvl;if(!$isData){if($schema.length<it.opts.loopRequired&&it.schema.properties&&Object.keys(it.schema.properties).length){var $required=[];var arr1=$schema;if(arr1){var $property,i1=-1,l1=arr1.length-1;while(i1<l1){$property=arr1[i1+=1];var $propertySch=it.schema.properties[$property];if(!($propertySch&&(it.opts.strictKeywords?typeof $propertySch=="object"&&Object.keys($propertySch).length>0||$propertySch===false:it.util.schemaHasRules($propertySch,it.RULES.all)))){$required[$required.length]=$property}}}}else{var $required=$schema}}if($isData||$required.length){var $currentErrorPath=it.errorPath,$loopRequired=$isData||$required.length>=it.opts.loopRequired,$ownProperties=it.opts.ownProperties;if($breakOnError){out+=" var missing"+$lvl+"; ";if($loopRequired){if(!$isData){out+=" var "+$vSchema+" = validate.schema"+$schemaPath+"; "}var $i="i"+$lvl,$propertyPath="schema"+$lvl+"["+$i+"]",$missingProperty="' + "+$propertyPath+" + '";if(it.opts._errorDataPathProperty){it.errorPath=it.util.getPathExpr($currentErrorPath,$propertyPath,it.opts.jsonPointers)}out+=" var "+$valid+" = true; ";if($isData){out+=" if (schema"+$lvl+" === undefined) "+$valid+" = true; else if (!Array.isArray(schema"+$lvl+")) "+$valid+" = false; else {"}out+=" for (var "+$i+" = 0; "+$i+" < "+$vSchema+".length; "+$i+"++) { "+$valid+" = "+$data+"["+$vSchema+"["+$i+"]] !== undefined ";if($ownProperties){out+=" && Object.prototype.hasOwnProperty.call("+$data+", "+$vSchema+"["+$i+"]) "}out+="; if (!"+$valid+") break; } ";if($isData){out+=" } "}out+=" if (!"+$valid+") { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { missingProperty: '"+$missingProperty+"' } ";if(it.opts.messages!==false){out+=" , message: '";if(it.opts._errorDataPathProperty){out+="is a required property"}else{out+="should have required property \\'"+$missingProperty+"\\'"}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } else { "}else{out+=" if ( ";var arr2=$required;if(arr2){var $propertyKey,$i=-1,l2=arr2.length-1;while($i<l2){$propertyKey=arr2[$i+=1];if($i){out+=" || "}var $prop=it.util.getProperty($propertyKey),$useData=$data+$prop;out+=" ( ( "+$useData+" === undefined ";if($ownProperties){out+=" || ! Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($propertyKey)+"') "}out+=") && (missing"+$lvl+" = "+it.util.toQuotedString(it.opts.jsonPointers?$propertyKey:$prop)+") ) "}}out+=") { ";var $propertyPath="missing"+$lvl,$missingProperty="' + "+$propertyPath+" + '";if(it.opts._errorDataPathProperty){it.errorPath=it.opts.jsonPointers?it.util.getPathExpr($currentErrorPath,$propertyPath,true):$currentErrorPath+" + "+$propertyPath}var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { missingProperty: '"+$missingProperty+"' } ";if(it.opts.messages!==false){out+=" , message: '";if(it.opts._errorDataPathProperty){out+="is a required property"}else{out+="should have required property \\'"+$missingProperty+"\\'"}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } else { "}}else{if($loopRequired){if(!$isData){out+=" var "+$vSchema+" = validate.schema"+$schemaPath+"; "}var $i="i"+$lvl,$propertyPath="schema"+$lvl+"["+$i+"]",$missingProperty="' + "+$propertyPath+" + '";if(it.opts._errorDataPathProperty){it.errorPath=it.util.getPathExpr($currentErrorPath,$propertyPath,it.opts.jsonPointers)}if($isData){out+=" if ("+$vSchema+" && !Array.isArray("+$vSchema+")) { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { missingProperty: '"+$missingProperty+"' } ";if(it.opts.messages!==false){out+=" , message: '";if(it.opts._errorDataPathProperty){out+="is a required property"}else{out+="should have required property \\'"+$missingProperty+"\\'"}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+$vSchema+" !== undefined) { "}out+=" for (var "+$i+" = 0; "+$i+" < "+$vSchema+".length; "+$i+"++) { if ("+$data+"["+$vSchema+"["+$i+"]] === undefined ";if($ownProperties){out+=" || ! Object.prototype.hasOwnProperty.call("+$data+", "+$vSchema+"["+$i+"]) "}out+=") { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { missingProperty: '"+$missingProperty+"' } ";if(it.opts.messages!==false){out+=" , message: '";if(it.opts._errorDataPathProperty){out+="is a required property"}else{out+="should have required property \\'"+$missingProperty+"\\'"}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ";if($isData){out+=" } "}}else{var arr3=$required;if(arr3){var $propertyKey,i3=-1,l3=arr3.length-1;while(i3<l3){$propertyKey=arr3[i3+=1];var $prop=it.util.getProperty($propertyKey),$missingProperty=it.util.escapeQuotes($propertyKey),$useData=$data+$prop;if(it.opts._errorDataPathProperty){it.errorPath=it.util.getPath($currentErrorPath,$propertyKey,it.opts.jsonPointers)}out+=" if ( "+$useData+" === undefined ";if($ownProperties){out+=" || ! Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($propertyKey)+"') "}out+=") { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { missingProperty: '"+$missingProperty+"' } ";if(it.opts.messages!==false){out+=" , message: '";if(it.opts._errorDataPathProperty){out+="is a required property"}else{out+="should have required property \\'"+$missingProperty+"\\'"}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}}}it.errorPath=$currentErrorPath}else if($breakOnError){out+=" if (true) {"}return out}},{}],375:[function(require,module,exports){"use strict";module.exports=function generate_uniqueItems(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(($schema||$isData)&&it.opts.uniqueItems!==false){if($isData){out+=" var "+$valid+"; if ("+$schemaValue+" === false || "+$schemaValue+" === undefined) "+$valid+" = true; else if (typeof "+$schemaValue+" != 'boolean') "+$valid+" = false; else { "}out+=" var i = "+$data+".length , "+$valid+" = true , j; if (i > 1) { ";var $itemType=it.schema.items&&it.schema.items.type,$typeIsArray=Array.isArray($itemType);if(!$itemType||$itemType=="object"||$itemType=="array"||$typeIsArray&&($itemType.indexOf("object")>=0||$itemType.indexOf("array")>=0)){out+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+$data+"[i], "+$data+"[j])) { "+$valid+" = false; break outer; } } } "}else{out+=" var itemIndices = {}, item; for (;i--;) { var item = "+$data+"[i]; ";var $method="checkDataType"+($typeIsArray?"s":"");out+=" if ("+it.util[$method]($itemType,"item",it.opts.strictNumbers,true)+") continue; ";if($typeIsArray){out+=" if (typeof item == 'string') item = '\"' + item; "}out+=" if (typeof itemIndices[item] == 'number') { "+$valid+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}out+=" } ";if($isData){out+=" } "}out+=" if (!"+$valid+") { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"uniqueItems"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { i: i, j: j } ";if(it.opts.messages!==false){out+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } ";if($breakOnError){out+=" else { "}}else{if($breakOnError){out+=" if (true) { "}}return out}},{}],376:[function(require,module,exports){"use strict";module.exports=function generate_validate(it,$keyword,$ruleType){var out="";var $async=it.schema.$async===true,$refKeywords=it.util.schemaHasRulesExcept(it.schema,it.RULES.all,"$ref"),$id=it.self._getId(it.schema);if(it.opts.strictKeywords){var $unknownKwd=it.util.schemaUnknownRules(it.schema,it.RULES.keywords);if($unknownKwd){var $keywordsMsg="unknown keyword: "+$unknownKwd;if(it.opts.strictKeywords==="log")it.logger.warn($keywordsMsg);else throw new Error($keywordsMsg)}}if(it.isTop){out+=" var validate = ";if($async){it.async=true;out+="async "}out+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ";if($id&&(it.opts.sourceCode||it.opts.processCode)){out+=" "+("/*# sourceURL="+$id+" */")+" "}}if(typeof it.schema=="boolean"||!($refKeywords||it.schema.$ref)){var $keyword="false schema";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;if(it.schema===false){if(it.isTop){$breakOnError=true}else{out+=" var "+$valid+" = false; "}var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"false schema")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: 'boolean schema is false' "}if(it.opts.verbose){out+=" , schema: false , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}}else{if(it.isTop){if($async){out+=" return data; "}else{out+=" validate.errors = null; return true; "}}else{out+=" var "+$valid+" = true; "}}if(it.isTop){out+=" }; return validate; "}return out}if(it.isTop){var $top=it.isTop,$lvl=it.level=0,$dataLvl=it.dataLevel=0,$data="data";it.rootId=it.resolve.fullPath(it.self._getId(it.root.schema));it.baseId=it.baseId||it.rootId;delete it.isTop;it.dataPathArr=[""];if(it.schema.default!==undefined&&it.opts.useDefaults&&it.opts.strictDefaults){var $defaultMsg="default is ignored in the schema root";if(it.opts.strictDefaults==="log")it.logger.warn($defaultMsg);else throw new Error($defaultMsg)}out+=" var vErrors = null; ";out+=" var errors = 0; ";out+=" if (rootData === undefined) rootData = data; "}else{var $lvl=it.level,$dataLvl=it.dataLevel,$data="data"+($dataLvl||"");if($id)it.baseId=it.resolve.url(it.baseId,$id);if($async&&!it.async)throw new Error("async schema in sync schema");out+=" var errs_"+$lvl+" = errors;"}var $valid="valid"+$lvl,$breakOnError=!it.opts.allErrors,$closingBraces1="",$closingBraces2="";var $errorKeyword;var $typeSchema=it.schema.type,$typeIsArray=Array.isArray($typeSchema);if($typeSchema&&it.opts.nullable&&it.schema.nullable===true){if($typeIsArray){if($typeSchema.indexOf("null")==-1)$typeSchema=$typeSchema.concat("null")}else if($typeSchema!="null"){$typeSchema=[$typeSchema,"null"];$typeIsArray=true}}if($typeIsArray&&$typeSchema.length==1){$typeSchema=$typeSchema[0];$typeIsArray=false}if(it.schema.$ref&&$refKeywords){if(it.opts.extendRefs=="fail"){throw new Error('$ref: validation keywords used in schema at path "'+it.errSchemaPath+'" (see option extendRefs)')}else if(it.opts.extendRefs!==true){$refKeywords=false;it.logger.warn('$ref: keywords ignored in schema at path "'+it.errSchemaPath+'"')}}if(it.schema.$comment&&it.opts.$comment){out+=" "+it.RULES.all.$comment.code(it,"$comment")}if($typeSchema){if(it.opts.coerceTypes){var $coerceToTypes=it.util.coerceToTypes(it.opts.coerceTypes,$typeSchema)}var $rulesGroup=it.RULES.types[$typeSchema];if($coerceToTypes||$typeIsArray||$rulesGroup===true||$rulesGroup&&!$shouldUseGroup($rulesGroup)){var $schemaPath=it.schemaPath+".type",$errSchemaPath=it.errSchemaPath+"/type";var $schemaPath=it.schemaPath+".type",$errSchemaPath=it.errSchemaPath+"/type",$method=$typeIsArray?"checkDataTypes":"checkDataType";out+=" if ("+it.util[$method]($typeSchema,$data,it.opts.strictNumbers,true)+") { ";if($coerceToTypes){var $dataType="dataType"+$lvl,$coerced="coerced"+$lvl;out+=" var "+$dataType+" = typeof "+$data+"; var "+$coerced+" = undefined; ";if(it.opts.coerceTypes=="array"){out+=" if ("+$dataType+" == 'object' && Array.isArray("+$data+") && "+$data+".length == 1) { "+$data+" = "+$data+"[0]; "+$dataType+" = typeof "+$data+"; if ("+it.util.checkDataType(it.schema.type,$data,it.opts.strictNumbers)+") "+$coerced+" = "+$data+"; } "}out+=" if ("+$coerced+" !== undefined) ; ";var arr1=$coerceToTypes;if(arr1){var $type,$i=-1,l1=arr1.length-1;while($i<l1){$type=arr1[$i+=1];if($type=="string"){out+=" else if ("+$dataType+" == 'number' || "+$dataType+" == 'boolean') "+$coerced+" = '' + "+$data+"; else if ("+$data+" === null) "+$coerced+" = ''; "}else if($type=="number"||$type=="integer"){out+=" else if ("+$dataType+" == 'boolean' || "+$data+" === null || ("+$dataType+" == 'string' && "+$data+" && "+$data+" == +"+$data+" ";if($type=="integer"){out+=" && !("+$data+" % 1)"}out+=")) "+$coerced+" = +"+$data+"; "}else if($type=="boolean"){out+=" else if ("+$data+" === 'false' || "+$data+" === 0 || "+$data+" === null) "+$coerced+" = false; else if ("+$data+" === 'true' || "+$data+" === 1) "+$coerced+" = true; "}else if($type=="null"){out+=" else if ("+$data+" === '' || "+$data+" === 0 || "+$data+" === false) "+$coerced+" = null; "}else if(it.opts.coerceTypes=="array"&&$type=="array"){out+=" else if ("+$dataType+" == 'string' || "+$dataType+" == 'number' || "+$dataType+" == 'boolean' || "+$data+" == null) "+$coerced+" = ["+$data+"]; "}}}out+=" else { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"type")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { type: '";if($typeIsArray){out+=""+$typeSchema.join(",")}else{out+=""+$typeSchema}out+="' } ";if(it.opts.messages!==false){out+=" , message: 'should be ";if($typeIsArray){out+=""+$typeSchema.join(",")}else{out+=""+$typeSchema}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } if ("+$coerced+" !== undefined) { ";var $parentData=$dataLvl?"data"+($dataLvl-1||""):"parentData",$parentDataProperty=$dataLvl?it.dataPathArr[$dataLvl]:"parentDataProperty";out+=" "+$data+" = "+$coerced+"; ";if(!$dataLvl){out+="if ("+$parentData+" !== undefined)"}out+=" "+$parentData+"["+$parentDataProperty+"] = "+$coerced+"; } "}else{var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"type")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { type: '";if($typeIsArray){out+=""+$typeSchema.join(",")}else{out+=""+$typeSchema}out+="' } ";if(it.opts.messages!==false){out+=" , message: 'should be ";if($typeIsArray){out+=""+$typeSchema.join(",")}else{out+=""+$typeSchema}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}}out+=" } "}}if(it.schema.$ref&&!$refKeywords){out+=" "+it.RULES.all.$ref.code(it,"$ref")+" ";if($breakOnError){out+=" } if (errors === ";if($top){out+="0"}else{out+="errs_"+$lvl}out+=") { ";$closingBraces2+="}"}}else{var arr2=it.RULES;if(arr2){var $rulesGroup,i2=-1,l2=arr2.length-1;while(i2<l2){$rulesGroup=arr2[i2+=1];if($shouldUseGroup($rulesGroup)){if($rulesGroup.type){out+=" if ("+it.util.checkDataType($rulesGroup.type,$data,it.opts.strictNumbers)+") { "}if(it.opts.useDefaults){if($rulesGroup.type=="object"&&it.schema.properties){var $schema=it.schema.properties,$schemaKeys=Object.keys($schema);var arr3=$schemaKeys;if(arr3){var $propertyKey,i3=-1,l3=arr3.length-1;while(i3<l3){$propertyKey=arr3[i3+=1];var $sch=$schema[$propertyKey];if($sch.default!==undefined){var $passData=$data+it.util.getProperty($propertyKey);if(it.compositeRule){if(it.opts.strictDefaults){var $defaultMsg="default is ignored for: "+$passData;if(it.opts.strictDefaults==="log")it.logger.warn($defaultMsg);else throw new Error($defaultMsg)}}else{out+=" if ("+$passData+" === undefined ";if(it.opts.useDefaults=="empty"){out+=" || "+$passData+" === null || "+$passData+" === '' "}out+=" ) "+$passData+" = ";if(it.opts.useDefaults=="shared"){out+=" "+it.useDefault($sch.default)+" "}else{out+=" "+JSON.stringify($sch.default)+" "}out+="; "}}}}}else if($rulesGroup.type=="array"&&Array.isArray(it.schema.items)){var arr4=it.schema.items;if(arr4){var $sch,$i=-1,l4=arr4.length-1;while($i<l4){$sch=arr4[$i+=1];if($sch.default!==undefined){var $passData=$data+"["+$i+"]";if(it.compositeRule){if(it.opts.strictDefaults){var $defaultMsg="default is ignored for: "+$passData;if(it.opts.strictDefaults==="log")it.logger.warn($defaultMsg);else throw new Error($defaultMsg)}}else{out+=" if ("+$passData+" === undefined ";if(it.opts.useDefaults=="empty"){out+=" || "+$passData+" === null || "+$passData+" === '' "}out+=" ) "+$passData+" = ";if(it.opts.useDefaults=="shared"){out+=" "+it.useDefault($sch.default)+" "}else{out+=" "+JSON.stringify($sch.default)+" "}out+="; "}}}}}}var arr5=$rulesGroup.rules;if(arr5){var $rule,i5=-1,l5=arr5.length-1;while(i5<l5){$rule=arr5[i5+=1];if($shouldUseRule($rule)){var $code=$rule.code(it,$rule.keyword,$rulesGroup.type);if($code){out+=" "+$code+" ";if($breakOnError){$closingBraces1+="}"}}}}}if($breakOnError){out+=" "+$closingBraces1+" ";$closingBraces1=""}if($rulesGroup.type){out+=" } ";if($typeSchema&&$typeSchema===$rulesGroup.type&&!$coerceToTypes){out+=" else { ";var $schemaPath=it.schemaPath+".type",$errSchemaPath=it.errSchemaPath+"/type";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"type")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { type: '";if($typeIsArray){out+=""+$typeSchema.join(",")}else{out+=""+$typeSchema}out+="' } ";if(it.opts.messages!==false){out+=" , message: 'should be ";if($typeIsArray){out+=""+$typeSchema.join(",")}else{out+=""+$typeSchema}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } "}}if($breakOnError){out+=" if (errors === ";if($top){out+="0"}else{out+="errs_"+$lvl}out+=") { ";$closingBraces2+="}"}}}}}if($breakOnError){out+=" "+$closingBraces2+" "}if($top){if($async){out+=" if (errors === 0) return data; ";out+=" else throw new ValidationError(vErrors); "}else{out+=" validate.errors = vErrors; ";out+=" return errors === 0; "}out+=" }; return validate;"}else{out+=" var "+$valid+" = errors === errs_"+$lvl+";"}function $shouldUseGroup($rulesGroup){var rules=$rulesGroup.rules;for(var i=0;i<rules.length;i++)if($shouldUseRule(rules[i]))return true}function $shouldUseRule($rule){return it.schema[$rule.keyword]!==undefined||$rule.implements&&$ruleImplementsSomeKeyword($rule)}function $ruleImplementsSomeKeyword($rule){var impl=$rule.implements;for(var i=0;i<impl.length;i++)if(it.schema[impl[i]]!==undefined)return true}return out}},{}],377:[function(require,module,exports){"use strict";var IDENTIFIER=/^[a-z_$][a-z0-9_$-]*$/i;var customRuleCode=require("./dotjs/custom");var definitionSchema=require("./definition_schema");module.exports={add:addKeyword,get:getKeyword,remove:removeKeyword,validate:validateKeyword};function addKeyword(keyword,definition){var RULES=this.RULES;if(RULES.keywords[keyword])throw new Error("Keyword "+keyword+" is already defined");if(!IDENTIFIER.test(keyword))throw new Error("Keyword "+keyword+" is not a valid identifier");if(definition){this.validateKeyword(definition,true);var dataType=definition.type;if(Array.isArray(dataType)){for(var i=0;i<dataType.length;i++)_addRule(keyword,dataType[i],definition)}else{_addRule(keyword,dataType,definition)}var metaSchema=definition.metaSchema;if(metaSchema){if(definition.$data&&this._opts.$data){metaSchema={anyOf:[metaSchema,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}}definition.validateSchema=this.compile(metaSchema,true)}}RULES.keywords[keyword]=RULES.all[keyword]=true;function _addRule(keyword,dataType,definition){var ruleGroup;for(var i=0;i<RULES.length;i++){var rg=RULES[i];if(rg.type==dataType){ruleGroup=rg;break}}if(!ruleGroup){ruleGroup={type:dataType,rules:[]};RULES.push(ruleGroup)}var rule={keyword:keyword,definition:definition,custom:true,code:customRuleCode,implements:definition.implements};ruleGroup.rules.push(rule);RULES.custom[keyword]=rule}return this}function getKeyword(keyword){var rule=this.RULES.custom[keyword];return rule?rule.definition:this.RULES.keywords[keyword]||false}function removeKeyword(keyword){var RULES=this.RULES;delete RULES.keywords[keyword];delete RULES.all[keyword];delete RULES.custom[keyword];for(var i=0;i<RULES.length;i++){var rules=RULES[i].rules;for(var j=0;j<rules.length;j++){if(rules[j].keyword==keyword){rules.splice(j,1);break}}}return this}function validateKeyword(definition,throwError){validateKeyword.errors=null;var v=this._validateKeyword=this._validateKeyword||this.compile(definitionSchema,true);if(v(definition))return true;validateKeyword.errors=v.errors;if(throwError)throw new Error("custom keyword definition is invalid: "+this.errorsText(v.errors));else return false}},{"./definition_schema":350,"./dotjs/custom":360}],378:[function(require,module,exports){module.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:false}},{}],379:[function(require,module,exports){module.exports={$schema:"http://json-schema.org/draft-06/schema#",$id:"http://json-schema.org/draft-06/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},title:{type:"string"},description:{type:"string"},default:{},examples:{type:"array",items:{}},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:{}},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:{},enum:{type:"array",minItems:1,uniqueItems:true},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{
38
- $ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:true}]},format:{type:"string"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:{}}},{}],380:[function(require,module,exports){module.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:true,readOnly:{type:"boolean",default:false},examples:{type:"array",items:true},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:true},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:true,enum:{type:"array",items:true,minItems:1,uniqueItems:true},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:true}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:true}},{}],381:[function(require,module,exports){module.exports={newInvalidAsn1Error:function(msg){var e=new Error;e.name="InvalidAsn1Error";e.message=msg||"";return e}}},{}],382:[function(require,module,exports){var errors=require("./errors");var types=require("./types");var Reader=require("./reader");var Writer=require("./writer");module.exports={Reader:Reader,Writer:Writer};for(var t in types){if(types.hasOwnProperty(t))module.exports[t]=types[t]}for(var e in errors){if(errors.hasOwnProperty(e))module.exports[e]=errors[e]}},{"./errors":381,"./reader":383,"./types":384,"./writer":385}],383:[function(require,module,exports){var assert=require("assert");var Buffer=require("safer-buffer").Buffer;var ASN1=require("./types");var errors=require("./errors");var newInvalidAsn1Error=errors.newInvalidAsn1Error;function Reader(data){if(!data||!Buffer.isBuffer(data))throw new TypeError("data must be a node Buffer");this._buf=data;this._size=data.length;this._len=0;this._offset=0}Object.defineProperty(Reader.prototype,"length",{enumerable:true,get:function(){return this._len}});Object.defineProperty(Reader.prototype,"offset",{enumerable:true,get:function(){return this._offset}});Object.defineProperty(Reader.prototype,"remain",{get:function(){return this._size-this._offset}});Object.defineProperty(Reader.prototype,"buffer",{get:function(){return this._buf.slice(this._offset)}});Reader.prototype.readByte=function(peek){if(this._size-this._offset<1)return null;var b=this._buf[this._offset]&255;if(!peek)this._offset+=1;return b};Reader.prototype.peek=function(){return this.readByte(true)};Reader.prototype.readLength=function(offset){if(offset===undefined)offset=this._offset;if(offset>=this._size)return null;var lenB=this._buf[offset++]&255;if(lenB===null)return null;if((lenB&128)===128){lenB&=127;if(lenB===0)throw newInvalidAsn1Error("Indefinite length not supported");if(lenB>4)throw newInvalidAsn1Error("encoding too long");if(this._size-offset<lenB)return null;this._len=0;for(var i=0;i<lenB;i++)this._len=(this._len<<8)+(this._buf[offset++]&255)}else{this._len=lenB}return offset};Reader.prototype.readSequence=function(tag){var seq=this.peek();if(seq===null)return null;if(tag!==undefined&&tag!==seq)throw newInvalidAsn1Error("Expected 0x"+tag.toString(16)+": got 0x"+seq.toString(16));var o=this.readLength(this._offset+1);if(o===null)return null;this._offset=o;return seq};Reader.prototype.readInt=function(){return this._readTag(ASN1.Integer)};Reader.prototype.readBoolean=function(){return this._readTag(ASN1.Boolean)===0?false:true};Reader.prototype.readEnumeration=function(){return this._readTag(ASN1.Enumeration)};Reader.prototype.readString=function(tag,retbuf){if(!tag)tag=ASN1.OctetString;var b=this.peek();if(b===null)return null;if(b!==tag)throw newInvalidAsn1Error("Expected 0x"+tag.toString(16)+": got 0x"+b.toString(16));var o=this.readLength(this._offset+1);if(o===null)return null;if(this.length>this._size-o)return null;this._offset=o;if(this.length===0)return retbuf?Buffer.alloc(0):"";var str=this._buf.slice(this._offset,this._offset+this.length);this._offset+=this.length;return retbuf?str:str.toString("utf8")};Reader.prototype.readOID=function(tag){if(!tag)tag=ASN1.OID;var b=this.readString(tag,true);if(b===null)return null;var values=[];var value=0;for(var i=0;i<b.length;i++){var byte=b[i]&255;value<<=7;value+=byte&127;if((byte&128)===0){values.push(value);value=0}}value=values.shift();values.unshift(value%40);values.unshift(value/40>>0);return values.join(".")};Reader.prototype._readTag=function(tag){assert.ok(tag!==undefined);var b=this.peek();if(b===null)return null;if(b!==tag)throw newInvalidAsn1Error("Expected 0x"+tag.toString(16)+": got 0x"+b.toString(16));var o=this.readLength(this._offset+1);if(o===null)return null;if(this.length>4)throw newInvalidAsn1Error("Integer too long: "+this.length);if(this.length>this._size-o)return null;this._offset=o;var fb=this._buf[this._offset];var value=0;for(var i=0;i<this.length;i++){value<<=8;value|=this._buf[this._offset++]&255}if((fb&128)===128&&i!==4)value-=1<<i*8;return value>>0};module.exports=Reader},{"./errors":381,"./types":384,assert:16,"safer-buffer":470}],384:[function(require,module,exports){module.exports={EOC:0,Boolean:1,Integer:2,BitString:3,OctetString:4,Null:5,OID:6,ObjectDescriptor:7,External:8,Real:9,Enumeration:10,PDV:11,Utf8String:12,RelativeOID:13,Sequence:16,Set:17,NumericString:18,PrintableString:19,T61String:20,VideotexString:21,IA5String:22,UTCTime:23,GeneralizedTime:24,GraphicString:25,VisibleString:26,GeneralString:28,UniversalString:29,CharacterString:30,BMPString:31,Constructor:32,Context:128}},{}],385:[function(require,module,exports){var assert=require("assert");var Buffer=require("safer-buffer").Buffer;var ASN1=require("./types");var errors=require("./errors");var newInvalidAsn1Error=errors.newInvalidAsn1Error;var DEFAULT_OPTS={size:1024,growthFactor:8};function merge(from,to){assert.ok(from);assert.equal(typeof from,"object");assert.ok(to);assert.equal(typeof to,"object");var keys=Object.getOwnPropertyNames(from);keys.forEach(function(key){if(to[key])return;var value=Object.getOwnPropertyDescriptor(from,key);Object.defineProperty(to,key,value)});return to}function Writer(options){options=merge(DEFAULT_OPTS,options||{});this._buf=Buffer.alloc(options.size||1024);this._size=this._buf.length;this._offset=0;this._options=options;this._seq=[]}Object.defineProperty(Writer.prototype,"buffer",{get:function(){if(this._seq.length)throw newInvalidAsn1Error(this._seq.length+" unended sequence(s)");return this._buf.slice(0,this._offset)}});Writer.prototype.writeByte=function(b){if(typeof b!=="number")throw new TypeError("argument must be a Number");this._ensure(1);this._buf[this._offset++]=b};Writer.prototype.writeInt=function(i,tag){if(typeof i!=="number")throw new TypeError("argument must be a Number");if(typeof tag!=="number")tag=ASN1.Integer;var sz=4;while(((i&4286578688)===0||(i&4286578688)===4286578688>>0)&&sz>1){sz--;i<<=8}if(sz>4)throw newInvalidAsn1Error("BER ints cannot be > 0xffffffff");this._ensure(2+sz);this._buf[this._offset++]=tag;this._buf[this._offset++]=sz;while(sz-- >0){this._buf[this._offset++]=(i&4278190080)>>>24;i<<=8}};Writer.prototype.writeNull=function(){this.writeByte(ASN1.Null);this.writeByte(0)};Writer.prototype.writeEnumeration=function(i,tag){if(typeof i!=="number")throw new TypeError("argument must be a Number");if(typeof tag!=="number")tag=ASN1.Enumeration;return this.writeInt(i,tag)};Writer.prototype.writeBoolean=function(b,tag){if(typeof b!=="boolean")throw new TypeError("argument must be a Boolean");if(typeof tag!=="number")tag=ASN1.Boolean;this._ensure(3);this._buf[this._offset++]=tag;this._buf[this._offset++]=1;this._buf[this._offset++]=b?255:0};Writer.prototype.writeString=function(s,tag){if(typeof s!=="string")throw new TypeError("argument must be a string (was: "+typeof s+")");if(typeof tag!=="number")tag=ASN1.OctetString;var len=Buffer.byteLength(s);this.writeByte(tag);this.writeLength(len);if(len){this._ensure(len);this._buf.write(s,this._offset);this._offset+=len}};Writer.prototype.writeBuffer=function(buf,tag){if(typeof tag!=="number")throw new TypeError("tag must be a number");if(!Buffer.isBuffer(buf))throw new TypeError("argument must be a buffer");this.writeByte(tag);this.writeLength(buf.length);this._ensure(buf.length);buf.copy(this._buf,this._offset,0,buf.length);this._offset+=buf.length};Writer.prototype.writeStringArray=function(strings){if(!strings instanceof Array)throw new TypeError("argument must be an Array[String]");var self=this;strings.forEach(function(s){self.writeString(s)})};Writer.prototype.writeOID=function(s,tag){if(typeof s!=="string")throw new TypeError("argument must be a string");if(typeof tag!=="number")tag=ASN1.OID;if(!/^([0-9]+\.){3,}[0-9]+$/.test(s))throw new Error("argument is not a valid OID string");function encodeOctet(bytes,octet){if(octet<128){bytes.push(octet)}else if(octet<16384){bytes.push(octet>>>7|128);bytes.push(octet&127)}else if(octet<2097152){bytes.push(octet>>>14|128);bytes.push((octet>>>7|128)&255);bytes.push(octet&127)}else if(octet<268435456){bytes.push(octet>>>21|128);bytes.push((octet>>>14|128)&255);bytes.push((octet>>>7|128)&255);bytes.push(octet&127)}else{bytes.push((octet>>>28|128)&255);bytes.push((octet>>>21|128)&255);bytes.push((octet>>>14|128)&255);bytes.push((octet>>>7|128)&255);bytes.push(octet&127)}}var tmp=s.split(".");var bytes=[];bytes.push(parseInt(tmp[0],10)*40+parseInt(tmp[1],10));tmp.slice(2).forEach(function(b){encodeOctet(bytes,parseInt(b,10))});var self=this;this._ensure(2+bytes.length);this.writeByte(tag);this.writeLength(bytes.length);bytes.forEach(function(b){self.writeByte(b)})};Writer.prototype.writeLength=function(len){if(typeof len!=="number")throw new TypeError("argument must be a Number");this._ensure(4);if(len<=127){this._buf[this._offset++]=len}else if(len<=255){this._buf[this._offset++]=129;this._buf[this._offset++]=len}else if(len<=65535){this._buf[this._offset++]=130;this._buf[this._offset++]=len>>8;this._buf[this._offset++]=len}else if(len<=16777215){this._buf[this._offset++]=131;this._buf[this._offset++]=len>>16;this._buf[this._offset++]=len>>8;this._buf[this._offset++]=len}else{throw newInvalidAsn1Error("Length too long (> 4 bytes)")}};Writer.prototype.startSequence=function(tag){if(typeof tag!=="number")tag=ASN1.Sequence|ASN1.Constructor;this.writeByte(tag);this._seq.push(this._offset);this._ensure(3);this._offset+=3};Writer.prototype.endSequence=function(){var seq=this._seq.pop();var start=seq+3;var len=this._offset-start;if(len<=127){this._shift(start,len,-2);this._buf[seq]=len}else if(len<=255){this._shift(start,len,-1);this._buf[seq]=129;this._buf[seq+1]=len}else if(len<=65535){this._buf[seq]=130;this._buf[seq+1]=len>>8;this._buf[seq+2]=len}else if(len<=16777215){this._shift(start,len,1);this._buf[seq]=131;this._buf[seq+1]=len>>16;this._buf[seq+2]=len>>8;this._buf[seq+3]=len}else{throw newInvalidAsn1Error("Sequence too long")}};Writer.prototype._shift=function(start,len,shift){assert.ok(start!==undefined);assert.ok(len!==undefined);assert.ok(shift);this._buf.copy(this._buf,start+shift,start,start+len);this._offset+=shift};Writer.prototype._ensure=function(len){assert.ok(len);if(this._size-this._offset<len){var sz=this._size*this._options.growthFactor;if(sz-this._offset<len)sz+=len;var buf=Buffer.alloc(sz);this._buf.copy(buf,0,0,this._offset);this._buf=buf;this._size=sz}};module.exports=Writer},{"./errors":381,"./types":384,assert:16,"safer-buffer":470}],386:[function(require,module,exports){var Ber=require("./ber/index");module.exports={Ber:Ber,BerReader:Ber.Reader,BerWriter:Ber.Writer}},{"./ber/index":382}],387:[function(require,module,exports){(function(Buffer,process){(function(){var assert=require("assert");var Stream=require("stream").Stream;var util=require("util");var UUID_REGEXP=/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;function _capitalize(str){return str.charAt(0).toUpperCase()+str.slice(1)}function _toss(name,expected,oper,arg,actual){throw new assert.AssertionError({message:util.format("%s (%s) is required",name,expected),actual:actual===undefined?typeof arg:actual(arg),expected:expected,operator:oper||"===",stackStartFunction:_toss.caller})}function _getClass(arg){return Object.prototype.toString.call(arg).slice(8,-1)}function noop(){}var types={bool:{check:function(arg){return typeof arg==="boolean"}},func:{check:function(arg){return typeof arg==="function"}},string:{check:function(arg){return typeof arg==="string"}},object:{check:function(arg){return typeof arg==="object"&&arg!==null}},number:{check:function(arg){return typeof arg==="number"&&!isNaN(arg)}},finite:{check:function(arg){return typeof arg==="number"&&!isNaN(arg)&&isFinite(arg)}},buffer:{check:function(arg){return Buffer.isBuffer(arg)},operator:"Buffer.isBuffer"},array:{check:function(arg){return Array.isArray(arg)},operator:"Array.isArray"},stream:{check:function(arg){return arg instanceof Stream},operator:"instanceof",actual:_getClass},date:{check:function(arg){return arg instanceof Date},operator:"instanceof",actual:_getClass},regexp:{check:function(arg){return arg instanceof RegExp},operator:"instanceof",actual:_getClass},uuid:{check:function(arg){return typeof arg==="string"&&UUID_REGEXP.test(arg)},operator:"isUUID"}};function _setExports(ndebug){var keys=Object.keys(types);var out;if(process.env.NODE_NDEBUG){out=noop}else{out=function(arg,msg){if(!arg){_toss(msg,"true",arg)}}}keys.forEach(function(k){if(ndebug){out[k]=noop;return}var type=types[k];out[k]=function(arg,msg){if(!type.check(arg)){_toss(msg,k,type.operator,arg,type.actual)}}});keys.forEach(function(k){var name="optional"+_capitalize(k);if(ndebug){out[name]=noop;return}var type=types[k];out[name]=function(arg,msg){if(arg===undefined||arg===null){return}if(!type.check(arg)){_toss(msg,k,type.operator,arg,type.actual)}}});keys.forEach(function(k){var name="arrayOf"+_capitalize(k);if(ndebug){out[name]=noop;return}var type=types[k];var expected="["+k+"]";out[name]=function(arg,msg){if(!Array.isArray(arg)){_toss(msg,expected,type.operator,arg,type.actual)}var i;for(i=0;i<arg.length;i++){if(!type.check(arg[i])){_toss(msg,expected,type.operator,arg,type.actual)}}}});keys.forEach(function(k){var name="optionalArrayOf"+_capitalize(k);if(ndebug){out[name]=noop;return}var type=types[k];var expected="["+k+"]";out[name]=function(arg,msg){if(arg===undefined||arg===null){return}if(!Array.isArray(arg)){_toss(msg,expected,type.operator,arg,type.actual)}var i;for(i=0;i<arg.length;i++){if(!type.check(arg[i])){_toss(msg,expected,type.operator,arg,type.actual)}}}});Object.keys(assert).forEach(function(k){if(k==="AssertionError"){out[k]=assert[k];return}if(ndebug){out[k]=noop;return}out[k]=assert[k]});out._setExports=_setExports;return out}module.exports=_setExports(process.env.NODE_NDEBUG)}).call(this)}).call(this,{isBuffer:require("../../browser-agent/node_modules/is-buffer/index.js")},require("_process"))},{"../../browser-agent/node_modules/is-buffer/index.js":146,_process:179,assert:16,stream:229,util:243}],388:[function(require,module,exports){var crypto=require("crypto"),parse=require("url").parse;var keys=["acl","location","logging","notification","partNumber","policy","requestPayment","torrent","uploadId","uploads","versionId","versioning","versions","website"];function authorization(options){return"AWS "+options.key+":"+sign(options)}module.exports=authorization;module.exports.authorization=authorization;function hmacSha1(options){return crypto.createHmac("sha1",options.secret).update(options.message).digest("base64")}module.exports.hmacSha1=hmacSha1;function sign(options){options.message=stringToSign(options);return hmacSha1(options)}module.exports.sign=sign;function signQuery(options){options.message=queryStringToSign(options);return hmacSha1(options)}module.exports.signQuery=signQuery;function stringToSign(options){var headers=options.amazonHeaders||"";if(headers)headers+="\n";var r=[options.verb,options.md5,options.contentType,options.date?options.date.toUTCString():"",headers+options.resource];return r.join("\n")}module.exports.stringToSign=stringToSign;function queryStringToSign(options){return"GET\n\n\n"+options.date+"\n"+options.resource}module.exports.queryStringToSign=queryStringToSign;function canonicalizeHeaders(headers){var buf=[],fields=Object.keys(headers);for(var i=0,len=fields.length;i<len;++i){var field=fields[i],val=headers[field],field=field.toLowerCase();if(0!==field.indexOf("x-amz"))continue;buf.push(field+":"+val)}return buf.sort().join("\n")}module.exports.canonicalizeHeaders=canonicalizeHeaders;function canonicalizeResource(resource){var url=parse(resource,true),path=url.pathname,buf=[];Object.keys(url.query).forEach(function(key){if(!~keys.indexOf(key))return;var val=""==url.query[key]?"":"="+encodeURIComponent(url.query[key]);buf.push(key+val)});return path+(buf.length?"?"+buf.sort().join("&"):"")}module.exports.canonicalizeResource=canonicalizeResource},{crypto:81,url:238}],389:[function(require,module,exports){(function(process,Buffer){(function(){var aws4=exports,url=require("url"),querystring=require("querystring"),crypto=require("crypto"),lru=require("./lru"),credentialsCache=lru(1e3);function hmac(key,string,encoding){return crypto.createHmac("sha256",key).update(string,"utf8").digest(encoding)}function hash(string,encoding){return crypto.createHash("sha256").update(string,"utf8").digest(encoding)}function encodeRfc3986(urlEncodedString){return urlEncodedString.replace(/[!'()*]/g,function(c){return"%"+c.charCodeAt(0).toString(16).toUpperCase()})}function encodeRfc3986Full(str){return encodeRfc3986(encodeURIComponent(str))}var HEADERS_TO_IGNORE={authorization:true,connection:true,"x-amzn-trace-id":true,"user-agent":true,expect:true,"presigned-expires":true,range:true};function RequestSigner(request,credentials){if(typeof request==="string")request=url.parse(request);var headers=request.headers=request.headers||{},hostParts=(!this.service||!this.region)&&this.matchHost(request.hostname||request.host||headers.Host||headers.host);this.request=request;this.credentials=credentials||this.defaultCredentials();this.service=request.service||hostParts[0]||"";this.region=request.region||hostParts[1]||"us-east-1";if(this.service==="email")this.service="ses";if(!request.method&&request.body)request.method="POST";if(!headers.Host&&!headers.host){headers.Host=request.hostname||request.host||this.createHost();if(request.port)headers.Host+=":"+request.port}if(!request.hostname&&!request.host)request.hostname=headers.Host||headers.host;this.isCodeCommitGit=this.service==="codecommit"&&request.method==="GIT"}RequestSigner.prototype.matchHost=function(host){var match=(host||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/);var hostParts=(match||[]).slice(1,3);if(hostParts[1]==="es")hostParts=hostParts.reverse();if(hostParts[1]=="s3"){hostParts[0]="s3";hostParts[1]="us-east-1"}else{for(var i=0;i<2;i++){if(/^s3-/.test(hostParts[i])){hostParts[1]=hostParts[i].slice(3);hostParts[0]="s3";break}}}return hostParts};RequestSigner.prototype.isSingleRegion=function(){if(["s3","sdb"].indexOf(this.service)>=0&&this.region==="us-east-1")return true;return["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)>=0};RequestSigner.prototype.createHost=function(){var region=this.isSingleRegion()?"":"."+this.region,subdomain=this.service==="ses"?"email":this.service;return subdomain+region+".amazonaws.com"};RequestSigner.prototype.prepareRequest=function(){this.parsePath();var request=this.request,headers=request.headers,query;if(request.signQuery){this.parsedPath.query=query=this.parsedPath.query||{};if(this.credentials.sessionToken)query["X-Amz-Security-Token"]=this.credentials.sessionToken;if(this.service==="s3"&&!query["X-Amz-Expires"])query["X-Amz-Expires"]=86400;if(query["X-Amz-Date"])this.datetime=query["X-Amz-Date"];else query["X-Amz-Date"]=this.getDateTime();query["X-Amz-Algorithm"]="AWS4-HMAC-SHA256";query["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString();query["X-Amz-SignedHeaders"]=this.signedHeaders()}else{if(!request.doNotModifyHeaders&&!this.isCodeCommitGit){if(request.body&&!headers["Content-Type"]&&!headers["content-type"])headers["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8";if(request.body&&!headers["Content-Length"]&&!headers["content-length"])headers["Content-Length"]=Buffer.byteLength(request.body);if(this.credentials.sessionToken&&!headers["X-Amz-Security-Token"]&&!headers["x-amz-security-token"])headers["X-Amz-Security-Token"]=this.credentials.sessionToken;if(this.service==="s3"&&!headers["X-Amz-Content-Sha256"]&&!headers["x-amz-content-sha256"])headers["X-Amz-Content-Sha256"]=hash(this.request.body||"","hex");if(headers["X-Amz-Date"]||headers["x-amz-date"])this.datetime=headers["X-Amz-Date"]||headers["x-amz-date"];else headers["X-Amz-Date"]=this.getDateTime()}delete headers.Authorization;delete headers.authorization}};RequestSigner.prototype.sign=function(){if(!this.parsedPath)this.prepareRequest();if(this.request.signQuery){this.parsedPath.query["X-Amz-Signature"]=this.signature()}else{this.request.headers.Authorization=this.authHeader()}this.request.path=this.formatPath();return this.request};RequestSigner.prototype.getDateTime=function(){if(!this.datetime){var headers=this.request.headers,date=new Date(headers.Date||headers.date||new Date);this.datetime=date.toISOString().replace(/[:\-]|\.\d{3}/g,"");if(this.isCodeCommitGit)this.datetime=this.datetime.slice(0,-1)}return this.datetime};RequestSigner.prototype.getDate=function(){return this.getDateTime().substr(0,8)};RequestSigner.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")};RequestSigner.prototype.signature=function(){var date=this.getDate(),cacheKey=[this.credentials.secretAccessKey,date,this.region,this.service].join(),kDate,kRegion,kService,kCredentials=credentialsCache.get(cacheKey);if(!kCredentials){kDate=hmac("AWS4"+this.credentials.secretAccessKey,date);kRegion=hmac(kDate,this.region);kService=hmac(kRegion,this.service);kCredentials=hmac(kService,"aws4_request");credentialsCache.set(cacheKey,kCredentials)}return hmac(kCredentials,this.stringToSign(),"hex")};RequestSigner.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),hash(this.canonicalString(),"hex")].join("\n")};RequestSigner.prototype.canonicalString=function(){if(!this.parsedPath)this.prepareRequest();var pathStr=this.parsedPath.path,query=this.parsedPath.query,headers=this.request.headers,queryStr="",normalizePath=this.service!=="s3",decodePath=this.service==="s3"||this.request.doNotEncodePath,decodeSlashesInPath=this.service==="s3",firstValOnly=this.service==="s3",bodyHash;if(this.service==="s3"&&this.request.signQuery){bodyHash="UNSIGNED-PAYLOAD"}else if(this.isCodeCommitGit){bodyHash=""}else{bodyHash=headers["X-Amz-Content-Sha256"]||headers["x-amz-content-sha256"]||hash(this.request.body||"","hex")}if(query){var reducedQuery=Object.keys(query).reduce(function(obj,key){if(!key)return obj;obj[encodeRfc3986Full(key)]=!Array.isArray(query[key])?query[key]:firstValOnly?query[key][0]:query[key];return obj},{});var encodedQueryPieces=[];Object.keys(reducedQuery).sort().forEach(function(key){if(!Array.isArray(reducedQuery[key])){encodedQueryPieces.push(key+"="+encodeRfc3986Full(reducedQuery[key]))}else{reducedQuery[key].map(encodeRfc3986Full).sort().forEach(function(val){encodedQueryPieces.push(key+"="+val)})}});queryStr=encodedQueryPieces.join("&")}if(pathStr!=="/"){if(normalizePath)pathStr=pathStr.replace(/\/{2,}/g,"/");pathStr=pathStr.split("/").reduce(function(path,piece){if(normalizePath&&piece===".."){path.pop()}else if(!normalizePath||piece!=="."){if(decodePath)piece=decodeURIComponent(piece.replace(/\+/g," "));path.push(encodeRfc3986Full(piece))}return path},[]).join("/");if(pathStr[0]!=="/")pathStr="/"+pathStr;if(decodeSlashesInPath)pathStr=pathStr.replace(/%2F/g,"/")}return[this.request.method||"GET",pathStr,queryStr,this.canonicalHeaders()+"\n",this.signedHeaders(),bodyHash].join("\n")};RequestSigner.prototype.canonicalHeaders=function(){var headers=this.request.headers;function trimAll(header){return header.toString().trim().replace(/\s+/g," ")}return Object.keys(headers).filter(function(key){return HEADERS_TO_IGNORE[key.toLowerCase()]==null}).sort(function(a,b){return a.toLowerCase()<b.toLowerCase()?-1:1}).map(function(key){return key.toLowerCase()+":"+trimAll(headers[key])}).join("\n")};RequestSigner.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map(function(key){return key.toLowerCase()}).filter(function(key){return HEADERS_TO_IGNORE[key]==null}).sort().join(";")};RequestSigner.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")};RequestSigner.prototype.defaultCredentials=function(){var env=process.env;return{accessKeyId:env.AWS_ACCESS_KEY_ID||env.AWS_ACCESS_KEY,secretAccessKey:env.AWS_SECRET_ACCESS_KEY||env.AWS_SECRET_KEY,sessionToken:env.AWS_SESSION_TOKEN}};RequestSigner.prototype.parsePath=function(){var path=this.request.path||"/";if(/[^0-9A-Za-z;,\/?:@&=+$\-_.!~*'()#%]/.test(path)){path=encodeURI(decodeURI(path))}var queryIx=path.indexOf("?"),query=null;if(queryIx>=0){query=querystring.parse(path.slice(queryIx+1));path=path.slice(0,queryIx)}this.parsedPath={path:path,query:query}};RequestSigner.prototype.formatPath=function(){var path=this.parsedPath.path,query=this.parsedPath.query;if(!query)return path;if(query[""]!=null)delete query[""];return path+"?"+encodeRfc3986(querystring.stringify(query))};aws4.RequestSigner=RequestSigner;aws4.sign=function(request,credentials){return new RequestSigner(request,credentials).sign()}}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{"./lru":390,_process:179,buffer:71,crypto:81,querystring:190,url:238}],390:[function(require,module,exports){module.exports=function(size){return new LruCache(size)};function LruCache(size){this.capacity=size|0;this.map=Object.create(null);this.list=new DoublyLinkedList}LruCache.prototype.get=function(key){var node=this.map[key];if(node==null)return undefined;this.used(node);return node.val};LruCache.prototype.set=function(key,val){var node=this.map[key];if(node!=null){node.val=val}else{if(!this.capacity)this.prune();if(!this.capacity)return false;node=new DoublyLinkedNode(key,val);this.map[key]=node;this.capacity--}this.used(node);return true};LruCache.prototype.used=function(node){this.list.moveToFront(node)};LruCache.prototype.prune=function(){var node=this.list.pop();if(node!=null){delete this.map[node.key];this.capacity++}};function DoublyLinkedList(){this.firstNode=null;this.lastNode=null}DoublyLinkedList.prototype.moveToFront=function(node){if(this.firstNode==node)return;this.remove(node);if(this.firstNode==null){this.firstNode=node;this.lastNode=node;node.prev=null;node.next=null}else{node.prev=null;node.next=this.firstNode;node.next.prev=node;this.firstNode=node}};DoublyLinkedList.prototype.pop=function(){var lastNode=this.lastNode;if(lastNode!=null){this.remove(lastNode)}return lastNode};DoublyLinkedList.prototype.remove=function(node){if(this.firstNode==node){this.firstNode=node.next}else if(node.prev!=null){node.prev.next=node.next}if(this.lastNode==node){this.lastNode=node.prev}else if(node.next!=null){node.next.prev=node.prev}};function DoublyLinkedNode(key,val){this.key=key;this.val=val;this.prev=null;this.next=null}},{}],391:[function(require,module,exports){"use strict";var crypto_hash_sha512=require("tweetnacl").lowlevel.crypto_hash;var BLF_J=0;var Blowfish=function(){
23
+ ;if(xhr.readyState!==rStates.LOADING||!response)break;self.push(new Buffer(new Uint8Array(response)));break;case"ms-stream":response=xhr.response;if(xhr.readyState!==rStates.LOADING)break;var reader=new global.MSStreamReader;reader.onprogress=function(){if(reader.result.byteLength>self._pos){self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos))));self._pos=reader.result.byteLength}};reader.onload=function(){self.push(null)};reader.readAsArrayBuffer(response);break}if(self._xhr.readyState===rStates.DONE&&self._mode!=="ms-stream"){self.push(null)}}}).call(this)}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{"./capability":231,_process:179,buffer:71,inherits:145,"readable-stream":205}],234:[function(require,module,exports){"use strict";var Buffer=require("safe-buffer").Buffer;var isEncoding=Buffer.isEncoding||function(encoding){encoding=""+encoding;switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function _normalizeEncoding(enc){if(!enc)return"utf8";var retried;while(true){switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase();retried=true}}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if(typeof nenc!=="string"&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}exports.StringDecoder=StringDecoder;function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text;this.end=utf16End;nb=4;break;case"utf8":this.fillLast=utf8FillLast;nb=4;break;case"base64":this.text=base64Text;this.end=base64End;nb=3;break;default:this.write=simpleWrite;this.end=simpleEnd;return}this.lastNeed=0;this.lastTotal=0;this.lastChar=Buffer.allocUnsafe(nb)}StringDecoder.prototype.write=function(buf){if(buf.length===0)return"";var r;var i;if(this.lastNeed){r=this.fillLast(buf);if(r===undefined)return"";i=this.lastNeed;this.lastNeed=0}else{i=0}if(i<buf.length)return r?r+this.text(buf,i):this.text(buf,i);return r||""};StringDecoder.prototype.end=utf8End;StringDecoder.prototype.text=utf8Text;StringDecoder.prototype.fillLast=function(buf){if(this.lastNeed<=buf.length){buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,buf.length);this.lastNeed-=buf.length};function utf8CheckByte(byte){if(byte<=127)return 0;else if(byte>>5===6)return 2;else if(byte>>4===14)return 3;else if(byte>>3===30)return 4;return-1}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j<i)return 0;var nb=utf8CheckByte(buf[j]);if(nb>=0){if(nb>0)self.lastNeed=nb-1;return nb}if(--j<i)return 0;nb=utf8CheckByte(buf[j]);if(nb>=0){if(nb>0)self.lastNeed=nb-2;return nb}if(--j<i)return 0;nb=utf8CheckByte(buf[j]);if(nb>=0){if(nb>0){if(nb===2)nb=0;else self.lastNeed=nb-3}return nb}return 0}function utf8CheckExtraBytes(self,buf,p){if((buf[0]&192)!==128){self.lastNeed=0;return"�".repeat(p)}if(self.lastNeed>1&&buf.length>1){if((buf[1]&192)!==128){self.lastNeed=1;return"�".repeat(p+1)}if(self.lastNeed>2&&buf.length>2){if((buf[2]&192)!==128){self.lastNeed=2;return"�".repeat(p+2)}}}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed;var r=utf8CheckExtraBytes(this,buf,p);if(r!==undefined)return r;if(this.lastNeed<=buf.length){buf.copy(this.lastChar,p,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}buf.copy(this.lastChar,p,0,buf.length);this.lastNeed-=buf.length}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);buf.copy(this.lastChar,0,end);return buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed)return r+"�".repeat(this.lastTotal-this.lastNeed);return r}function utf16Text(buf,i){if((buf.length-i)%2===0){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(c>=55296&&c<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=buf[buf.length-2];this.lastChar[1]=buf[buf.length-1];return r.slice(0,-1)}}return r}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=buf[buf.length-1];return buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;if(n===0)return buf.toString("base64",i);this.lastNeed=3-n;this.lastTotal=3;if(n===1){this.lastChar[0]=buf[buf.length-1]}else{this.lastChar[0]=buf[buf.length-2];this.lastChar[1]=buf[buf.length-1]}return buf.toString("base64",i,buf.length-n)}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed)return r+this.lastChar.toString("base64",0,3-this.lastNeed);return r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}},{"safe-buffer":235}],235:[function(require,module,exports){arguments[4][202][0].apply(exports,arguments)},{buffer:71,dup:202}],236:[function(require,module,exports){(function(setImmediate,clearImmediate){(function(){var nextTick=require("process/browser.js").nextTick;var apply=Function.prototype.apply;var slice=Array.prototype.slice;var immediateIds={};var nextImmediateId=0;exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)};exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)};exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()};function Timeout(id,clearFn){this._id=id;this._clearFn=clearFn}Timeout.prototype.unref=Timeout.prototype.ref=function(){};Timeout.prototype.close=function(){this._clearFn.call(window,this._id)};exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId);item._idleTimeout=msecs};exports.unenroll=function(item){clearTimeout(item._idleTimeoutId);item._idleTimeout=-1};exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;if(msecs>=0){item._idleTimeoutId=setTimeout(function onTimeout(){if(item._onTimeout)item._onTimeout()},msecs)}};exports.setImmediate=typeof setImmediate==="function"?setImmediate:function(fn){var id=nextImmediateId++;var args=arguments.length<2?false:slice.call(arguments,1);immediateIds[id]=true;nextTick(function onNextTick(){if(immediateIds[id]){if(args){fn.apply(null,args)}else{fn.call(null)}exports.clearImmediate(id)}});return id};exports.clearImmediate=typeof clearImmediate==="function"?clearImmediate:function(id){delete immediateIds[id]}}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":179,timers:236}],237:[function(require,module,exports){var Buffer=require("buffer").Buffer;module.exports=function(buf){if(buf instanceof Uint8Array){if(buf.byteOffset===0&&buf.byteLength===buf.buffer.byteLength){return buf.buffer}else if(typeof buf.buffer.slice==="function"){return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}}if(Buffer.isBuffer(buf)){var arrayCopy=new Uint8Array(buf.length);var len=buf.length;for(var i=0;i<len;i++){arrayCopy[i]=buf[i]}return arrayCopy.buffer}else{throw new Error("Argument must be a Buffer")}}},{buffer:71}],238:[function(require,module,exports){"use strict";var punycode=require("punycode");var util=require("./util");exports.parse=urlParse;exports.resolve=urlResolve;exports.resolveObject=urlResolveObject;exports.format=urlFormat;exports.Url=Url;function Url(){this.protocol=null;this.slashes=null;this.auth=null;this.host=null;this.port=null;this.hostname=null;this.hash=null;this.search=null;this.query=null;this.pathname=null;this.path=null;this.href=null}var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,simplePathPattern=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,delims=["<",">",'"',"`"," ","\r","\n","\t"],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:true,"javascript:":true},hostlessProtocol={javascript:true,"javascript:":true},slashedProtocol={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},querystring=require("querystring");function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&util.isObject(url)&&url instanceof Url)return url;var u=new Url;u.parse(url,parseQueryString,slashesDenoteHost);return u}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url)){throw new TypeError("Parameter 'url' must be a string, not "+typeof url)}var queryIndex=url.indexOf("?"),splitter=queryIndex!==-1&&queryIndex<url.indexOf("#")?"?":"#",uSplit=url.split(splitter),slashRegex=/\\/g;uSplit[0]=uSplit[0].replace(slashRegex,"/");url=uSplit.join(splitter);var rest=url;rest=rest.trim();if(!slashesDenoteHost&&url.split("#").length===1){var simplePath=simplePathPattern.exec(rest);if(simplePath){this.path=rest;this.href=rest;this.pathname=simplePath[1];if(simplePath[2]){this.search=simplePath[2];if(parseQueryString){this.query=querystring.parse(this.search.substr(1))}else{this.query=this.search.substr(1)}}else if(parseQueryString){this.search="";this.query={}}return this}}var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto;rest=rest.substr(proto.length)}if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes=rest.substr(0,2)==="//";if(slashes&&!(proto&&hostlessProtocol[proto])){rest=rest.substr(2);this.slashes=true}}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){var hostEnd=-1;for(var i=0;i<hostEndingChars.length;i++){var hec=rest.indexOf(hostEndingChars[i]);if(hec!==-1&&(hostEnd===-1||hec<hostEnd))hostEnd=hec}var auth,atSign;if(hostEnd===-1){atSign=rest.lastIndexOf("@")}else{atSign=rest.lastIndexOf("@",hostEnd)}if(atSign!==-1){auth=rest.slice(0,atSign);rest=rest.slice(atSign+1);this.auth=decodeURIComponent(auth)}hostEnd=-1;for(var i=0;i<nonHostChars.length;i++){var hec=rest.indexOf(nonHostChars[i]);if(hec!==-1&&(hostEnd===-1||hec<hostEnd))hostEnd=hec}if(hostEnd===-1)hostEnd=rest.length;this.host=rest.slice(0,hostEnd);rest=rest.slice(hostEnd);this.parseHost();this.hostname=this.hostname||"";var ipv6Hostname=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!ipv6Hostname){var hostparts=this.hostname.split(/\./);for(var i=0,l=hostparts.length;i<l;i++){var part=hostparts[i];if(!part)continue;if(!part.match(hostnamePartPattern)){var newpart="";for(var j=0,k=part.length;j<k;j++){if(part.charCodeAt(j)>127){newpart+="x"}else{newpart+=part[j]}}if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i);var notHost=hostparts.slice(i+1);var bit=part.match(hostnamePartStart);if(bit){validParts.push(bit[1]);notHost.unshift(bit[2])}if(notHost.length){rest="/"+notHost.join(".")+rest}this.hostname=validParts.join(".");break}}}}if(this.hostname.length>hostnameMaxLen){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!ipv6Hostname){this.hostname=punycode.toASCII(this.hostname)}var p=this.port?":"+this.port:"";var h=this.hostname||"";this.host=h+p;this.href+=this.host;if(ipv6Hostname){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(rest[0]!=="/"){rest="/"+rest}}}if(!unsafeProtocol[lowerProto]){for(var i=0,l=autoEscape.length;i<l;i++){var ae=autoEscape[i];if(rest.indexOf(ae)===-1)continue;var esc=encodeURIComponent(ae);if(esc===ae){esc=escape(ae)}rest=rest.split(ae).join(esc)}}var hash=rest.indexOf("#");if(hash!==-1){this.hash=rest.substr(hash);rest=rest.slice(0,hash)}var qm=rest.indexOf("?");if(qm!==-1){this.search=rest.substr(qm);this.query=rest.substr(qm+1);if(parseQueryString){this.query=querystring.parse(this.query)}rest=rest.slice(0,qm)}else if(parseQueryString){this.search="";this.query={}}if(rest)this.pathname=rest;if(slashedProtocol[lowerProto]&&this.hostname&&!this.pathname){this.pathname="/"}if(this.pathname||this.search){var p=this.pathname||"";var s=this.search||"";this.path=p+s}this.href=this.format();return this};function urlFormat(obj){if(util.isString(obj))obj=urlParse(obj);if(!(obj instanceof Url))return Url.prototype.format.call(obj);return obj.format()}Url.prototype.format=function(){var auth=this.auth||"";if(auth){auth=encodeURIComponent(auth);auth=auth.replace(/%3A/i,":");auth+="@"}var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",host=false,query="";if(this.host){host=auth+this.host}else if(this.hostname){host=auth+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]");if(this.port){host+=":"+this.port}}if(this.query&&util.isObject(this.query)&&Object.keys(this.query).length){query=querystring.stringify(this.query)}var search=this.search||query&&"?"+query||"";if(protocol&&protocol.substr(-1)!==":")protocol+=":";if(this.slashes||(!protocol||slashedProtocol[protocol])&&host!==false){host="//"+(host||"");if(pathname&&pathname.charAt(0)!=="/")pathname="/"+pathname}else if(!host){host=""}if(hash&&hash.charAt(0)!=="#")hash="#"+hash;if(search&&search.charAt(0)!=="?")search="?"+search;pathname=pathname.replace(/[?#]/g,function(match){return encodeURIComponent(match)});search=search.replace("#","%23");return protocol+host+pathname+search+hash};function urlResolve(source,relative){return urlParse(source,false,true).resolve(relative)}Url.prototype.resolve=function(relative){return this.resolveObject(urlParse(relative,false,true)).format()};function urlResolveObject(source,relative){if(!source)return relative;return urlParse(source,false,true).resolveObject(relative)}Url.prototype.resolveObject=function(relative){if(util.isString(relative)){var rel=new Url;rel.parse(relative,false,true);relative=rel}var result=new Url;var tkeys=Object.keys(this);for(var tk=0;tk<tkeys.length;tk++){var tkey=tkeys[tk];result[tkey]=this[tkey]}result.hash=relative.hash;if(relative.href===""){result.href=result.format();return result}if(relative.slashes&&!relative.protocol){var rkeys=Object.keys(relative);for(var rk=0;rk<rkeys.length;rk++){var rkey=rkeys[rk];if(rkey!=="protocol")result[rkey]=relative[rkey]}if(slashedProtocol[result.protocol]&&result.hostname&&!result.pathname){result.path=result.pathname="/"}result.href=result.format();return result}if(relative.protocol&&relative.protocol!==result.protocol){if(!slashedProtocol[relative.protocol]){var keys=Object.keys(relative);for(var v=0;v<keys.length;v++){var k=keys[v];result[k]=relative[k]}result.href=result.format();return result}result.protocol=relative.protocol;if(!relative.host&&!hostlessProtocol[relative.protocol]){var relPath=(relative.pathname||"").split("/");while(relPath.length&&!(relative.host=relPath.shift()));if(!relative.host)relative.host="";if(!relative.hostname)relative.hostname="";if(relPath[0]!=="")relPath.unshift("");if(relPath.length<2)relPath.unshift("");result.pathname=relPath.join("/")}else{result.pathname=relative.pathname}result.search=relative.search;result.query=relative.query;result.host=relative.host||"";result.auth=relative.auth;result.hostname=relative.hostname||relative.host;result.port=relative.port;if(result.pathname||result.search){var p=result.pathname||"";var s=result.search||"";result.path=p+s}result.slashes=result.slashes||relative.slashes;result.href=result.format();return result}var isSourceAbs=result.pathname&&result.pathname.charAt(0)==="/",isRelAbs=relative.host||relative.pathname&&relative.pathname.charAt(0)==="/",mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative.pathname&&relative.pathname.split("/")||[],psychotic=result.protocol&&!slashedProtocol[result.protocol];if(psychotic){result.hostname="";result.port=null;if(result.host){if(srcPath[0]==="")srcPath[0]=result.host;else srcPath.unshift(result.host)}result.host="";if(relative.protocol){relative.hostname=null;relative.port=null;if(relative.host){if(relPath[0]==="")relPath[0]=relative.host;else relPath.unshift(relative.host)}relative.host=null}mustEndAbs=mustEndAbs&&(relPath[0]===""||srcPath[0]==="")}if(isRelAbs){result.host=relative.host||relative.host===""?relative.host:result.host;result.hostname=relative.hostname||relative.hostname===""?relative.hostname:result.hostname;result.search=relative.search;result.query=relative.query;srcPath=relPath}else if(relPath.length){if(!srcPath)srcPath=[];srcPath.pop();srcPath=srcPath.concat(relPath);result.search=relative.search;result.query=relative.query}else if(!util.isNullOrUndefined(relative.search)){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift()}}result.search=relative.search;result.query=relative.query;if(!util.isNull(result.pathname)||!util.isNull(result.search)){result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")}result.href=result.format();return result}if(!srcPath.length){result.pathname=null;if(result.search){result.path="/"+result.search}else{result.path=null}result.href=result.format();return result}var last=srcPath.slice(-1)[0];var hasTrailingSlash=(result.host||relative.host||srcPath.length>1)&&(last==="."||last==="..")||last==="";var up=0;for(var i=srcPath.length;i>=0;i--){last=srcPath[i];if(last==="."){srcPath.splice(i,1)}else if(last===".."){srcPath.splice(i,1);up++}else if(up){srcPath.splice(i,1);up--}}if(!mustEndAbs&&!removeAllDots){for(;up--;up){srcPath.unshift("..")}}if(mustEndAbs&&srcPath[0]!==""&&(!srcPath[0]||srcPath[0].charAt(0)!=="/")){srcPath.unshift("")}if(hasTrailingSlash&&srcPath.join("/").substr(-1)!=="/"){srcPath.push("")}var isAbsolute=srcPath[0]===""||srcPath[0]&&srcPath[0].charAt(0)==="/";if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift()}}mustEndAbs=mustEndAbs||result.host&&srcPath.length;if(mustEndAbs&&!isAbsolute){srcPath.unshift("")}if(!srcPath.length){result.pathname=null;result.path=null}else{result.pathname=srcPath.join("/")}if(!util.isNull(result.pathname)||!util.isNull(result.search)){result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")}result.auth=relative.auth||result.auth;result.slashes=result.slashes||relative.slashes;result.href=result.format();return result};Url.prototype.parseHost=function(){var host=this.host;var port=portPattern.exec(host);if(port){port=port[0];if(port!==":"){this.port=port.substr(1)}host=host.substr(0,host.length-port.length)}if(host)this.hostname=host}},{"./util":239,punycode:187,querystring:190}],239:[function(require,module,exports){"use strict";module.exports={isString:function(arg){return typeof arg==="string"},isObject:function(arg){return typeof arg==="object"&&arg!==null},isNull:function(arg){return arg===null},isNullOrUndefined:function(arg){return arg==null}}},{}],240:[function(require,module,exports){(function(global){(function(){module.exports=deprecate;function deprecate(fn,msg){if(config("noDeprecation")){return fn}var warned=false;function deprecated(){if(!warned){if(config("throwDeprecation")){throw new Error(msg)}else if(config("traceDeprecation")){console.trace(msg)}else{console.warn(msg)}warned=true}return fn.apply(this,arguments)}return deprecated}function config(name){try{if(!global.localStorage)return false}catch(_){return false}var val=global.localStorage[name];if(null==val)return false;return String(val).toLowerCase()==="true"}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],241:[function(require,module,exports){arguments[4][17][0].apply(exports,arguments)},{dup:17}],242:[function(require,module,exports){arguments[4][18][0].apply(exports,arguments)},{dup:18}],243:[function(require,module,exports){arguments[4][19][0].apply(exports,arguments)},{"./support/isBuffer":242,_process:179,dup:19,inherits:241}],244:[function(require,module,exports){var indexOf=require("indexof");var Object_keys=function(obj){if(Object.keys)return Object.keys(obj);else{var res=[];for(var key in obj)res.push(key);return res}};var forEach=function(xs,fn){if(xs.forEach)return xs.forEach(fn);else for(var i=0;i<xs.length;i++){fn(xs[i],i,xs)}};var defineProp=function(){try{Object.defineProperty({},"_",{});return function(obj,name,value){Object.defineProperty(obj,name,{writable:true,enumerable:false,configurable:true,value:value})}}catch(e){return function(obj,name,value){obj[name]=value}}}();var globals=["Array","Boolean","Date","Error","EvalError","Function","Infinity","JSON","Math","NaN","Number","Object","RangeError","ReferenceError","RegExp","String","SyntaxError","TypeError","URIError","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","eval","isFinite","isNaN","parseFloat","parseInt","undefined","unescape"];function Context(){}Context.prototype={};var Script=exports.Script=function NodeScript(code){if(!(this instanceof Script))return new Script(code);this.code=code};Script.prototype.runInContext=function(context){if(!(context instanceof Context)){throw new TypeError("needs a 'context' argument.")}var iframe=document.createElement("iframe");if(!iframe.style)iframe.style={};iframe.style.display="none";document.body.appendChild(iframe);var win=iframe.contentWindow;var wEval=win.eval,wExecScript=win.execScript;if(!wEval&&wExecScript){wExecScript.call(win,"null");wEval=win.eval}forEach(Object_keys(context),function(key){win[key]=context[key]});forEach(globals,function(key){if(context[key]){win[key]=context[key]}});var winKeys=Object_keys(win);var res=wEval.call(win,this.code);forEach(Object_keys(win),function(key){if(key in context||indexOf(winKeys,key)===-1){context[key]=win[key]}});forEach(globals,function(key){if(!(key in context)){defineProp(context,key,win[key])}});document.body.removeChild(iframe);return res};Script.prototype.runInThisContext=function(){return eval(this.code)};Script.prototype.runInNewContext=function(context){var ctx=Script.createContext(context);var res=this.runInContext(ctx);forEach(Object_keys(ctx),function(key){context[key]=ctx[key]});return res};forEach(Object_keys(Script.prototype),function(name){exports[name]=Script[name]=function(code){var s=Script(code);return s[name].apply(s,[].slice.call(arguments,1))}});exports.createScript=function(code){return exports.Script(code)};exports.createContext=Script.createContext=function(context){var copy=new Context;if(typeof context==="object"){forEach(Object_keys(context),function(key){copy[key]=context[key]})}return copy}},{indexof:144}],245:[function(require,module,exports){module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty;function extend(){var target={};for(var i=0;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(hasOwnProperty.call(source,key)){target[key]=source[key]}}}return target}},{}],246:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./lib/feature-detection","./lib/config","./lib/browser-agent","./lib/configuration-override"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var feature_detection_1=require("./lib/feature-detection");var config_1=require("./lib/config");var browser_agent_1=require("./lib/browser-agent");var configuration_override_1=require("./lib/configuration-override");var SEALIGHTS_WINDOW_OBJECT="$Sealights";var COMPONENTS="components";var featureDetection=null;try{featureDetection=new feature_detection_1.FeatureDetection(window);if(window&&window[SEALIGHTS_WINDOW_OBJECT]){window[SEALIGHTS_WINDOW_OBJECT].configuration=configuration_override_1.ConfigurationOverride.create(window[SEALIGHTS_WINDOW_OBJECT].configuration);var browserAgent_1=new browser_agent_1.BrowserAgent(window,featureDetection);window["$SealightsAgent"]=browserAgent_1;window[SEALIGHTS_WINDOW_OBJECT].agentVersion=config_1.SL_AGENT_VERSION;if(window[SEALIGHTS_WINDOW_OBJECT]&&window[SEALIGHTS_WINDOW_OBJECT][COMPONENTS]){Object.keys(window[SEALIGHTS_WINDOW_OBJECT][COMPONENTS]).forEach(function(buildSessionId){browserAgent_1.createInstance(window[SEALIGHTS_WINDOW_OBJECT][COMPONENTS][buildSessionId])})}else{browserAgent_1.createInstance(window[SEALIGHTS_WINDOW_OBJECT])}}}catch(e){if(featureDetection&&featureDetection.hasConsoleLogAPI()){console.log("Sealights browser listener failed to start. Error: ",e)}}})},{"./lib/browser-agent":251,"./lib/config":257,"./lib/configuration-override":259,"./lib/feature-detection":266}],247:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./state-tracker","../../common/state-tracker","./test-state-helper","./entities/environment-data","./services/http/http-client","./services/json/json-client","./istanbul-to-footprints-convertor","./istanbul-to-footprints-convertor-v3","./services/light-backend-proxy","./footprints-queue-sender","./watchdog","./code-coverage-manager","./browser-agent-instance","./queues/footprints-items-queue","./configuration-manager","./logger/log-factory","./basic-uuid-generator","./window-timers-wrapper","./color-cookie-handler","./queues/queue","./delegate","./services/json/json-client-adapter","./browser-events-process","./browser-hits-converter","./browser-agent-instance-fpv6","./browser-hits-collector","./sl-mapping-loader","./services/json/noop-json-client","../../common/agent-instance-data","../../common/agent-events/agent-events-conracts","../../common/agent-events/cockpit-notifier","../../common/http/backend-proxy","../../common/config-process/config-loader","../../common/footprints-process-v6/relative-path-resolver","../../common/footprints-process-v6/footprints-buffer","../../common/footprints-process-v6/index","../../common/config-process","../../common/system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentFactory=void 0;var state_tracker_1=require("./state-tracker");var state_tracker_2=require("../../common/state-tracker");var test_state_helper_1=require("./test-state-helper");var environment_data_1=require("./entities/environment-data");var http_client_1=require("./services/http/http-client");var json_client_1=require("./services/json/json-client");var istanbul_to_footprints_convertor_1=require("./istanbul-to-footprints-convertor");var istanbul_to_footprints_convertor_v3_1=require("./istanbul-to-footprints-convertor-v3");var light_backend_proxy_1=require("./services/light-backend-proxy");var footprints_queue_sender_1=require("./footprints-queue-sender");var watchdog_1=require("./watchdog");var code_coverage_manager_1=require("./code-coverage-manager");var browser_agent_instance_1=require("./browser-agent-instance");var footprints_items_queue_1=require("./queues/footprints-items-queue");var configuration_manager_1=require("./configuration-manager");var log_factory_1=require("./logger/log-factory");var basic_uuid_generator_1=require("./basic-uuid-generator");var window_timers_wrapper_1=require("./window-timers-wrapper");var color_cookie_handler_1=require("./color-cookie-handler");var queue_1=require("./queues/queue");var delegate_1=require("./delegate");var json_client_adapter_1=require("./services/json/json-client-adapter");var browser_events_process_1=require("./browser-events-process");var browser_hits_converter_1=require("./browser-hits-converter");var browser_agent_instance_fpv6_1=require("./browser-agent-instance-fpv6");var browser_hits_collector_1=require("./browser-hits-collector");var sl_mapping_loader_1=require("./sl-mapping-loader");var noop_json_client_1=require("./services/json/noop-json-client");var agent_instance_data_1=require("../../common/agent-instance-data");var agent_events_conracts_1=require("../../common/agent-events/agent-events-conracts");var cockpit_notifier_1=require("../../common/agent-events/cockpit-notifier");var backend_proxy_1=require("../../common/http/backend-proxy");var config_loader_1=require("../../common/config-process/config-loader");var relative_path_resolver_1=require("../../common/footprints-process-v6/relative-path-resolver");var footprints_buffer_1=require("../../common/footprints-process-v6/footprints-buffer");var index_1=require("../../common/footprints-process-v6/index");var config_process_1=require("../../common/config-process");var system_date_1=require("../../common/system-date");var FOOTPRINTS_SENDER_WATCHDOG="FootPrintsSenderWatchdog";var FOOTPRINTS_FLUSH_WATCHDOG="FootprintsFlushWatchdog";var ACTIVE_EXECUTION_WATCHDOG="ActiveExecutionWatchdog";var KEEP_ALIVE_WATCHDOG="KeepaliveWatchdog";var CONFIGURATION_WATCHDOG="getConfigFromServerWatchdog";var AgentFactory=function(){function AgentFactory(){}AgentFactory.createBrowserAgent=function(window,featureDetection,basicConfiguration){var configurationManager=AgentFactory.createConfigurationManager(basicConfiguration,window);var configuration=configurationManager.getConfiguration();var colorCookieHandler=AgentFactory.createColorCookieHandler(window);if(!configurationManager.isValidConfiguration()){return null}var agentInstanceData=new agent_instance_data_1.AgentInstanceData(agent_events_conracts_1.AgentType.TEST_LISTENER,agent_events_conracts_1.Technology.BROWSER);var logger=AgentFactory.createLogger("BrowserAgent",configuration,window);var agentConfiguration=this.createAgentConfiguration(configuration);var backendProxy=this.createBackendProxy(agentConfiguration,agentInstanceData,window,featureDetection,configuration);var eventProcess=this.createEventProcess(window,featureDetection,configuration,agentConfiguration,agentInstanceData,backendProxy);cockpit_notifier_1.CockpitNotifier.notifyStart(agentConfiguration,agentInstanceData,logger,{},backendProxy);if(agentConfiguration.footprintsEnableV6.value){return this.createBrowserAgentInstanceFPV6(window,featureDetection,configuration,agentInstanceData,logger,agentConfiguration,backendProxy,eventProcess,colorCookieHandler)}var stateTracker=AgentFactory.createStateTracker(configuration,window,featureDetection,agentInstanceData);var footprintsQueueSender=AgentFactory.createFootprintsQueueSender(window,featureDetection,configuration,stateTracker,agentInstanceData);var agent=new browser_agent_instance_1.BrowserAgentInstance(logger,footprintsQueueSender,configuration,window,colorCookieHandler,stateTracker,eventProcess,agentConfiguration);return agent};AgentFactory.createBrowserAgentInstanceFPV6=function(window,featureDetection,configuration,agentInstanceData,logger,agentConfig,backendProxy,eventsProcess,colorCookieHandler){
24
+ var configProcess=this.createConfigProcess(window,configuration,agentInstanceData,agentConfig,backendProxy);var stateTracker=this.createStateTrackerInfra(window,configuration,agentInstanceData,agentConfig,backendProxy,configProcess);var footprintsProcessV6=this.getCreateFootprintsProcessV6(window,configuration,agentInstanceData,agentConfig,backendProxy,stateTracker);var lightBackendProxy=AgentFactory.createLightBackendProxy(window,featureDetection,configuration,agentInstanceData);var slMappingLoader=this.createSlMappingLoader(window,lightBackendProxy,configuration);var flushFootprintsWatchdog=AgentFactory.createWatchdog(window,configuration,FOOTPRINTS_FLUSH_WATCHDOG,agentConfig.footprintsCollectIntervalSecs.value);return new browser_agent_instance_fpv6_1.BrowserAgentInstanceFpv6(logger,footprintsProcessV6,configuration,window,colorCookieHandler,stateTracker,eventsProcess,agentConfig,flushFootprintsWatchdog,slMappingLoader)};AgentFactory.createFootprintsQueueSender=function(window,featureDetection,configuration,stateTracker,agentInstanceData){var watchdog=AgentFactory.createWatchdog(window,configuration,FOOTPRINTS_SENDER_WATCHDOG);var lightBackendProxy=AgentFactory.createLightBackendProxy(window,featureDetection,configuration,agentInstanceData);var codeCoverageManager=AgentFactory.createCodeCoverageManager(window,configuration);var testStateHelper=AgentFactory.createTestStateHelper();var environmentData=AgentFactory.createEnvironmentData(window,configuration);var footprintsItemsQueue=AgentFactory.createFootprintsItemsQueue(configuration);var logger=AgentFactory.createLogger("FootprintsQueueSender",configuration,window);var slMappingLoader=this.createSlMappingLoader(window,lightBackendProxy,configuration);var footprintsQueueSender=new footprints_queue_sender_1.FootprintsQueueSender(watchdog,lightBackendProxy,codeCoverageManager,stateTracker,testStateHelper,environmentData,configuration,footprintsItemsQueue,window,logger,slMappingLoader);return footprintsQueueSender};AgentFactory.createWatchdog=function(window,configuration,classname,intervalSec){var intervalMS=(intervalSec||configuration.interval||10)*1e3;var logger=AgentFactory.createLogger(classname,configuration,window);var windowTimeoutWrapper=AgentFactory.createWindowTimersWrapper(window);var watchdog=new watchdog_1.Watchdog(intervalMS,windowTimeoutWrapper,{autoReset:true},logger);return watchdog};AgentFactory.createCodeCoverageManager=function(window,configuration){var istanbulToFootprintsConvertor=AgentFactory.createInstanbulToFootprintsConvertor(window,configuration);var codeCoverageManager=new code_coverage_manager_1.CodeCoverageManager(istanbulToFootprintsConvertor,configuration);return codeCoverageManager};AgentFactory.createLightBackendProxy=function(window,featureDetection,configuration,agentInstanceData){var jsonClient=AgentFactory.createJsonClient(window,featureDetection,configuration,agentInstanceData);var logger=AgentFactory.createLogger("FootprintsServiceProxy",configuration,window);var lightBackendProxy=new light_backend_proxy_1.LightBackendProxy(configuration,jsonClient,logger);return lightBackendProxy};AgentFactory.createSlMappingLoader=function(window,lightBackendProxy,configuration){var logger=AgentFactory.createLogger("slMappingLoader",configuration,window);return new sl_mapping_loader_1.SlMappingLoader(lightBackendProxy,window,logger)};AgentFactory.createJsonClient=function(window,featureDetection,configuration,agentInstanceData){var httpClient=AgentFactory.createHttpClient(window,featureDetection,configuration);return configuration.blockBrowserHttpTraffic?new noop_json_client_1.NoopJsonClient(httpClient,configuration,agentInstanceData):new json_client_1.JsonClient(httpClient,configuration,agentInstanceData)};AgentFactory.createHttpClient=function(window,featureDetection,configuration){var logger=AgentFactory.createLogger("HttpClient",configuration,window);var httpClient=new http_client_1.HttpClient(window,featureDetection,logger);return httpClient};AgentFactory.createStateTracker=function(configuration,window,featureDetection,agentInstanceData){var watchdog=AgentFactory.createWatchdog(window,configuration,ACTIVE_EXECUTION_WATCHDOG);var logger=AgentFactory.createLogger("StateTracker",configuration,window);var jsonClient=AgentFactory.createJsonClient(window,featureDetection,configuration,agentInstanceData);var stateTracker=new state_tracker_1.StateTracker(configuration,jsonClient,watchdog,logger);return stateTracker};AgentFactory.createColorCookieHandler=function(window){var colorCookieHandler=new color_cookie_handler_1.ColorCookieHandler(window);return colorCookieHandler};AgentFactory.createTestStateHelper=function(){var testStateHelper=new test_state_helper_1.TestStateHelper;return testStateHelper};AgentFactory.createWindowTimersWrapper=function(window){var windowTimersWrapper=new window_timers_wrapper_1.WindowTimersWrapper(window);return windowTimersWrapper};AgentFactory.createEnvironmentData=function(window,configuration){if(!environment_data_1.EnvironmentData.constantAgentId)environment_data_1.EnvironmentData.constantAgentId=basic_uuid_generator_1.BasicUuidGenerator.createUuid()+"<|>"+this.getTime(window);var environmentData=environment_data_1.EnvironmentData.create(configuration);return environmentData};AgentFactory.createInstanbulToFootprintsConvertor=function(window,configuration){var instanbulToFootprintsConvertor=null;if(configuration.resolveWithoutHash){instanbulToFootprintsConvertor=new istanbul_to_footprints_convertor_v3_1.IstanbulToFootprintsConvertorV3(window,configuration)}else{instanbulToFootprintsConvertor=new istanbul_to_footprints_convertor_1.IstanbulToFootprintsConverter(window,configuration)}return instanbulToFootprintsConvertor};AgentFactory.createFootprintsItemsQueue=function(configuration){var footprintsItemsQueue=new footprints_items_queue_1.FootprintsItemsQueue(configuration);return footprintsItemsQueue};AgentFactory.createEventProcess=function(window,featureDetection,configurationData,agentConfiguration,agentInstanceData,backendProxy){var sendToServerWatchdog=this.createWatchdog(window,configurationData,"sendToServer");var keepAliveWatchdog=this.createWatchdog(window,configurationData,"keepAlive");var environmentData=this.createEnvironmentData(window,configurationData);environmentData.testStage=agentConfiguration.testStage.value;var logger=AgentFactory.createLogger("BrowserAgent",configurationData,window);var queue=new queue_1.Queue(new delegate_1.Delegate);var eventsProcess=new browser_events_process_1.BrowserEventsProcess(agentConfiguration,agentInstanceData,sendToServerWatchdog,keepAliveWatchdog,environmentData,backendProxy,queue,logger);return eventsProcess};AgentFactory.createBackendProxy=function(agentConfiguration,agentInstanceData,window,featureDetection,configurationData){var logger=this.createLogger("BackendProxy",configurationData,window);var httpClientConfig=this.createHttpClientConfig(agentConfiguration);var jsonClientAdapter=this.createJsonClientAdapter(window,featureDetection,configurationData,agentInstanceData);var backendProxy=new backend_proxy_1.BackendProxy(agentInstanceData,httpClientConfig,logger,jsonClientAdapter);return backendProxy};AgentFactory.createHttpClientConfig=function(agentConfig){return{token:agentConfig.token.value,proxy:agentConfig.proxy.value,server:agentConfig.server.value,compressRequests:agentConfig.gzip.value}};AgentFactory.createConfigurationManager=function(basicConfiguration,window){var logger=AgentFactory.createLogger("ConfigurationManager",basicConfiguration,window);var configurationManager=new configuration_manager_1.ConfigurationManager(logger,basicConfiguration,window);return configurationManager};AgentFactory.createLogger=function(className,basicConfiguration,window){var _a,_b;return log_factory_1.LogFactory.createLogger(className,basicConfiguration.logLevel||((_b=(_a=window===null||window===void 0?void 0:window.$Sealights)===null||_a===void 0?void 0:_a.configuration)===null||_b===void 0?void 0:_b.logLevel))};AgentFactory.getTime=function(window){if(window&&window.performance&&typeof window.performance.now==="function"){return performance.now()}return system_date_1.getSystemDateValueOf()};AgentFactory.createAgentConfiguration=function(configuration){var configLoader=new config_loader_1.ConfigLoader;var configObject=configuration;if(!configObject.build){configObject.build=configObject.buildName}if(!configObject.branch){configObject.branch=configObject.branchName}return configLoader.loadAgentConfiguration(configuration)};AgentFactory.createJsonClientAdapter=function(window,featureDetection,config,agentInstanceData){var jsonClient=this.createJsonClient(window,featureDetection,config,agentInstanceData);return new json_client_adapter_1.JsonClientAdapter(jsonClient,config.server)};AgentFactory.getCreateFootprintsProcessV6=function(window,configuration,agentInstanceData,agentConfig,backendProxy,stateTracker){var sendToServerWatchdog=AgentFactory.createWatchdog(window,configuration,FOOTPRINTS_SENDER_WATCHDOG,agentConfig.footprintsSendIntervalSecs.value);var keepaliveWatchdog=AgentFactory.createWatchdog(window,configuration,KEEP_ALIVE_WATCHDOG);var relativePathResolver=new relative_path_resolver_1.RelativePathResolver;var hitsCollector=new browser_hits_collector_1.BrowserHitsCollector(configuration.buildSessionId,this.createLogger("browserHitsCollector",configuration,window));var hitsConverter=new browser_hits_converter_1.BrowserHitsConverter(relativePathResolver,window,agentConfig.buildSessionId.value,this.createLogger("HitsConverter",configuration,window));var footprintsBuffer=new footprints_buffer_1.FootprintsBuffer(agentInstanceData,agentConfig);return new index_1.FootprintsProcess(agentConfig,sendToServerWatchdog,keepaliveWatchdog,this.createLogger("footprintsProcess",configuration,window),hitsCollector,hitsConverter,footprintsBuffer,backendProxy,stateTracker)};AgentFactory.createConfigProcess=function(window,configuration,agentInstanceData,agentConfig,backendProxy){var sendToServerWatchdog=AgentFactory.createWatchdog(window,configuration,CONFIGURATION_WATCHDOG,30);return new config_process_1.ConfigProcess(agentConfig,sendToServerWatchdog,backendProxy,this.createLogger("configProcess",configuration,window))};AgentFactory.createStateTrackerInfra=function(window,configuration,agentInstanceData,agentConfig,backendProxy,configProcess){var watchdog=AgentFactory.createWatchdog(window,configuration,ACTIVE_EXECUTION_WATCHDOG,agentConfig.executionQueryIntervalSecs.value);return new state_tracker_2.StateTracker(agentConfig,configProcess,watchdog,backendProxy,this.createLogger("stateTracker",configuration,window))};return AgentFactory}();exports.AgentFactory=AgentFactory})},{"../../common/agent-events/agent-events-conracts":289,"../../common/agent-events/cockpit-notifier":294,"../../common/agent-instance-data":299,"../../common/config-process":303,"../../common/config-process/config-loader":300,"../../common/footprints-process-v6/footprints-buffer":317,"../../common/footprints-process-v6/index":320,"../../common/footprints-process-v6/relative-path-resolver":322,"../../common/http/backend-proxy":324,"../../common/state-tracker":331,"../../common/system-date":332,"./basic-uuid-generator":248,"./browser-agent-instance":250,"./browser-agent-instance-fpv6":249,"./browser-events-process":252,"./browser-hits-collector":253,"./browser-hits-converter":254,"./code-coverage-manager":255,"./color-cookie-handler":256,"./configuration-manager":258,"./delegate":261,"./entities/environment-data":264,"./footprints-queue-sender":267,"./istanbul-to-footprints-convertor":269,"./istanbul-to-footprints-convertor-v3":268,"./logger/log-factory":272,"./queues/footprints-items-queue":274,"./queues/queue":275,"./services/http/http-client":276,"./services/json/json-client":280,"./services/json/json-client-adapter":279,"./services/json/noop-json-client":281,"./services/light-backend-proxy":282,"./sl-mapping-loader":283,"./state-tracker":284,"./test-state-helper":285,"./watchdog":287,"./window-timers-wrapper":288}],248:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BasicUuidGenerator=void 0;var BasicUuidGenerator=function(){function BasicUuidGenerator(){}BasicUuidGenerator.createUuid=function(){var uuid="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=Math.random()*16|0,v=c=="x"?r:r&3|8;return v.toString(16)});return uuid};return BasicUuidGenerator}();exports.BasicUuidGenerator=BasicUuidGenerator})},{}],249:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./browser-agent-instance"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserAgentInstanceFpv6=void 0;var browser_agent_instance_1=require("./browser-agent-instance");var BrowserAgentInstanceFpv6=function(_super){__extends(BrowserAgentInstanceFpv6,_super);function BrowserAgentInstanceFpv6(logger,footprintsProcess,configuration,window,colorCookieHandler,stateTracker,eventsProcess,agentConfig,flushFootprintsWatchdog,slMappingLoader){var _this=_super.call(this,logger,{},configuration,window,colorCookieHandler,stateTracker,eventsProcess,agentConfig)||this;_this.footprintsProcess=footprintsProcess;_this.flushFootprintsWatchdog=flushFootprintsWatchdog;_this.slMappingLoader=slMappingLoader;_this.stateTracker.on("test_identifier_changed",_this.footprintsProcess.handleTestIdChanged.bind(_this.footprintsProcess));return _this}BrowserAgentInstanceFpv6.prototype.delegateEvents=function(){};BrowserAgentInstanceFpv6.prototype.startFootprintsProcess=function(){this.flushFootprintsWatchdog.addOnAlarmListener(this.footprintsProcess.flushCurrentFootprints.bind(this.footprintsProcess));this.flushFootprintsWatchdog.start();this.footprintsProcess.start();this.stateTracker.start();this.slMappingLoader.loadSlMapping(this.configuration.buildSessionId)};BrowserAgentInstanceFpv6.prototype.stopFootprintsProcess=function(){this.flushFootprintsWatchdog.stop();this.footprintsProcess.stop(function(){})};BrowserAgentInstanceFpv6.prototype.submitFootprints=function(){this.footprintsProcess.submitQueuedFootprints()};BrowserAgentInstanceFpv6.prototype.submitFootprintsSync=function(){return __awaiter(this,void 0,void 0,function(){var e_1;return __generator(this,function(_a){switch(_a.label){case 0:_a.trys.push([0,3,,4]);return[4,this.footprintsProcess.flushCurrentFootprints()];case 1:_a.sent();return[4,this.footprintsProcess.submitQueuedFootprints()];case 2:_a.sent();return[3,4];case 3:e_1=_a.sent();this.logger.error("Failed to submit footprint sync '"+e_1.message+"'");return[3,4];case 4:return[2]}})})};return BrowserAgentInstanceFpv6}(browser_agent_instance_1.BrowserAgentInstance);exports.BrowserAgentInstanceFpv6=BrowserAgentInstanceFpv6})},{"./browser-agent-instance":250}],250:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./config","./karma-handler","./basic-uuid-generator","../../common/agent-events/cockpit-notifier"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserAgentInstance=void 0;var config_1=require("./config");var karma_handler_1=require("./karma-handler");var basic_uuid_generator_1=require("./basic-uuid-generator");var cockpit_notifier_1=require("../../common/agent-events/cockpit-notifier");var BrowserAgentInstance=function(){function BrowserAgentInstance(logger,footprintsQueueSender,configuration,window,colorCookieHandler,stateTracker,eventsProcess,agentConfig){this.logger=logger;this.footprintsQueueSender=footprintsQueueSender;this.configuration=configuration;this.window=window;this.colorCookieHandler=colorCookieHandler;this.stateTracker=stateTracker;this.eventsProcess=eventsProcess;this.agentConfig=agentConfig;this._isStarted=false;if(logger==null)throw new Error("'logger' cannot be null or undefined");if(configuration==null)throw new Error("'configuration' cannot be null or undefined");if(window==null)throw new Error("'window' cannot be null or undefined");if(eventsProcess==null)throw new Error("'eventsProcess' cannot be null or undefined");if(agentConfig==null)throw new Error("'agentConfig' cannot be null or undefined");logger.info("Sealights "+config_1.SL_AGENT_TYPE+" version "+config_1.SL_AGENT_VERSION+" has been loaded");this.delegateEvents()}BrowserAgentInstance.prototype.delegateEvents=function(footprintsProcess){var _this=this;this.stateTracker.addOnColorChangedListener(function(){var color=_this.stateTracker.getCurrentColor();_this.colorCookieHandler.handleColorChange(color)})};BrowserAgentInstance.getExecutionId=function(){if(!BrowserAgentInstance.executionId){var execId=basic_uuid_generator_1.BasicUuidGenerator.createUuid();BrowserAgentInstance.executionId=execId}return BrowserAgentInstance.executionId};BrowserAgentInstance.prototype.enqueueEvent=function(event){this.eventsProcess.enqueueEvent(event)};BrowserAgentInstance.prototype.start=function(){if(this._isStarted)return;this.logger.info("Agent is starting. registerShutdownHook:"+this.configuration.registerShutdownHook);if(this.configuration.registerShutdownHook){this.registerShutdownHook()}this.eventsProcess.start();this.startFootprintsProcess();this._isStarted=true};BrowserAgentInstance.prototype.startFootprintsProcess=function(){this.footprintsQueueSender.start()};BrowserAgentInstance.prototype.stop=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:if(!this._isStarted)return[2];this.logger.info("Agent is stopping.");return[4,this.eventsProcess.stop()];case 1:_a.sent();this.stopFootprintsProcess();return[4,cockpit_notifier_1.CockpitNotifier.notifyShutdown()];case 2:_a.sent();this._isStarted=false;return[2]}})})};BrowserAgentInstance.prototype.stopFootprintsProcess=function(){this.footprintsQueueSender.sendAllSync()};BrowserAgentInstance.prototype.setCurrentTestIdentifier=function(testIdentifier){this.logger.info("Agent is setting current test identifier. testIdentifier:'"+testIdentifier+"'.");this.stateTracker.setCurrentTestIdentifier(testIdentifier)};BrowserAgentInstance.prototype.endTest=function(){this.logger.info("Test '"+this.stateTracker.getCurrentTestIdentifier()+"' ended, sending remaining footprints");this.submitFootprints();this.stateTracker.setCurrentTestIdentifier(null)};BrowserAgentInstance.prototype.submitFootprints=function(){this.footprintsQueueSender.sendAll()};BrowserAgentInstance.prototype.submitFootprintsSync=function(){try{this.footprintsQueueSender.sendAllSync()}catch(e){this.logger.error("Failed to submit footprint sync '"+e.message+"'")}};BrowserAgentInstance.prototype.isStarted=function(){return this._isStarted};BrowserAgentInstance.prototype.registerShutdownHook=function(){var context=this;var oldUnload=this.window.onunload;this.window.onunload=function(){if(oldUnload){oldUnload.call(arguments)}context.stop()};var oldBeforeUnload=this.window.onbeforeunload;this.window.onbeforeunload=function(){if(oldBeforeUnload){oldBeforeUnload.call(arguments)}context.stop()};if(this.window.__karma__){var handler=new karma_handler_1.KarmaHandler(this.window,this,this.logger);handler.overrideKarmaMethods();handler.start()}};return BrowserAgentInstance}();exports.BrowserAgentInstance=BrowserAgentInstance})},{"../../common/agent-events/cockpit-notifier":294,"./basic-uuid-generator":248,"./config":257,"./karma-handler":270}],251:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-factory","./logger/log-factory"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserAgent=void 0;var agent_factory_1=require("./agent-factory");var log_factory_1=require("./logger/log-factory");var BrowserAgent=function(){function BrowserAgent(window,featureDetection){this.instances=[];this.running=false;this.logger=log_factory_1.LogFactory.createLogger("BrowserAgent");this.instanceAddedForBsid={};this.window=window;this.featureDetection=featureDetection}BrowserAgent.prototype.addInstance=function(instance){this.instances.push(instance)};BrowserAgent.prototype.createInstance=function(configuration){if(this.instanceAddedForBsid[configuration.buildSessionId]){this.logger.info("Already has instance for bsid '"+configuration.buildSessionId+"'");return}try{this.instanceAddedForBsid[configuration.buildSessionId]=true;var browserAgent=agent_factory_1.AgentFactory.createBrowserAgent(this.window,this.featureDetection,configuration);if(browserAgent){browserAgent.start();this.instances.push(browserAgent)}else{this.logger.error("Invalid configuration for app: "+configuration.appName+",\n build: "+configuration.buildName+", branch: "+configuration.branchName+"\n Sealights agent disabled")}}catch(e){this.logger.error("Error while creating agent for app: "+configuration.appName+", build: "+configuration.buildName+",\n branch: "+configuration.branchName+". Error "+e)}};BrowserAgent.prototype.start=function(){if(this.instances.length==0){return}this.instances.forEach(function(instance){return instance.start()});this.running=true};BrowserAgent.prototype.stop=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,Promise.all(this.instances.map(function(instance){return instance.stop()}))];case 1:_a.sent();this.running=false;return[2]}})})};BrowserAgent.prototype.isRunning=function(){return this.running};BrowserAgent.prototype.setCurrentTestIdentifier=function(identifier){this.instances.forEach(function(instance){return instance.setCurrentTestIdentifier(identifier)})};BrowserAgent.prototype.sendAllFootprints=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,Promise.all(this.instances.map(function(instance){return instance.submitFootprintsSync()}))];case 1:_a.sent();return[2]}})})};return BrowserAgent}();exports.BrowserAgent=BrowserAgent})},{"./agent-factory":247,"./logger/log-factory":272}],252:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/events-process"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserEventsProcess=void 0;var events_process_1=require("../../common/events-process");var BrowserEventsProcess=function(_super){__extends(BrowserEventsProcess,_super);function BrowserEventsProcess(){return _super!==null&&_super.apply(this,arguments)||this}BrowserEventsProcess.prototype.stop=function(){return __awaiter(this,void 0,void 0,function(){var callback,items,packet;var _this=this;return __generator(this,function(_a){this.isRunning=false;this.sendToServerWatchdog.stop();if(this.configuration.enabled.value===false||this.configuration.sendEvents.value===false){return[2]}callback=function(err){if(err){_this.logger.error("Failed to submit final events, Error : '"+err+"'")}};while(this.eventsQueue.getQueueSize()>0){
25
+ items=this.eventsQueue.dequeue(events_process_1.EventsProcess.ITEMS_TO_DEQUE);packet=this.createEventsPacket(items);this.backendProxy.submitEvents(packet,callback,false)}return[2]})})};return BrowserEventsProcess}(events_process_1.EventsProcess);exports.BrowserEventsProcess=BrowserEventsProcess})},{"../../common/events-process":314}],253:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/footprints-process-v6/hits-collector"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserHitsCollector=void 0;var hits_collector_1=require("../../common/footprints-process-v6/hits-collector");var BrowserHitsCollector=function(_super){__extends(BrowserHitsCollector,_super);function BrowserHitsCollector(buildSessionId,logger,globalCoverageObject){var _this=_super.call(this,logger,globalCoverageObject)||this;_this.buildSessionId=buildSessionId;return _this}BrowserHitsCollector.prototype.getGlobalCoverageObject=function(){if(!this.globalCoverageObject){var coverageObject="$SealightsCoverage";var coverageObjectForBSID=coverageObject+"_"+this.buildSessionId;this.globalCoverageObject=window[coverageObjectForBSID]||window[coverageObject]}return this.globalCoverageObject};return BrowserHitsCollector}(hits_collector_1.HitsCollector);exports.BrowserHitsCollector=BrowserHitsCollector})},{"../../common/footprints-process-v6/hits-collector":318}],254:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/footprints-process-v6/base-browser-hits-converter"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserHitsConverter=void 0;var base_browser_hits_converter_1=require("../../common/footprints-process-v6/base-browser-hits-converter");var BrowserHitsConverter=function(_super){__extends(BrowserHitsConverter,_super);function BrowserHitsConverter(relativePathResolver,window,buildSessionId,logger){var _this=_super.call(this,relativePathResolver,buildSessionId,logger)||this;_this.window=window;return _this}BrowserHitsConverter.prototype.getSlMapping=function(){return this.window.slMappings[this.buildSessionId]||{}};return BrowserHitsConverter}(base_browser_hits_converter_1.BaseBrowserHitsConverter);exports.BrowserHitsConverter=BrowserHitsConverter})},{"../../common/footprints-process-v6/base-browser-hits-converter":315}],255:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CodeCoverageManager=void 0;var CodeCoverageManager=function(){function CodeCoverageManager(convertor,configuration){this.convertor=convertor;this.configuration=configuration;this.aggregatedCoverage={};this.isDestroyed=false}CodeCoverageManager.prototype.findCoverageContainer=function(){var coverageObject="$SealightsCoverage";var coverageObjectForBSID=coverageObject+"_"+this.configuration.buildSessionId;return window[coverageObjectForBSID]||window[coverageObject]};CodeCoverageManager.prototype.getFootprints=function(testInfo){var counters=this.getCounters(true);return this.convertor.convert(counters,testInfo.testName,testInfo.executionId)};CodeCoverageManager.prototype._clearCounters=function(istanbulCoverageObject){if(!istanbulCoverageObject)return;if(this.isDestroyed)return;var context=this;this.forEachProp(istanbulCoverageObject,function(moduleName,m){context.aggregatedCoverage[moduleName]=context.aggregatedCoverage[moduleName]||{s:{},b:{},f:{}};var am=context.aggregatedCoverage[moduleName];context.forEachProp(m.s,function(sid,s){am.s[sid]=(am.s[sid]||0)+m.s[sid];m.s[sid]=0});context.forEachProp(m.b,function(bid,b){am.b[bid]=am.b[bid]||Array.apply(null,Array(m.b[bid].length)).map(Number.prototype.valueOf,0);for(var idx=0;idx<am.b[bid].length;idx++){am.b[bid][idx]+=m.b[bid][idx];m.b[bid][idx]=0}});context.forEachProp(m.f,function(fid,f){am.f[fid]=(am.f[fid]||0)+m.f[fid];m.f[fid]=0})})};CodeCoverageManager.prototype.cloneCodeMetrics=function(o){var cloned={};for(var i in o){cloned[i]=this.cloneModule(o[i])}return cloned};CodeCoverageManager.prototype.cloneModule=function(m){var cm={b:{},f:{},s:{}};for(var i in m.s){cm.s[i]=m.s[i]}for(var i in m.f){cm.f[i]=m.f[i]}for(var i in m.b){cm.b[i]=m.b[i].slice()}cm.metadata=m.metadata;cm.path=m.path;cm.fnMap=m.fnMap;cm.fnToBranch=m.fnToBranch;cm.branchMap=m.branchMap;cm.inputSourceMap=m.inputSourceMap;return cm};CodeCoverageManager.prototype.forEachProp=function(obj,func){Object.keys(obj).forEach(function(k){func(k,obj[k])})};CodeCoverageManager.prototype.clearCounters=function(){if(this.isDestroyed)return;var ct=this.findCoverageContainer();if(ct){this._clearCounters(ct)}};CodeCoverageManager.prototype.getCounters=function(clearAfterwards){if(this.isDestroyed)return{};var ct=this.findCoverageContainer();if(ct){var ret=this.cloneCodeMetrics(ct);if(clearAfterwards)this._clearCounters(ct);return ret}};return CodeCoverageManager}();exports.CodeCoverageManager=CodeCoverageManager})},{}],256:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./state-tracker"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ColorCookieHandler=void 0;var state_tracker_1=require("./state-tracker");var ColorCookieHandler=function(){function ColorCookieHandler(window){this.window=window;this.COOKIE_KEY="x-sl-testid"}ColorCookieHandler.prototype.setCookie=function(color){var cookie=this.COOKIE_KEY+"="+color;this.window.document.cookie=cookie};ColorCookieHandler.prototype.handleColorChange=function(color){if(color!=null&&color!=state_tracker_1.StateTracker.ANONYMOUS_FOOTPRINTS_COLOR){this.setCookie(color)}else{this.removeCookie()}};ColorCookieHandler.prototype.removeCookie=function(){this.window.document.cookie=this.COOKIE_KEY+"=;expires=Thu, 01 Jan 1970 00:00:01 GMT;"};ColorCookieHandler.prototype.getCookie=function(){return this.window.document.cookie};return ColorCookieHandler}();exports.ColorCookieHandler=ColorCookieHandler})},{"./state-tracker":284}],257:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SL_AGENT_TYPE=exports.SL_AGENT_VERSION=void 0;exports.SL_AGENT_VERSION="1.0.0";exports.SL_AGENT_TYPE="browser"})},{}],258:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./entities/configuration-data"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigurationManager=void 0;var configuration_data_1=require("./entities/configuration-data");var ConfigurationManager=function(){function ConfigurationManager(logger,basicConfiguration,window){this.logger=logger;this.basicConfiguration=basicConfiguration;this.window=window;if(logger==null)throw new Error("'logger' cannot be null or undefined");if(basicConfiguration==null)throw new Error("'basicConfiguration' cannot be null or undefined");if(window==null)throw new Error("'window' cannot be null or undefined")}ConfigurationManager.prototype.getConfiguration=function(){if(this.currentConfiguration)return this.currentConfiguration;var configurationData=this.getDefaults();this.overrideConfiguration(configurationData);configurationData.labId=this.resolveLabId();this.currentConfiguration=configurationData;this.printConfiguration(configurationData);this.validateConfiguration(configurationData);return configurationData};ConfigurationManager.prototype.getDefaults=function(){var config=new configuration_data_1.ConfigurationData;config.appName=this.basicConfiguration.appName;config.branchName=this.basicConfiguration.branchName;config.buildName=this.basicConfiguration.buildName;config.buildSessionId=this.basicConfiguration.buildSessionId;config.customerId=this.basicConfiguration.customerId;config.token=this.basicConfiguration.token;config.server=this.basicConfiguration.server;config.interval=this.basicConfiguration.interval||10;config.maxItemsInQueue=this.basicConfiguration.maxItemsInQueue||500;config.workspacepath=this.basicConfiguration.workspacepath;return config};ConfigurationManager.prototype.resolveLabId=function(){var labId=this.readLabIdFromWindow();if(labId){this.logger.info("Using labId from the 'window' object. LabId:"+labId);return labId}labId=this.basicConfiguration.labId;if(labId){this.logger.info("Using labId from basic configuration. LabId:"+labId);return labId}labId=this.readLabIdFromSessionStorage();if(labId){this.logger.info("Using labId from session storage. LabId:"+labId);return labId}labId=this.basicConfiguration.buildSessionId;if(labId){this.logger.info("Using buildSessionId as labId. LabId:"+labId);return labId}labId=this.basicConfiguration.appName;if(labId){this.logger.info("Using appName as labId. LabId:"+labId);return labId}return"DefaultLabId"};ConfigurationManager.prototype.overrideConfiguration=function(configurationData){for(var p in this.basicConfiguration){configurationData[p]=this.basicConfiguration[p]}this.logger.info("[TO CS] - TODO: Send request to server to get the configuration.")};ConfigurationManager.prototype.printConfiguration=function(configurationData){this.logger.info("***********************************************************");this.logger.info("Current configuration:");this.logger.info("------------------------------------------------");for(var prop in configurationData){this.logger.info(prop+": '"+configurationData[prop])+"'"}this.logger.info("***********************************************************")};ConfigurationManager.prototype.validateConfiguration=function(configurationData){var _this=this;var fieldsWithError=[];if(!configurationData.customerId||configurationData.customerId=="")fieldsWithError.push("customerId");if(!configurationData.server||configurationData.server=="")fieldsWithError.push("server");if(!configurationData.appName||configurationData.appName=="")fieldsWithError.push("appName");if(!configurationData.branchName||configurationData.branchName=="")fieldsWithError.push("branchName");if(!configurationData.buildName||configurationData.buildName=="")fieldsWithError.push("buildName");if(!configurationData.token||configurationData.token=="")fieldsWithError.push("token");if(fieldsWithError.length>0){this.logger.warn("------------------------------------------------");this.logger.warn("Detected an invalid configuration:");fieldsWithError.forEach(function(field){_this.logger.warn("'"+field+"' is required but it had a 'null' or empty value.")});this.logger.warn("Please fix the configuration prior to using SeaLights.");this.logger.warn("------------------------------------------------")}this._isValidConfiguration=fieldsWithError.length==0};ConfigurationManager.prototype.isValidConfiguration=function(){return this._isValidConfiguration};ConfigurationManager.prototype.readLabIdFromSessionStorage=function(){var labId=null;if(this.window.sessionStorage&&typeof this.window.sessionStorage==="function"){labId=this.window.sessionStorage.getItem(ConfigurationManager.LAB_ID_KEY)}return labId};ConfigurationManager.prototype.readLabIdFromWindow=function(){return this.window[ConfigurationManager.LAB_ID_KEY]};ConfigurationManager.LAB_ID_KEY="__sl.labId__";return ConfigurationManager}();exports.ConfigurationManager=ConfigurationManager})},{"./entities/configuration-data":263}],259:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","events","./logger/console-logger"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigurationOverride=exports.ConfigChangedEvents=void 0;var EventEmitter=require("events");var console_logger_1=require("./logger/console-logger");var ConfigChangedEvents;(function(ConfigChangedEvents){ConfigChangedEvents["LOG_LEVEL_CHANGED"]="logLevelChanged"})(ConfigChangedEvents=exports.ConfigChangedEvents||(exports.ConfigChangedEvents={}));var ConfigurationOverride=function(_super){__extends(ConfigurationOverride,_super);function ConfigurationOverride(initialConfig){var _this=_super.call(this)||this;_this._logLevel=console_logger_1.LogLevels.INFO;_this.setMaxListeners(500);_this.loadInitialConfig(initialConfig);return _this}Object.defineProperty(ConfigurationOverride.prototype,"logLevel",{get:function(){return this._logLevel},set:function(value){this._logLevel=value;this.emit(ConfigChangedEvents.LOG_LEVEL_CHANGED,value)},enumerable:false,configurable:true});ConfigurationOverride.prototype.loadInitialConfig=function(initialConfig){if(initialConfig===void 0){initialConfig={}}for(var prop in initialConfig){var descriptor=Object.getOwnPropertyDescriptor(this.constructor.prototype,prop);if(descriptor&&typeof descriptor.set==="function"){this[prop]=initialConfig[prop]}}};ConfigurationOverride.create=function(configuration){if(configuration instanceof ConfigurationOverride){return configuration}return new ConfigurationOverride(configuration)};return ConfigurationOverride}(EventEmitter);exports.ConfigurationOverride=ConfigurationOverride})},{"./logger/console-logger":271,events:110}],260:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ExecutionStatus=void 0;var ExecutionStatus;(function(ExecutionStatus){ExecutionStatus["InProgress"]="created";ExecutionStatus["Ending"]="pendingDelete"})(ExecutionStatus=exports.ExecutionStatus||(exports.ExecutionStatus={}))})},{}],261:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Delegate=void 0;var Delegate=function(){function Delegate(){this.functions=new Array}Delegate.prototype.addListener=function(func){if(!func)return;if(this.functions)this.functions.push(func)};Delegate.prototype.fire=function(){if(!this.functions)return;for(var i=0;i<this.functions.length;i++){this.functions[i]()}};return Delegate}();exports.Delegate=Delegate})},{}],262:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BasicConfigurationData=void 0;var BasicConfigurationData=function(){function BasicConfigurationData(){}return BasicConfigurationData}();exports.BasicConfigurationData=BasicConfigurationData})},{}],263:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./basic-configuation-data"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigurationData=void 0;var basic_configuation_data_1=require("./basic-configuation-data");var ConfigurationData=function(_super){__extends(ConfigurationData,_super);function ConfigurationData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.registerShutdownHook=true;_this.enabled=true;return _this}return ConfigurationData}(basic_configuation_data_1.BasicConfigurationData);exports.ConfigurationData=ConfigurationData})},{"./basic-configuation-data":262}],264:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../config"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EnvironmentData=void 0;var config_1=require("../config");var EnvironmentData=function(){function EnvironmentData(){}EnvironmentData.create=function(configuration){var data=new EnvironmentData;data.agentType=config_1.SL_AGENT_TYPE;data.agentVersion=config_1.SL_AGENT_VERSION;data.agentId=EnvironmentData.constantAgentId;data.labId=configuration.labId||"";data.meta={navigator:window.navigator,userAgent:window.navigator&&window.navigator.userAgent,location:window.location};return data};return EnvironmentData}();exports.EnvironmentData=EnvironmentData})},{"../config":257}],265:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsItemData=void 0;var FootprintsItemData=function(){function FootprintsItemData(){}return FootprintsItemData}();exports.FootprintsItemData=FootprintsItemData})},{}],266:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FeatureDetection=void 0;var FeatureDetection=function(){function FeatureDetection(window){this.window=window;if(!window)throw new Error("'window' cannot be null or undefined")}FeatureDetection.prototype.hasBeaconAPI=function(){var result=window.navigator&&this.isFunction(window.navigator["sendBeacon"]);return result};FeatureDetection.prototype.hasConsoleLogAPI=function(){var result=window.console&&this.isFunction(window.console.log);return result};FeatureDetection.prototype.hasJsonAPI=function(){var result=JSON&&this.isFunction(JSON.stringify)&&this.isFunction(JSON.parse);return result};FeatureDetection.prototype.isFunction=function(o){return o&&typeof o==="function"};return FeatureDetection}();exports.FeatureDetection=FeatureDetection})},{}],267:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./entities/footprints-item-data","../../common/system-date","../../common/agent-events/cockpit-notifier"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsQueueSender=void 0;var footprints_item_data_1=require("./entities/footprints-item-data");var system_date_1=require("../../common/system-date");var cockpit_notifier_1=require("../../common/agent-events/cockpit-notifier");var FootprintsQueueSender=function(){function FootprintsQueueSender(watchdog,lightBackendProxy,codeCoverageManager,stateTracker,testStateHelper,environmentData,configuration,footprintsQueue,window,logger,slMappingLoader){var _this=this;this.watchdog=watchdog;this.lightBackendProxy=lightBackendProxy;this.codeCoverageManager=codeCoverageManager;this.stateTracker=stateTracker;this.testStateHelper=testStateHelper;this.environmentData=environmentData;this.configuration=configuration;this.footprintsQueue=footprintsQueue;this.window=window;this.logger=logger;this.slMappingLoader=slMappingLoader;this.isStarted=false;if(watchdog==null)throw new Error("'watchdog' cannot be null or undefined");if(lightBackendProxy==null)throw new Error("'lightBackendProxy' cannot be null or undefined");if(codeCoverageManager==null)throw new Error("'codeCoverageManager' cannot be null or undefined");if(stateTracker==null)throw new Error("'stateTracker' cannot be null or undefined");if(testStateHelper==null)throw new Error("'testStateHelper' cannot be null or undefined");if(environmentData==null)throw new Error("'environmentData' cannot be null or undefined");if(configuration==null)throw new Error("'configuration' cannot be null or undefined");if(footprintsQueue==null)throw new Error("'footprintsQueue' cannot be null or undefined");if(window==null)throw new Error("'window' cannot be null or undefined");if(logger==null)throw new Error("'logger' cannot be null or undefined");this.context=this;this.watchdog.addOnAlarmListener(function(){_this.context.onTimerTick()})}FootprintsQueueSender.prototype.onTimerTick=function(){if(!this.stateTracker.shouldCollectFootprints()){return}var footprints=this.getCurrentFootprints();this.send(footprints)};FootprintsQueueSender.prototype.start=function(){if(this.isStarted)return;this.watchdog.start();this.slMappingLoader.loadSlMapping(this.configuration.buildSessionId);this.isStarted=true};FootprintsQueueSender.prototype.stop=function(){if(!this.isStarted)return;this.watchdog.stop();this.isStarted=false};FootprintsQueueSender.prototype.send=function(footprintsData,async,shouldRequeue){if(async===void 0){async=true}if(shouldRequeue===void 0){shouldRequeue=true}if(!footprintsData){this.logger.info("No need to send footprints as the 'footprintsData' is null or undefined.");return}var request=this.createRequest(footprintsData);if(request==null){this.logger.info("No need to send footprints as the request is empty.");return}var context=this;var onSuccess=function(){context.logger.info("Sent footprints successfully")};var onError=function(response){context.logger.error("Failed while trying to send footprints. response.responseText: '"+response.responseText+"'. response.statusCode:"+response.statusCode);if(shouldRequeue){context.logger.info("Requeuing footprints again");context.footprintsQueue.requeueItems(footprintsData)}};this.lightBackendProxy.submitRequest(request,onSuccess,onError,async)};FootprintsQueueSender.prototype.sendAllSync=function(){if(!this.stateTracker.shouldCollectFootprints()){return}this.logger.info("Sending all remaining footprints synchronously.");this.delayIfHasRequestsInProgress();var async=false;var footprints=this.getCurrentFootprints();this.send(footprints,async)};FootprintsQueueSender.prototype.sendAll=function(){var footprints=this.getCurrentFootprints();this.send(footprints)};FootprintsQueueSender.prototype.delayIfHasRequestsInProgress=function(){var counter=this.configuration.delayShutdownInSeconds||30;while(this.lightBackendProxy.hasRequestsInProgress()&&counter-- >0){this.logger.info("Has other requests in progress. Sleeping.. # of requests: "+this.lightBackendProxy.getRequestsInProgressCount()+". Remaining retries: "+counter);this.sleep(1e3)}};FootprintsQueueSender.prototype.pushCurrentFootprints=function(){if(!this.stateTracker.shouldCollectFootprints()){return}var testId=this.stateTracker.getCurrentTestIdentifier();var testInfo=this.testStateHelper.splitTestIdToExecutionAndTestName(testId);var footprints=this.codeCoverageManager.getFootprints(testInfo);if(this.configuration.resolveWithoutHash){this.enqueueV5Footprints(footprints)}else{this.enqueueV2Footprints(footprints,testInfo)}};FootprintsQueueSender.prototype.enqueueV2Footprints=function(appsAndFootprintsArray,testInfo){if(appsAndFootprintsArray&&appsAndFootprintsArray.length){var queueItem=new footprints_item_data_1.FootprintsItemData;queueItem.testName=testInfo.testName;queueItem.executionId=testInfo.executionId;queueItem.apps=appsAndFootprintsArray;this.footprintsQueue.enqueueItem(queueItem)}};FootprintsQueueSender.prototype.enqueueV5Footprints=function(footprintsRequest){if(!footprintsRequest)return;if(!footprintsRequest.apps||footprintsRequest.apps.length==0)return;if(!footprintsRequest.tests||footprintsRequest.tests.length==0)return;this.footprintsQueue.enqueueItem(footprintsRequest)};FootprintsQueueSender.prototype.getCurrentFootprints=function(){this.pushCurrentFootprints();var footprints=this.footprintsQueue.getQueueContentsAndEmptyQueue();return footprints};FootprintsQueueSender.prototype.createRequest=function(data){if(this.configuration.resolveWithoutHash){return this.createV5FootprintsRequest(data)}return this.createV2FootprintsRequest(data)};FootprintsQueueSender.prototype.createV5FootprintsRequest=function(footprintsData){var originalRequest=footprintsData[0];if(!originalRequest){return null}if(!this.hasApps(originalRequest)||!this.hasTests(originalRequest)){return null}var request={};request.customerId=this.configuration.customerId;request.environment=this.environmentData;request.configurationData=this.configuration;request.apps=originalRequest.apps;request.tests=originalRequest.tests;request.meta=originalRequest.meta;return request};FootprintsQueueSender.prototype.createV2FootprintsRequest=function(appsAndFootprintsArray){if(!appsAndFootprintsArray||!appsAndFootprintsArray.length){return null}var request={};request.customerId=this.configuration.customerId;request.items=appsAndFootprintsArray;request.environment=this.environmentData;request.configurationData=this.configuration;return request};FootprintsQueueSender.prototype.sleep=function(millis){var start=system_date_1.getSystemDateValueOf();var end=null;do{end=system_date_1.getSystemDateValueOf()}while(end-start<millis)};FootprintsQueueSender.prototype.hasApps=function(request){return request.apps&&request.apps.length>0};FootprintsQueueSender.prototype.hasTests=function(request){return request.tests&&request.tests.length>0};FootprintsQueueSender.prototype.loadSlMapping=function(){var _this=this;this.window.slMappings=this.window.slMappings||{};if(!this.window.slMappings[this.configuration.buildSessionId]){this.lightBackendProxy.getSlMappingFromServer(this.configuration.buildSessionId).then(function(mapping){return _this.window.slMappings[_this.configuration.buildSessionId]=mapping},function(err){var errMsg="Error while trying to load slMapping from server '"+err+"'";_this.logger.error(errMsg);cockpit_notifier_1.CockpitNotifier.sendGenericMessage(errMsg);_this.window.slMappings[_this.configuration.buildSessionId]={}})}};return FootprintsQueueSender}();exports.FootprintsQueueSender=FootprintsQueueSender})},{"../../common/agent-events/cockpit-notifier":294,"../../common/system-date":332,"./entities/footprints-item-data":265}],268:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./logger/log-factory","../../common/footprints-process-v6/location-formatter","../../common/footprints-process/collection-interval","../../common/system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.IstanbulToFootprintsConvertorV3=void 0;var log_factory_1=require("./logger/log-factory");var location_formatter_1=require("../../common/footprints-process-v6/location-formatter");var collection_interval_1=require("../../common/footprints-process/collection-interval");var system_date_1=require("../../common/system-date");var IstanbulToFootprintsConvertorV3=function(){function IstanbulToFootprintsConvertorV3(window,cfg){this.window=window;this.cfg=cfg;this.totalTests=0;if(!window)throw new Error("window is required");if(!cfg)throw new Error("cfg is required");this.collectionInterval=new collection_interval_1.CollectionInterval(this.cfg.interval*1e3);this.logger=log_factory_1.LogFactory.createLogger("IstanbulToFootprintsConvertor")}IstanbulToFootprintsConvertorV3.prototype.resetState=function(){this.totalTests=0;this.eidToHitsIndex={};this.uniqueIdToElement={};this.testNameToTestData={};this.fileNameToAppFile={};this.collectionInterval.next()};IstanbulToFootprintsConvertorV3.prototype.convert=function(istanbulFootprints,testName,executionId,mockTime){this.resetState();var result=this.createFootprintsFile();var app=result.apps[0];var localTime=mockTime?mockTime:system_date_1.getSystemDateValueOf();var test=this.getOrCreateTestData(testName,executionId,localTime,result);for(var moduleName in istanbulFootprints){var istanbulModule=istanbulFootprints[moduleName];if(!istanbulModule){continue}var scopeData={test:test,app:app,modulePath:istanbulModule.path.replace(/\\/g,"/"),istanbulModule:istanbulModule};if(istanbulModule.f){this.addMethodsWithHits(scopeData)}if(istanbulModule.b){this.addBranchesWithHits(scopeData)}}result.apps=this.filterAppsWithoutHits(result.apps);return result}
26
+ ;IstanbulToFootprintsConvertorV3.prototype.filterAppsWithoutHits=function(apps){var _this=this;if(!apps)return apps;return apps.filter(function(app){return _this.filterFilesWithoutHits(app)})};IstanbulToFootprintsConvertorV3.prototype.filterFilesWithoutHits=function(app){var _this=this;var hasFiles=false;if(!app||!app.files){return hasFiles}app.files=app.files.filter(function(file){return _this.filterElementsWithoutHits(file)});hasFiles=app.files.length>0;return hasFiles};IstanbulToFootprintsConvertorV3.prototype.filterElementsWithoutHits=function(file){var hasMethodHits=this.filterElementWithoutHits(file,"methods");var hasBranchHits=this.filterElementWithoutHits(file,"branches");var hasLineHits=this.filterElementWithoutHits(file,"lines");var hasHits=hasMethodHits||hasBranchHits||hasLineHits;return hasHits};IstanbulToFootprintsConvertorV3.prototype.filterElementWithoutHits=function(file,coverageType){var _this=this;var fileObject=file;var arrayOfCodeElements=fileObject[coverageType]||[];arrayOfCodeElements=arrayOfCodeElements.filter(function(ce){return _this.hasHit(ce)});fileObject[coverageType]=arrayOfCodeElements;var hasHits=arrayOfCodeElements.length>0;return hasHits};IstanbulToFootprintsConvertorV3.prototype.hasHit=function(element){var hasHitInAnyTest=element.hits.some(function(hitToTest){return hitToTest[1]>0});return hasHitInAnyTest};IstanbulToFootprintsConvertorV3.prototype.addMethodsWithHits=function(scopeData){var istanbulModule=scopeData.istanbulModule;for(var methodId in istanbulModule.f){var hits=istanbulModule.f[methodId];if(hits>0){var methodData=istanbulModule.fnMap[methodId];this.addOrUpdateMethodElement(scopeData,methodData,hits)}}};IstanbulToFootprintsConvertorV3.prototype.addBranchesWithHits=function(scopeData){var istanbulModule=scopeData.istanbulModule;for(var branchId in istanbulModule.b){var probesArray=istanbulModule.b[branchId];for(var idx=0;idx<probesArray.length;idx++){var hits=probesArray[idx];if(hits>0){var branchData=istanbulModule.branchMap[branchId];this.addOrUpdateBranchElement(scopeData,branchData,idx,hits)}}}};IstanbulToFootprintsConvertorV3.prototype.addOrUpdateMethodElement=function(scopeData,methodData,hits){var loc=methodData.loc||methodData.lc;var decl=methodData.decl||methodData.d;this.addOrUpdateElement(scopeData,loc,hits,this.getOrCreateMethodElement,false);if(decl){this.addOrUpdateElement(scopeData,decl,hits,this.getOrCreateMethodElement,false)}};IstanbulToFootprintsConvertorV3.prototype.addOrUpdateBranchElement=function(scopeData,branchData,probeIndex,hits){var locations=branchData.locations||branchData.lcs;var probePositionData=locations[probeIndex];this.addOrUpdateElement(scopeData,probePositionData,hits,this.getOrCreateBranchElement,true,probeIndex)};IstanbulToFootprintsConvertorV3.prototype.addOrUpdateElement=function(scopeData,startPositionData,hits,getOrCreateElement,isBranch,probIndex){var file=this.getOrCreateFootprintsAppFile(scopeData.modulePath,scopeData.app);var startPosition=startPositionData.start||startPositionData.st;var uniqueId=this.createUniqueId(startPosition,scopeData.modulePath,isBranch,probIndex);if(!uniqueId){return}var element=getOrCreateElement.call(this,uniqueId,file);this.addOrUpdateElementHits(scopeData.test,uniqueId,element,hits)};IstanbulToFootprintsConvertorV3.prototype.createUniqueId=function(startPosition,fullFilePath,isBranch,probIndex){var delimiter=isBranch?"|":"@";var uniqueId=fullFilePath+delimiter+this.formatLoc(startPosition);if(probIndex!=null){uniqueId+="|"+probIndex}var mapping=this.window.slMappings[this.cfg.buildSessionId];if(mapping){uniqueId=mapping[uniqueId]||uniqueId}return uniqueId};IstanbulToFootprintsConvertorV3.prototype.addOrUpdateElementHits=function(testData,elementUniqueId,element,hits){var HITS_INDEX=1;var eid=elementUniqueId+"|"+testData.index;var index=this.eidToHitsIndex[eid];if(index!=null){var testIndexAndHits=element.hits[index];var elementHits=testIndexAndHits[HITS_INDEX];elementHits=elementHits+hits;testIndexAndHits[HITS_INDEX]=elementHits}else{var testIndexAndHits=new Array;testIndexAndHits.push(testData.index);testIndexAndHits.push(hits);var length_1=element.hits.push(testIndexAndHits);this.eidToHitsIndex[eid]=length_1-1}};IstanbulToFootprintsConvertorV3.prototype.getOrCreateTestData=function(testName,executionId,localTime,result){if(!this.testNameToTestData[testName]){var test_1={executionId:executionId,localTime:localTime,testName:testName,collectionInterval:this.collectionInterval.toJson()};result.tests.push(test_1);this.testNameToTestData[testName]={index:this.totalTests++,test:test_1}}return this.testNameToTestData[testName]};IstanbulToFootprintsConvertorV3.prototype.getOrCreateMethodElement=function(uniqueId,file){if(!this.uniqueIdToElement[uniqueId]){var x={hits:new Array,uniqueId:uniqueId};this.uniqueIdToElement[uniqueId]=x;file.methods.push(x)}return this.uniqueIdToElement[uniqueId]};IstanbulToFootprintsConvertorV3.prototype.getOrCreateBranchElement=function(uniqueId,file){if(!this.uniqueIdToElement[uniqueId]){var x={hits:new Array,uniqueId:uniqueId};this.uniqueIdToElement[uniqueId]=x;if(file.branches)file.branches.push(x)}return this.uniqueIdToElement[uniqueId]};IstanbulToFootprintsConvertorV3.prototype.getOrCreateFootprintsAppFile=function(fileName,app){if(this.fileNameToAppFile[fileName]){return this.fileNameToAppFile[fileName]}var file={methods:new Array,branches:new Array,lines:new Array,path:fileName};app.files.push(file);this.fileNameToAppFile[fileName]=file;return file};IstanbulToFootprintsConvertorV3.prototype.createFootprintsFile=function(){var result={configurationData:{},customerId:this.cfg.customerId,environment:{},tests:[],apps:[],meta:{}};this.fileNameToAppFile={};this.testNameToTestData={};var app={appName:this.cfg.appName,branchName:this.cfg.branchName,buildName:this.cfg.buildName,moduleName:"",buildSessionId:this.cfg.buildSessionId,files:new Array};result.apps.push(app);return result};IstanbulToFootprintsConvertorV3.prototype.formatLoc=function(loc){return location_formatter_1.formatLocation(loc,this.logger)};return IstanbulToFootprintsConvertorV3}();exports.IstanbulToFootprintsConvertorV3=IstanbulToFootprintsConvertorV3})},{"../../common/footprints-process-v6/location-formatter":321,"../../common/footprints-process/collection-interval":323,"../../common/system-date":332,"./logger/log-factory":272}],269:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.IstanbulToFootprintsConverter=void 0;var utils_1=require("./utils");var IstanbulToFootprintsConverter=function(){function IstanbulToFootprintsConverter(window,configuration){this.window=window;this.configuration=configuration;if(configuration==null)throw new Error("'configuration' cannot be null or undefined")}IstanbulToFootprintsConverter.prototype.convert=function(istanbulFootprints){var apps={};var appsArray=new Array;if(istanbulFootprints){var context_1=this;Object.keys(istanbulFootprints).forEach(function(moduleName){var m=istanbulFootprints[moduleName];context_1.configuration.appName=context_1.configuration.appName||"";var a=apps[context_1.configuration.appName];var isNewApp=false;if(!a){a={appName:context_1.configuration.appName,build:context_1.configuration.buildName,branch:context_1.configuration.branchName,footprints:[]};isNewApp=true}var footprints=a.footprints;var filename=m.path;filename=filename.replace(/\\/g,"/");Object.keys(m.f).forEach(function(funcId){var funcInfo=m.fnMap[funcId];if(!funcInfo||funcInfo.skip)return;if(m.f[funcId]>0){var mn=context_1.getMethodName(funcInfo.name,funcInfo.guessedName);var pos=context_1.formatLoc(funcInfo.loc.originalStart||funcInfo.loc.start);if(m.inputSourceMap&&context_1.window["sourceMap"]){var sourceMapConsumer=new context_1.window["sourceMap"].SourceMapConsumer(m.inputSourceMap);pos=context_1.formatLoc(sourceMapConsumer.originalPositionFor(funcInfo.loc.start))}filename=funcInfo.originalFilename||filename;filename=context_1.getRelativeModulePath(filename);var fqmn=[mn,filename,pos].join("@");var hash=funcInfo.hash&&funcInfo.hash.hash;var footprintsItem_1={name:fqmn,hits:m.f[funcId],hash:hash,branches:new Array};if(m.fnToBranch&&m.fnToBranch[funcId]&&m.fnToBranch[funcId].length){m.fnToBranch[funcId].forEach(function(branchArray,index){var fileBranch=branchArray[0];var branchIndex=branchArray[1];if(m.b[fileBranch.toString()][branchIndex]>0){footprintsItem_1.branches.push(index)}})}footprints.push(footprintsItem_1)}});if(footprints.length&&isNewApp){appsArray.push(a);apps[a.appName]=a}})}return appsArray};IstanbulToFootprintsConverter.prototype.getMethodName=function(name,guessedName){var mn=name||guessedName||"(Anonymous)";if(mn.indexOf("(anonymous")>=0){mn="(Anonymous)"}return mn};IstanbulToFootprintsConverter.prototype.formatLoc=function(loc){return[loc.line,loc.column].join(",")};IstanbulToFootprintsConverter.prototype.getRelativeModulePath=function(path){var workspacepath=utils_1.Utils.adjustPathSlashes(this.configuration.workspacepath);path=utils_1.Utils.adjustPathSlashes(path);if(workspacepath){return path.replace(workspacepath,"")}return path};return IstanbulToFootprintsConverter}();exports.IstanbulToFootprintsConverter=IstanbulToFootprintsConverter})},{"./utils":286}],270:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./browser-agent-instance","../../common/utils/validation-utils","../../common/events-process/events-creator","../../common/events-process/events-contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.KarmaHandler=void 0;var browser_agent_instance_1=require("./browser-agent-instance");var validation_utils_1=require("../../common/utils/validation-utils");var events_creator_1=require("../../common/events-process/events-creator");var events_contracts_1=require("../../common/events-process/events-contracts");var KarmaHandler=function(){function KarmaHandler(window,agent,logger){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(window,"window");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agent,"agent");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this.window=window;this.agent=agent;this.logger=logger}KarmaHandler.prototype.overrideKarmaMethods=function(){if(!this.window.__karma__){this.logger.warn("Could not find '__karma__' object on window, skip overriding methods");return}var that=this;var originalResult=this.window.__karma__.result;var originalComplete=this.window.__karma__.complete;this.window.__karma__.result=function(resultObject){var testResult=that.resolveTestResult(resultObject);var testStartEvent=events_creator_1.EventsCreator.createTestStartedEvent(browser_agent_instance_1.BrowserAgentInstance.getExecutionId(),"karma",resultObject.fullName,resultObject.time);var testEndEvent=events_creator_1.EventsCreator.createTestEndEvent(browser_agent_instance_1.BrowserAgentInstance.getExecutionId(),"karma",resultObject.fullName,testResult,resultObject.time);that.agent.enqueueEvent(testStartEvent);that.agent.enqueueEvent(testEndEvent);var currentTestIdentifier=browser_agent_instance_1.BrowserAgentInstance.getExecutionId()+"/"+resultObject.fullName;that.agent.setCurrentTestIdentifier(currentTestIdentifier);if(originalResult instanceof Function){originalResult.apply(this,arguments)}};this.window.__karma__.complete=function(){var executionEndEvent=events_creator_1.EventsCreator.createEvent(events_contracts_1.EventTypes.ExecutionIdEnded,browser_agent_instance_1.BrowserAgentInstance.getExecutionId(),"karma");that.agent.enqueueEvent(executionEndEvent);that.agent.stop();if(originalComplete instanceof Function){originalComplete.apply(this,arguments)}}};KarmaHandler.prototype.start=function(){var agentStartedEvent=events_creator_1.EventsCreator.createEvent(events_contracts_1.EventTypes.AgentStarted,browser_agent_instance_1.BrowserAgentInstance.getExecutionId(),"karma");var executionStartedEvent=events_creator_1.EventsCreator.createEvent(events_contracts_1.EventTypes.ExecutionIdStarted,browser_agent_instance_1.BrowserAgentInstance.getExecutionId(),"karma");this.agent.enqueueEvent(agentStartedEvent);this.agent.enqueueEvent(executionStartedEvent)};KarmaHandler.prototype.resolveTestResult=function(result){if(result.skipped){return"skipped"}if(result.success){return"passed"}return"failed"};return KarmaHandler}();exports.KarmaHandler=KarmaHandler})},{"../../common/events-process/events-contracts":312,"../../common/events-process/events-creator":313,"../../common/utils/validation-utils":336,"./browser-agent-instance":250}],271:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../../common/system-date","../configuration-override"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConsoleLogger=exports.LogLevels=void 0;var system_date_1=require("../../../common/system-date");var configuration_override_1=require("../configuration-override");var LogLevels;(function(LogLevels){LogLevels["TRACE"]="trace";LogLevels["DEBUG"]="debug";LogLevels["INFO"]="info";LogLevels["WARNING"]="warning";LogLevels["ERROR"]="error";LogLevels["CRITICAL"]="critical";LogLevels["FATAL"]="fatal"})(LogLevels=exports.LogLevels||(exports.LogLevels={}));var ConsoleLogger=function(){function ConsoleLogger(level,selectedLogLevels){if(level===void 0){level=LogLevels.INFO}if(selectedLogLevels===void 0){selectedLogLevels=null}var _a,_b;this.level=level;this.selectedLogLevels=selectedLogLevels;this.logFn=function(){};this.stringifyFn=function(o){return""};this.context={};(_b=(_a=window.$Sealights)===null||_a===void 0?void 0:_a.configuration)===null||_b===void 0?void 0:_b.on(configuration_override_1.ConfigChangedEvents.LOG_LEVEL_CHANGED,this.initLogLevels.bind(this));if(!selectedLogLevels)this.initLogLevels(level);this.initStringifyFn();this.initLogFn()}ConsoleLogger.prototype.withLogLevel=function(level){var c=new ConsoleLogger(this.level);c.context=this.context;return c};ConsoleLogger.prototype.initLogFn=function(){var _this=this;if(console&&typeof console.log=="function"){this.logFn=function(o){var line=_this.stringifyFn(o);console.log(line)}}else{}};ConsoleLogger.prototype.initStringifyFn=function(){if(JSON&&typeof JSON.stringify=="function"){this.stringifyFn=JSON.stringify}else{this.stringifyFn=this.crudeStringifier}};ConsoleLogger.prototype.crudeStringifier=function(o){var strParts=Array();for(var p in o){strParts.push(p+"="+o[p].toString())}return strParts.join(", ")};ConsoleLogger.prototype.initLogLevels=function(level){var orderedLogLevels=[LogLevels.TRACE,LogLevels.DEBUG,LogLevels.INFO,LogLevels.WARNING,LogLevels.ERROR,LogLevels.CRITICAL,LogLevels.FATAL];var logLevel=level.toLowerCase();var minIdx=orderedLogLevels.indexOf(logLevel);if(minIdx===-1){this.handleLevelNotFound(level)}else{this.selectedLogLevels={};for(var i=0;i<orderedLogLevels.length;i++){this.selectedLogLevels[orderedLogLevels[i]]=i>=minIdx}}};ConsoleLogger.prototype.handleLevelNotFound=function(logLevel){if(logLevel=="off"){this.selectedLogLevels={}}};ConsoleLogger.prototype.internalLog=function(logLevel,logMsg,obj){if(!this.selectedLogLevels||!this.selectedLogLevels[logLevel])return;var logObject={level:logLevel.toUpperCase(),ts:system_date_1.getSystemDate().toISOString(),msg:logMsg?logMsg.toString():undefined};var ctx=this.context;for(var p in ctx){logObject[p]=ctx[p]}if(obj){if(obj instanceof Error){logObject.error=obj.toString()}else if(obj instanceof Object){for(var p in obj){logObject[p]=obj[p]}}else{logObject.data=obj}}this.logFn(logObject)};ConsoleLogger.prototype.clone=function(){var c=new ConsoleLogger(this.level,this.selectedLogLevels);var _t=this.context;for(var p in _t){c.context[p]=_t[p]}return c};ConsoleLogger.prototype.withClass=function(className){var c=this.clone();c.context.className=className;delete c.context.methodName;return c};ConsoleLogger.prototype.withMethod=function(methodName){var c=this.clone();c.context.methodName=methodName;return c};ConsoleLogger.prototype.withTx=function(tx){var c=this.clone();c.context.tx=tx;return c};ConsoleLogger.prototype.withComponent=function(componentName,componentVersion){var c=this.clone();c.context.componentName=componentName;c.context.componentVersion=componentVersion;return c};ConsoleLogger.prototype.withActivity=function(activityName){var c=this.clone();c.context.activityName=activityName;return c};ConsoleLogger.prototype.withProperty=function(propName,propValue){var c=this.clone();c.context[propName]=propValue;return c};ConsoleLogger.prototype.withProperties=function(objWithProperties,propNames){var c=this.clone();if(!propNames){propNames=Object.keys(objWithProperties)}propNames.forEach(function(pn){c.context[pn]=objWithProperties[pn]});return c};ConsoleLogger.prototype.fatal=function(logMsg,obj){this.internalLog(LogLevels.FATAL,logMsg,obj)};ConsoleLogger.prototype.critical=function(logMsg,obj){this.internalLog(LogLevels.CRITICAL,logMsg,obj)};ConsoleLogger.prototype.error=function(logMsg,obj){this.internalLog(LogLevels.ERROR,logMsg,obj)};ConsoleLogger.prototype.warn=function(logMsg,obj){this.internalLog(LogLevels.WARNING,logMsg,obj)};ConsoleLogger.prototype.info=function(logMsg,obj){this.internalLog(LogLevels.INFO,logMsg,obj)};ConsoleLogger.prototype.debug=function(logMsg,obj){this.internalLog(LogLevels.DEBUG,logMsg,obj)};ConsoleLogger.prototype.trace=function(logMsg,obj){this.internalLog(LogLevels.TRACE,logMsg,obj)};return ConsoleLogger}();exports.ConsoleLogger=ConsoleLogger})},{"../../../common/system-date":332,"../configuration-override":259}],272:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./null-logger","./console-logger"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.LogFactory=void 0;var null_logger_1=require("./null-logger");var console_logger_1=require("./console-logger");var LogFactory=function(){function LogFactory(){}LogFactory.createLogger=function(className,logLevel){try{var logger=new console_logger_1.ConsoleLogger(logLevel);logger.withClass(className);return logger}catch(e){return null_logger_1.NullLogger.INSTANCE}};return LogFactory}();exports.LogFactory=LogFactory})},{"./console-logger":271,"./null-logger":273}],273:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NullLogger=void 0;var NullLogger=function(){function NullLogger(){}NullLogger.prototype.fatal=function(logMsg,obj){};NullLogger.prototype.critical=function(logMsg,obj){};NullLogger.prototype.error=function(logMsg,obj){};NullLogger.prototype.warn=function(logMsg,obj){};NullLogger.prototype.info=function(logMsg,obj){};NullLogger.prototype.debug=function(logMsg,obj){};NullLogger.prototype.trace=function(logMsg,obj){};NullLogger.prototype.withClass=function(className){return NullLogger.INSTANCE};NullLogger.prototype.withMethod=function(methodName){return NullLogger.INSTANCE};NullLogger.prototype.withTx=function(tx){return NullLogger.INSTANCE};NullLogger.prototype.withComponent=function(componentName,componentVersion){return NullLogger.INSTANCE};NullLogger.prototype.withActivity=function(activityName){return NullLogger.INSTANCE};NullLogger.prototype.withProperty=function(propName,propValue){return NullLogger.INSTANCE};NullLogger.prototype.withProperties=function(objWithProperties,propNames){return NullLogger.INSTANCE};NullLogger.prototype.withLogLevel=function(level){return NullLogger.INSTANCE};NullLogger.INSTANCE=new NullLogger;return NullLogger}();exports.NullLogger=NullLogger})},{}],274:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../entities/footprints-item-data","../delegate","../../../common/system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsItemsQueue=void 0;var footprints_item_data_1=require("../entities/footprints-item-data");var delegate_1=require("../delegate");var system_date_1=require("../../../common/system-date");var FootprintsItemsQueue=function(){function FootprintsItemsQueue(configuration){this.maxItemsInQueue=500;this.queueSize=0;this.queue=new Array;this.onQueueFull=new delegate_1.Delegate;this.isQueueFull=function(){return this.getCurrentQueueSize()>=this.maxItemsInQueue};if(!configuration)throw new Error("'configuration' cannot be null or undefined");this.enabled=configuration.enabled;this.maxItemsInQueue=configuration.maxItemsInQueue}FootprintsItemsQueue.prototype.setEnabled=function(isEnabled){isEnabled=!!isEnabled;if(isEnabled!==this.enabled){this.enabled=isEnabled}if(!isEnabled){this.queue=new Array}};FootprintsItemsQueue.prototype.getEnabled=function(){return this.enabled};FootprintsItemsQueue.prototype.enqueueItem=function(footprintsItem){if(!this.enabled){return}footprintsItem=footprintsItem||new footprints_item_data_1.FootprintsItemData;footprintsItem.localTime=system_date_1.getSystemDateValueOf();this.queue.push(footprintsItem);this.queueSize++;this.checkQueueSize()};FootprintsItemsQueue.prototype.checkQueueSize=function(){if(this.isQueueFull()){this.onQueueFull.fire()}};FootprintsItemsQueue.prototype.getCurrentQueueSize=function(){return this.queueSize};FootprintsItemsQueue.prototype.requeueItems=function(footprintsItems){if(!this.enabled){return}var context=this;footprintsItems.forEach(function(item){context.queue.push(item);context.queueSize+=1});this.checkQueueSize()};FootprintsItemsQueue.prototype.getQueueContentsAndEmptyQueue=function(){var returnedItems=this.queue;this.queue=new Array;this.queueSize=0;return returnedItems};return FootprintsItemsQueue}();exports.FootprintsItemsQueue=FootprintsItemsQueue})},{"../../../common/system-date":332,"../delegate":261,"../entities/footprints-item-data":265}],275:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../../common/utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Queue=void 0;var validation_utils_1=require("../../../common/utils/validation-utils");var Queue=function(){function Queue(onQueueFull){this.queue=[];this._maxItemsInQueue=Queue.DEFAULT_MAX_ITEMS_IN_QUEUE;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(onQueueFull,"onQueueFull");this.onQueueFull=onQueueFull}Queue.prototype.requeue=function(items){if(!items||!items.length){return}this.queue=items.concat(this.queue)};Queue.prototype.enqueue=function(item){this.queue.push(item);if(this._maxItemsInQueue===this.queue.length){this.onQueueFull.fire()}};Queue.prototype.getQueueSize=function(){return this.queue.length};Queue.prototype.dequeue=function(size){if(!size){size=this.queue.length}if(this.queue.length===0){return[]}if(size>this.queue.length){size=this.queue.length}var dequeuedItems=this.queue.splice(0,size);return dequeuedItems};Queue.prototype.clear=function(){this.queue=[]};Queue.prototype.on=function(event,listener){this.onQueueFull.addListener(listener);return this};Object.defineProperty(Queue.prototype,"maxItemsInQueue",{get:function(){return this._maxItemsInQueue},set:function(value){this._maxItemsInQueue=value},enumerable:false,configurable:true});Queue.DEFAULT_MAX_ITEMS_IN_QUEUE=1e3;return Queue}();exports.Queue=Queue})},{"../../../common/utils/validation-utils":336}],276:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./http-response"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpClient=void 0;var http_response_1=require("./http-response");var HttpClient=function(){function HttpClient(window,featureDetection,logger){this.window=window;this.featureDetection=featureDetection;this.logger=logger;if(window==null)throw new Error("'window' cannot be null or undefined");if(featureDetection==null)throw new Error("'featureDetection' cannot be null or undefined")}HttpClient.prototype.send=function(request,onSuccess,onError){if(!request.url)return;var url=request.url;var httpMethod=request.httpMethod;var httpRequest=new XMLHttpRequest;httpRequest.open(httpMethod,url,request.async);if(request.headers){for(var i=0;i<request.headers.length;i++){var header=request.headers[i];if(header&&header.name&&header.value){httpRequest.setRequestHeader(header.name,header.value)}}}httpRequest.onreadystatechange=function(){if(httpRequest.readyState===XMLHttpRequest.DONE){var httpResponse=new http_response_1.HttpResponse;httpResponse.statusCode=httpRequest.status;httpResponse.responseText=httpRequest.responseText;if(httpRequest.status===200){if(onSuccess){onSuccess(httpResponse)}}else{if(onError){onError(httpResponse)}}}};httpRequest.send(request.data)};return HttpClient}();exports.HttpClient=HttpClient})},{"./http-response":278}],277:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpRequest=void 0;var HttpRequest=function(){function HttpRequest(){this.async=true}return HttpRequest}();exports.HttpRequest=HttpRequest})},{}],278:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpResponse=void 0;var HttpResponse=function(){function HttpResponse(){}return HttpResponse}();exports.HttpResponse=HttpResponse})},{}],279:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../../../common/utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.JsonClientAdapter=void 0;var validation_utils_1=require("../../../../common/utils/validation-utils");var JsonClientAdapter=function(){function JsonClientAdapter(jsonClient,serverUrl){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(jsonClient,"jsonClient");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(serverUrl,"serverUrl");this.jsonClient=jsonClient;this.serverUrl=serverUrl}JsonClientAdapter.prototype.delete=function(body,urlPath,callback){throw new Error("'delete' not implemented yet")};JsonClientAdapter.prototype.get=function(urlPath,callback,isNotFoundAcceptable,async){if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}if(async===void 0){async=false}urlPath=this.serverUrl+urlPath;var onSuccess=function(response){return callback(null,response,response.statusCode)};var onError=function(response){var error=new Error(response.responseText);callback(error,null,response.statusCode)};this.jsonClient.get(urlPath,onSuccess,onError,async)};JsonClientAdapter.prototype.put=function(requestData,urlPath,callback,async){if(async===void 0){async=true}throw new Error("'delete' not implemented yet")};JsonClientAdapter.prototype.post=function(requestData,urlPath,callback,async,contentType){if(async===void 0){async=true}urlPath=this.serverUrl+urlPath;var onSuccess=function(response){return callback(null,response,response.statusCode)};var onError=function(response){var error=new Error(response.responseText);callback(error,null,response.statusCode)};this.jsonClient.post(urlPath,requestData,onSuccess,onError,async,contentType)};JsonClientAdapter.prototype.postMultipart=function(requestData,urlPath,callback){throw new Error("'postMultipart' not implemented yet")};return JsonClientAdapter}();exports.JsonClientAdapter=JsonClientAdapter})},{"../../../../common/utils/validation-utils":336}],280:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../http/http-request","../../../../common/http/contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.JsonClient=void 0;var http_request_1=require("../http/http-request");var contracts_1=require("../../../../common/http/contracts");var JsonClient=function(){function JsonClient(httpClient,configuration,agentInstanceData){this.httpClient=httpClient;this.configuration=configuration;this.agentInstanceData=agentInstanceData;this.requestsInProgress=0;this.requestsInProgress=0}JsonClient.prototype.sendHttpRequest=function(request,onSuccess,onError,contentType){var context=this;try{this.requestsInProgress++;var httpRequest=new http_request_1.HttpRequest;httpRequest.headers=this.getHeaders(contentType);httpRequest.url=request.url;httpRequest.httpMethod=request.httpMethod;httpRequest.async=request.async;if(request.data!=null)httpRequest.data=JSON.stringify(request.data);this.httpClient.send(httpRequest,parseResponse,function(response){context.requestsInProgress--;if(onError!=null){onError(response)}})}catch(e){this.requestsInProgress--}function parseResponse(jsonResponse){try{var object=void 0;context.requestsInProgress--;if(jsonResponse&&jsonResponse.responseText&&jsonResponse.responseText!=""){object=JSON.parse(jsonResponse.responseText)}else{object=jsonResponse}if(onSuccess!=null){onSuccess(object)}}catch(e){if(onError!=null){jsonResponse.responseText="Failed parsing response. Response: '"+jsonResponse.responseText+"'";onError(jsonResponse)}}}};JsonClient.prototype.post=function(url,data,onSuccess,onError,async,contentType){if(async===void 0){async=true}this.send(url,data,onSuccess,onError,async,"POST",contentType)};JsonClient.prototype.get=function(url,onSuccess,onError,async,data){if(async===void 0){async=true}this.send(url,data,onSuccess,onError,async,"GET")};JsonClient.prototype.send=function(url,data,onSuccess,onError,async,httpMethod,contentType){if(async===void 0){async=true}
27
+ var request=new http_request_1.HttpRequest;request.url=url;request.data=data;request.httpMethod=httpMethod;request.async=async;this.sendHttpRequest(request,onSuccess,onError,contentType)};JsonClient.prototype.hasRequestsInProgress=function(){return this.requestsInProgress>0};JsonClient.prototype.getHeaders=function(contentType){var _a,_b;var headers=[{name:"Content-Type",value:contentType||contracts_1.ContentType.JSON}];headers.push({name:"sl-metadata",value:JSON.stringify(this.getSlMetadataHeaders())});if((_a=this===null||this===void 0?void 0:this.configuration)===null||_a===void 0?void 0:_a.token){headers.push({name:"Authorization",value:"Bearer "+((_b=this===null||this===void 0?void 0:this.configuration)===null||_b===void 0?void 0:_b.token)})}return headers};JsonClient.prototype.getSlMetadataHeaders=function(){var _a;return{agentId:this.agentInstanceData.agentId,buildSessionId:(_a=this.configuration)===null||_a===void 0?void 0:_a.buildSessionId,agentType:"browser"}};return JsonClient}();exports.JsonClient=JsonClient})},{"../../../../common/http/contracts":325,"../http/http-request":277}],281:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./json-client","../../logger/log-factory"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NoopJsonClient=void 0;var json_client_1=require("./json-client");var log_factory_1=require("../../logger/log-factory");var NoopJsonClient=function(_super){__extends(NoopJsonClient,_super);function NoopJsonClient(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.logger=log_factory_1.LogFactory.createLogger("NoopJsonClient");return _this}NoopJsonClient.prototype.send=function(url,data,onSuccess,onError,async,httpMethod,contentType){if(async===void 0){async=true}this.logger.info("noop json client not executing http request for url '"+url);onSuccess({})};return NoopJsonClient}(json_client_1.JsonClient);exports.NoopJsonClient=NoopJsonClient})},{"../../logger/log-factory":272,"./json-client":280}],282:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.LightBackendProxy=void 0;var LightBackendProxy=function(){function LightBackendProxy(configuration,jsonClient,logger){this.configuration=configuration;this.jsonClient=jsonClient;this.logger=logger}LightBackendProxy.prototype.submitRequest=function(request,onSuccess,onError,async){if(async===void 0){async=true}var url=this.createServerUrl(this.configuration);this.jsonClient.post(url,request,onSuccess,onError,async)};LightBackendProxy.prototype.hasRequestsInProgress=function(){return this.jsonClient.hasRequestsInProgress()};LightBackendProxy.prototype.getRequestsInProgressCount=function(){return this.jsonClient.requestsInProgress};LightBackendProxy.prototype.getSlMappingFromServer=function(buildSessionId){var _this=this;var url=[this.configuration.server,"v1","agents","blobs",buildSessionId].join("/")+"?view=concatJson";url=encodeURI(url);return new Promise(function(resolve,reject){_this.jsonClient.get(url,resolve,reject,false)})};LightBackendProxy.prototype.createServerUrl=function(configuration){if(configuration.token){var apiVersion=configuration.resolveWithoutHash?"/v5":"/v3";return configuration.server+apiVersion+"/agents/footprints/"}return configuration.server+"/v1/testfootprints/"};return LightBackendProxy}();exports.LightBackendProxy=LightBackendProxy})},{}],283:[function(require,module,exports){var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/agent-events/cockpit-notifier"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SlMappingLoader=void 0;var cockpit_notifier_1=require("../../common/agent-events/cockpit-notifier");var SlMappingLoader=function(){function SlMappingLoader(lightBackendProxy,window,logger){this.lightBackendProxy=lightBackendProxy;this.window=window;this.logger=logger}SlMappingLoader.prototype.loadSlMapping=function(buildSessionId){return __awaiter(this,void 0,void 0,function(){var flatted_1,slMappingArr,err_1,errMsg;return __generator(this,function(_a){switch(_a.label){case 0:this.window.slMappings=this.window.slMappings||{};if(!!this.window.slMappings[buildSessionId])return[3,4];_a.label=1;case 1:_a.trys.push([1,3,,4]);flatted_1={};return[4,this.lightBackendProxy.getSlMappingFromServer(buildSessionId)];case 2:slMappingArr=_a.sent();slMappingArr.forEach(function(mapping){flatted_1=__assign(__assign({},flatted_1),mapping)});this.window.slMappings[buildSessionId]=flatted_1;return[3,4];case 3:err_1=_a.sent();errMsg="Error while trying to load slMapping from server '"+err_1+"'";this.logger.error(errMsg);cockpit_notifier_1.CockpitNotifier.sendGenericMessage(errMsg);this.window.slMappings[buildSessionId]={};return[3,4];case 4:return[2]}})})};return SlMappingLoader}();exports.SlMappingLoader=SlMappingLoader})},{"../../common/agent-events/cockpit-notifier":294}],284:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./delegate","./contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StateTracker=void 0;var delegate_1=require("./delegate");var contracts_1=require("./contracts");var StateTracker=function(){function StateTracker(configuration,jsonClient,watchdog,logger){var _this=this;this.configuration=configuration;this.jsonClient=jsonClient;this.watchdog=watchdog;this.logger=logger;this.colorChanged=new delegate_1.Delegate;this.setCurrentTestIdentifier(StateTracker.ANONYMOUS_FOOTPRINTS_COLOR);this.watchdog.addOnAlarmListener(function(){_this.checkForActiveExecution()});this.checkForActiveExecution(false);this.watchdog.start()}StateTracker.prototype.setCurrentTestIdentifier=function(newColorOnWindow){if(newColorOnWindow!=null){if(newColorOnWindow!=StateTracker.ANONYMOUS_FOOTPRINTS_COLOR){this.stopWatchdog()}else{this.startWatchdog()}if(newColorOnWindow!=this.currentColorOnWindow){this.currentColorOnWindow=newColorOnWindow;this.colorChanged.fire()}}else if(this.currentColorOnWindow!=null&&newColorOnWindow==null){this.currentColorOnWindow=null;this.colorChanged.fire()}};StateTracker.prototype.getCurrentTestIdentifier=function(){return this.currentColorOnWindow};StateTracker.prototype.addOnColorChangedListener=function(listener){this.colorChanged.addListener(listener)};StateTracker.prototype.getCurrentColor=function(){return this.currentColorOnWindow};StateTracker.prototype.checkForActiveExecution=function(async){var _this=this;if(async===void 0){async=true}var url=this.configuration.server+("/v4/testExecution/"+this.configuration.labId);this.logger.info("[TO TST] - checkMappingStatus. Url '"+url+"'.");var onSuccess=function(data){_this.logger.info("[ACTIVE EXECUTION] Checking for active execution. No errors");if(data==null){_this.logger.warn("[ACTIVE EXECUTION] Received empty response. not sending footprints.");_this.hasActiveExecution=false;return}if(data.execution==null){_this.logger.info("[ACTIVE EXECUTION] Couldn't find active execution. not sending footprints.");_this.hasActiveExecution=false}else if(data.execution.status==contracts_1.ExecutionStatus.Ending){_this.logger.info("[ACTIVE EXECUTION] Execution is pending delete. sending last footprints");_this.hasActiveExecution=true}else if(data.execution.status==contracts_1.ExecutionStatus.InProgress){_this.logger.info("[ACTIVE EXECUTION] Active execution for labid '"+_this.configuration.labId+"'");_this.hasActiveExecution=true}else{_this.logger.warn("[ACTIVE EXECUTION] Unexpected status. status: ",data.execution.status);_this.hasActiveExecution=false}};var onError=function(response){_this.logger.error("[ACTIVE EXECUTION] Error checking for active execution: %s",response.responseText);_this.hasActiveExecution=false};this.jsonClient.get(url,onSuccess,onError,async)};StateTracker.prototype.shouldCollectFootprints=function(){if(this.getCurrentColor()==null){this.logger.info("Current test identifier is null, should not collect footprints");return false}if(this.getCurrentColor()!=StateTracker.ANONYMOUS_FOOTPRINTS_COLOR){this.logger.info("Not in anonymous footprints, should collect footprints");return true}if(this.hasActiveExecution){this.logger.info("Has active execution, should collect footprints");return true}this.logger.info("No active execution, should not collect footprints");return false};StateTracker.prototype.setActiveExecution=function(value){this.hasActiveExecution=value};StateTracker.prototype.stopWatchdog=function(){if(this.watchdog.getStatus().running){this.watchdog.stop()}};StateTracker.prototype.startWatchdog=function(){if(!this.watchdog.getStatus().running){this.watchdog.start()}};StateTracker.ANONYMOUS_FOOTPRINTS_COLOR="00000000-0000-0000-0000-000000000000/__init";return StateTracker}();exports.StateTracker=StateTracker})},{"./contracts":260,"./delegate":261}],285:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TestStateHelper=void 0;var TestStateHelper=function(){function TestStateHelper(){this.combineExecutionIdAndTestName=function(executionId,testName){testName=testName||"";if(!executionId)return"";return executionId+"/"+testName};this.splitTestIdToExecutionAndTestName=function(testId){testId=testId||"";var executionId=testId.split("/")[0];var testName=testId.indexOf("/")==-1?"":testId.substring(executionId.length+1);if(!executionId)testName="";return{executionId:executionId,testName:testName}}}return TestStateHelper}();exports.TestStateHelper=TestStateHelper})},{}],286:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","path"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Utils=void 0;var path=require("path");var Utils=function(){function Utils(){}Utils.adjustPathSlashes=function(path){path=(path||"").replace(/\\/g,"/");return path};Utils.getRelativeModulePath=function(path,workspacepath){workspacepath=Utils.adjustPathSlashes(workspacepath);path=Utils.adjustPathSlashes(path);if(workspacepath){return path.replace(workspacepath,"")}return path};Utils.resolveOriginalFullFileName=function(fullPath,originalFilename){if(path.isAbsolute(originalFilename)){return originalFilename}var generatedDir=path.dirname(fullPath);originalFilename=path.resolve(generatedDir,originalFilename);return originalFilename};Utils.parseBooleanValue=function(value){if(value&&typeof value=="boolean"){return value}if(value&&typeof value=="string"){return value.toLowerCase()=="true"}return false};return Utils}();exports.Utils=Utils})},{path:171}],287:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./delegate"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Watchdog=void 0;var delegate_1=require("./delegate");var Watchdog=function(){function Watchdog(timeout,timersWrapper,options,logger){this.timeout=timeout;this.timersWrapper=timersWrapper;this.options=options;this.logger=logger;this.handle=null;this.alarm=new delegate_1.Delegate;this.context=this;this.stopped=false;this.options=options||{}}Watchdog.prototype.abortTimer=function(){if(this.handle){this.timersWrapper.clearTimeout(this.handle);this.handle=null}};Watchdog.prototype.fireAlarm=function(){this.handle=null;try{this.alarm.fire()}catch(e){this.logger.error("Alarm caught an exception: %s",e)}if(this.options.autoReset){this.context.reset()}};Watchdog.prototype.addOnAlarmListener=function(listener){this.alarm.addListener(listener)};Watchdog.prototype.reset=function(){var _this=this;this.abortTimer();if(!this.stopped){this.handle=this.timersWrapper.setTimeout(function(){_this.fireAlarm()},this.timeout)}};Watchdog.prototype.stop=function(){this.stopped=true;this.abortTimer()};Watchdog.prototype.start=function(){this.stopped=false;this.reset()};Watchdog.prototype.getStatus=function(){return{running:!this.stopped}};Watchdog.prototype.on=function(event,listener){this.addOnAlarmListener(listener)};Watchdog.prototype.setInterval=function(newInterval){if(newInterval<=0)throw new Error("Invalid value for interval: "+newInterval);this.timeout=newInterval};return Watchdog}();exports.Watchdog=Watchdog})},{"./delegate":261}],288:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.WindowTimersWrapper=void 0;var WindowTimersWrapper=function(){function WindowTimersWrapper(window){this.window=window;if(!this.window)throw new Error("'window' cannot be null or undefined")}WindowTimersWrapper.prototype.clearInterval=function(handle){this.window.clearInterval(handle)};WindowTimersWrapper.prototype.clearTimeout=function(handle){this.window.clearTimeout(handle)};WindowTimersWrapper.prototype.setInterval=function(handler,timeout){var args=[];for(var _i=2;_i<arguments.length;_i++){args[_i-2]=arguments[_i]}return this.window.setInterval(handler,timeout,args)};WindowTimersWrapper.prototype.setTimeout=function(handler,timeout){var args=[];for(var _i=2;_i<arguments.length;_i++){args[_i-2]=arguments[_i]}return this.window.setTimeout(handler,timeout,args)};return WindowTimersWrapper}();exports.WindowTimersWrapper=WindowTimersWrapper})},{}],289:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Technology=exports.AgentEventCode=exports.AgentType=void 0;var AgentType;(function(AgentType){AgentType["BUILD_SCANNER"]="BuildScanner";AgentType["TEST_LISTENER"]="TestListener";AgentType["PRODUCTION_LISTENER"]="ProductionListener";AgentType["BROWSER_AGENT"]="BrowserAgent";AgentType["SLNODEJS"]="slnodejs"})(AgentType=exports.AgentType||(exports.AgentType={}));var AgentEventCode;(function(AgentEventCode){AgentEventCode[AgentEventCode["GENERIC_AGENT_EVENT"]=1e3]="GENERIC_AGENT_EVENT";AgentEventCode[AgentEventCode["AGENT_STARTED"]=1001]="AGENT_STARTED";AgentEventCode[AgentEventCode["AGENT_SHUTDOWN"]=1002]="AGENT_SHUTDOWN";AgentEventCode[AgentEventCode["AGENT_PING"]=1003]="AGENT_PING";AgentEventCode[AgentEventCode["AGENT_CONFIG_CHANGED"]=1004]="AGENT_CONFIG_CHANGED";AgentEventCode[AgentEventCode["FIRST_COVERAGE_INSTRUMENTATION_PERFORMED"]=1005]="FIRST_COVERAGE_INSTRUMENTATION_PERFORMED";AgentEventCode[AgentEventCode["FIRST_TIME_HAS_EXECUTION"]=1006]="FIRST_TIME_HAS_EXECUTION";AgentEventCode[AgentEventCode["FIRST_TIME_NO_EXECUTION"]=1007]="FIRST_TIME_NO_EXECUTION";AgentEventCode[AgentEventCode["AGENT_MUTED"]=1008]="AGENT_MUTED";AgentEventCode[AgentEventCode["AGENT_UNMUTED"]=1009]="AGENT_UNMUTED";AgentEventCode[AgentEventCode["FIRST_TIME_COLLECTED_FP"]=1010]="FIRST_TIME_COLLECTED_FP";AgentEventCode[AgentEventCode["GENERIC_MESSAGE"]=2e3]="GENERIC_MESSAGE";AgentEventCode[AgentEventCode["GENERIC_MESSAGE_SUPERUSER"]=2999]="GENERIC_MESSAGE_SUPERUSER";AgentEventCode[AgentEventCode["WARN"]=3e3]="WARN";AgentEventCode[AgentEventCode["AGENT_DID_NOT_SHUTDOWN"]=3001]="AGENT_DID_NOT_SHUTDOWN";AgentEventCode[AgentEventCode["GENERIC_WARNING_SUPERUSER"]=3999]="GENERIC_WARNING_SUPERUSER";AgentEventCode[AgentEventCode["GENERIC_ERROR"]=4e3]="GENERIC_ERROR";AgentEventCode[AgentEventCode["DUPLICATE_MODULE"]=4001]="DUPLICATE_MODULE";AgentEventCode[AgentEventCode["DATA_PROCESSOR_NO_EXECUTIONS"]=4002]="DATA_PROCESSOR_NO_EXECUTIONS";AgentEventCode[AgentEventCode["DATA_PROCESSOR_INVALID_FORMAT"]=4003]="DATA_PROCESSOR_INVALID_FORMAT";AgentEventCode[AgentEventCode["DATA_PROCESSOR_EMPTY_DATA"]=4004]="DATA_PROCESSOR_EMPTY_DATA";AgentEventCode[AgentEventCode["BUILD_MAP_SUBMISSION_ERROR"]=4005]="BUILD_MAP_SUBMISSION_ERROR";AgentEventCode[AgentEventCode["FOOTPRINTS_SUBMISSION_ERROR"]=4006]="FOOTPRINTS_SUBMISSION_ERROR";AgentEventCode[AgentEventCode["TEST_EVENTS_SUBMISSION_ERROR"]=4007]="TEST_EVENTS_SUBMISSION_ERROR";AgentEventCode[AgentEventCode["EXTERNAL_DATA_PROCESSOR_SUBMISSION_ERROR"]=4008]="EXTERNAL_DATA_PROCESSOR_SUBMISSION_ERROR";AgentEventCode[AgentEventCode["UNSUPPORTED_OS"]=4009]="UNSUPPORTED_OS";AgentEventCode[AgentEventCode["UNSUPPORTED_RUNTIME"]=4010]="UNSUPPORTED_RUNTIME";AgentEventCode[AgentEventCode["THIRD_PARTY_PACKAGE_DETECTED"]=4011]="THIRD_PARTY_PACKAGE_DETECTED";AgentEventCode[AgentEventCode["THIRD_PARTY_FILE_DETECTED"]=4012]="THIRD_PARTY_FILE_DETECTED";AgentEventCode[AgentEventCode["FOOTPRINTS_LOSS"]=4999]="FOOTPRINTS_LOSS";AgentEventCode[AgentEventCode["LEAST_VERBOSE_LOG"]=5001]="LEAST_VERBOSE_LOG";AgentEventCode[AgentEventCode["MOST_VERBOSE_LOG"]=5999]="MOST_VERBOSE_LOG"})(AgentEventCode=exports.AgentEventCode||(exports.AgentEventCode={}));var Technology;(function(Technology){Technology["NODEJS"]="nodejs";Technology["BROWSER"]="browser"})(Technology=exports.Technology||(exports.Technology={}))})},{}],290:[function(require,module,exports){var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-events-conracts","./agent-instance-info-builder","./machine-info-builder","./nodejs-env-info-builder","./agent-start-info-builder","./ci-info-builder","../http/backend-proxy","../utils/validation-utils","../watchdog","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentEventsController=void 0;var agent_events_conracts_1=require("./agent-events-conracts");var agent_instance_info_builder_1=require("./agent-instance-info-builder");var machine_info_builder_1=require("./machine-info-builder");var nodejs_env_info_builder_1=require("./nodejs-env-info-builder");var agent_start_info_builder_1=require("./agent-start-info-builder");var ci_info_builder_1=require("./ci-info-builder");var backend_proxy_1=require("../http/backend-proxy");var validation_utils_1=require("../utils/validation-utils");var watchdog_1=require("../watchdog");var system_date_1=require("../system-date");var AgentEventsController=function(){function AgentEventsController(agentConfig,agentInstanceData,logger,backendProxy,tool){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentConfig,"agentConfig");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentInstanceData,"agentInstanceData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this._agentConfig=agentConfig;this._logger=logger;this._agentInstanceData=agentInstanceData;this.shutDownRetries=0;this.backendProxy=backendProxy||this.createBackendProxy();this.addTool(tool);this.initWatchdog();this.submittedEventsMap=new Map}AgentEventsController.prototype.submitAgentStartedEvent=function(packageJsonFile){return __awaiter(this,void 0,void 0,function(){var event,result;return __generator(this,function(_a){switch(_a.label){case 0:this.startRequestStatus=StartRequestStatus.PENDING;event=this.buildAgentStartEvent(packageJsonFile||{});return[4,this.submitAgentEventRequest(event)];case 1:result=_a.sent();this.startRequestStatus=result?StartRequestStatus.SUCCEED:StartRequestStatus.FAILED;if(this.startRequestStatus!==StartRequestStatus.SUCCEED){this._logger.info("Agent start event failed to submit - ping events will not be sent")}else{this._pingWatchdog.start()}return[2]}})})};AgentEventsController.prototype.submitAgentEventRequest=function(event){return __awaiter(this,void 0,void 0,function(){var request,e_1;return __generator(this,function(_a){switch(_a.label){case 0:request={agentId:this._agentInstanceData.agentId,events:Array.isArray(event)?event:[event],appName:this._agentConfig.appName.value,buildSessionId:this._agentConfig.buildSessionId.value};_a.label=1;case 1:_a.trys.push([1,3,,4]);return[4,this.backendProxy.submitAgentEvent(request)];case 2:_a.sent();this._logger.info("Submitted '"+request.events.length+"' events successfully");return[2,true];case 3:e_1=_a.sent();this._logger.warn("Failed to submit '"+request.events.length+"' events. Error "+e_1);return[2,false];case 4:return[2]}})})};AgentEventsController.prototype.buildAgentStartEvent=function(packageJsonFile){var agentInstanceInfoBuilder=new agent_instance_info_builder_1.AgentInstanceInfoBuilder(this);var machineInfoBuilder=new machine_info_builder_1.MachineInfoBuilder;var dependencies=__assign(__assign({},packageJsonFile.dependencies),packageJsonFile.devDependencies);var nodejsEnvInfoBuilder=new nodejs_env_info_builder_1.NodejsEnvInfoBuilder(dependencies);var ciInfoBuilder=new ci_info_builder_1.CiInfoBuilder;var agentStartInfoBuilder=new agent_start_info_builder_1.AgentStartInfoBuilder(agentInstanceInfoBuilder,machineInfoBuilder,nodejsEnvInfoBuilder,ciInfoBuilder);var agentStartInfo=agentStartInfoBuilder.build();return this.buildEvent(agent_events_conracts_1.AgentEventCode.AGENT_STARTED,agentStartInfo)};AgentEventsController.prototype.buildAgentShutdownEvent=function(){return this.buildEvent(agent_events_conracts_1.AgentEventCode.AGENT_SHUTDOWN)};AgentEventsController.prototype.submitAgentShutdownEvent=function(){return __awaiter(this,void 0,void 0,function(){var event;var _this=this;return __generator(this,function(_a){this.shutDownRetries++;if(this.startRequestStatus==StartRequestStatus.FAILED){this._logger.debug("Agent start not submitted - not sending shut down events");return[2]}if(this.shutDownRetries>AgentEventsController.MAX_SHUTDOWN_RETRIES){this._logger.debug("Stop trying to send shutdown event after 60 seconds ");return[2]}this._pingWatchdog.stop();event=this.buildAgentShutdownEvent();if(this.startRequestStatus==StartRequestStatus.PENDING){setTimeout(function(){return _this.submitAgentShutdownEvent.call(_this)},1e3)}else{return[2,this.submitAgentEventRequest(event)]}return[2]})})};AgentEventsController.prototype.submitPingEvent=function(){return this.submitEvent(agent_events_conracts_1.AgentEventCode.AGENT_PING)};AgentEventsController.prototype.submitEvent=function(code){var _this=this;this.submittedEventsMap.set(code,true);this._logger.debug("About to send event with code '"+code+"', current time: "+system_date_1.getSystemDateValueOf());var event=this.buildEvent(code);this.submitAgentEventRequest(event).then(function(){return _this._logger.debug("Event with code '"+code+"' submitted successfully")})};AgentEventsController.prototype.submitEventOnce=function(code){if(!this.submittedEventsMap.get(code)){this.submitEvent(code)}};AgentEventsController.prototype.submitGenericMessage=function(message){this.sendMessage(message,agent_events_conracts_1.AgentEventCode.GENERIC_MESSAGE)};AgentEventsController.prototype.submitWarning=function(message){this.sendMessage(message,agent_events_conracts_1.AgentEventCode.WARN)};AgentEventsController.prototype.submitError=function(message){this.sendMessage(message,agent_events_conracts_1.AgentEventCode.GENERIC_ERROR)};AgentEventsController.prototype.submitErrorsBatch=function(messages){var _this=this;if(!messages||!messages.length){return}var events=messages.map(function(msg){return _this.buildEvent(agent_events_conracts_1.AgentEventCode.GENERIC_ERROR,msg)});this.submitAgentEventRequest(events).then(function(){return _this.logger.debug("'"+events.length+"' events were submitted successfully")})};AgentEventsController.prototype.sendMessage=function(message,code){var _this=this;this.logger.debug("About to send message '"+message+"' with code '"+code+"', current time: "+system_date_1.getSystemDateValueOf());var messageEvent=this.buildEvent(code,message);this.submitAgentEventRequest(messageEvent).then(function(){return _this.logger.debug("Message submitted successfully")})};AgentEventsController.prototype.submitConfigChanged=function(){var _this=this;var messageEvent=this.buildEvent(agent_events_conracts_1.AgentEventCode.AGENT_CONFIG_CHANGED,this._agentConfig.toJsonObject());this.submitAgentEventRequest(messageEvent).then(function(){return _this.logger.debug("Config changed event submitted successfully")})};Object.defineProperty(AgentEventsController.prototype,"watchdog",{get:function(){return this._pingWatchdog},enumerable:false,configurable:true});Object.defineProperty(AgentEventsController.prototype,"agentConfig",{get:function(){return this._agentConfig},enumerable:false,configurable:true});Object.defineProperty(AgentEventsController.prototype,"logger",{get:function(){return this._logger},enumerable:false,configurable:true});Object.defineProperty(AgentEventsController.prototype,"tools",{get:function(){return this._tools},enumerable:false,configurable:true});AgentEventsController.prototype.resolveTags=function(){return[]};AgentEventsController.prototype.addTool=function(tollInfo){if(!tollInfo)return;this._tools=this._tools||[];this._tools.push(tollInfo)};AgentEventsController.prototype.createBackendProxy=function(){var httpConfig={token:this._agentConfig.token.value,proxy:this._agentConfig.proxy.value,server:this._agentConfig.server.value,compressRequests:this._agentConfig.gzip.value};return new backend_proxy_1.BackendProxy(this._agentInstanceData,httpConfig,this._logger)};AgentEventsController.prototype.initWatchdog=function(){var watchdogOptions={interval:AgentEventsController.PING_INTERVAL,name:"AgentEventsWatchdog",autoReset:true,unref:true};var timers=this.getTimers();this._pingWatchdog=new watchdog_1.Watchdog(watchdogOptions,timers);this._pingWatchdog.on("alarm",this.submitPingEvent.bind(this))};AgentEventsController.prototype.getTimers=function(){if(this._agentInstanceData.technology===agent_events_conracts_1.Technology.BROWSER){return{setTimeout:setTimeout.bind(window),clearTimeout:clearTimeout.bind(window)}}else{return{setTimeout:setTimeout,clearTimeout:clearTimeout}}}
28
+ ;AgentEventsController.prototype.buildEvent=function(type,data){return{type:type,utcTimestamp_ms:system_date_1.getSystemDateValueOf(),data:data}};Object.defineProperty(AgentEventsController.prototype,"agentInstanceData",{get:function(){return this._agentInstanceData},enumerable:false,configurable:true});AgentEventsController.PING_INTERVAL=2*60*1e3;AgentEventsController.MAX_SHUTDOWN_RETRIES=60;return AgentEventsController}();exports.AgentEventsController=AgentEventsController;var StartRequestStatus;(function(StartRequestStatus){StartRequestStatus["FAILED"]="failed";StartRequestStatus["SUCCEED"]="succeed";StartRequestStatus["PENDING"]="pending"})(StartRequestStatus||(StartRequestStatus={}))})},{"../http/backend-proxy":324,"../system-date":332,"../utils/validation-utils":336,"../watchdog":337,"./agent-events-conracts":289,"./agent-instance-info-builder":291,"./agent-start-info-builder":292,"./ci-info-builder":293,"./machine-info-builder":296,"./nodejs-env-info-builder":297}],291:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./sensitive-data-filter"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentInstanceInfoBuilder=void 0;var sensitive_data_filter_1=require("./sensitive-data-filter");var SEALIGHTS_ENV_VAR_PREFIX="SL_";var AgentInstanceInfoBuilder=function(){function AgentInstanceInfoBuilder(agentEventsController){this.sendsPing=true;this.agentConfig=agentEventsController.agentConfig;this.agentId=agentEventsController.agentInstanceData.agentId;this.agentType=agentEventsController.agentInstanceData.agentType;this.tags=agentEventsController.resolveTags();this.tools=agentEventsController.tools;this.logger=agentEventsController.logger;this.technology=agentEventsController.agentInstanceData.technology;this.info={agentId:agentEventsController.agentInstanceData.agentId,agentType:agentEventsController.agentInstanceData.agentType,agentVersion:agentEventsController.agentInstanceData.agentVersion,technology:agentEventsController.agentInstanceData.technology}}AgentInstanceInfoBuilder.prototype.fillData=function(){this.info.tags=this.tags;this.info.tools=this.tools;this.info.technology=this.technology;this.info.sendsPing=this.sendsPing;this.fillFromAgentConfig();this.fillFromProcessObject()};AgentInstanceInfoBuilder.prototype.build=function(){this.fillData();return this.info};AgentInstanceInfoBuilder.prototype.fillFromAgentConfig=function(){this.info.buildSessionId=this.agentConfig.buildSessionId.value;this.info.labId=this.agentConfig.labId.value;this.info.agentConfig=this.agentConfig.toJsonObject()};AgentInstanceInfoBuilder.prototype.fillFromProcessObject=function(){this.info.processId=process.pid;this.info.processArch=process.arch;this.info.argv=process.argv;this.info.cwd=process.cwd();this.info.envVars=this.extractSealightsEnvVars()};AgentInstanceInfoBuilder.prototype.extractSealightsEnvVars=function(){var _this=this;var slEnvVars={};Object.keys(process.env).forEach(function(key){if(key.indexOf(SEALIGHTS_ENV_VAR_PREFIX)===0){slEnvVars[key]=sensitive_data_filter_1.isSensitive(key,process.env[key],_this.logger)?AgentInstanceInfoBuilder.SECRET_VALUE_PLACEHOLDER:process.env[key]}});return slEnvVars};AgentInstanceInfoBuilder.DEFAULT_BROWSER_AGENT_VERSION="1.0.0";AgentInstanceInfoBuilder.SEALIGHTS_WINDOW_OBJECT="$Sealights";AgentInstanceInfoBuilder.SECRET_VALUE_PLACEHOLDER="********";return AgentInstanceInfoBuilder}();exports.AgentInstanceInfoBuilder=AgentInstanceInfoBuilder})}).call(this)}).call(this,require("_process"))},{"./sensitive-data-filter":298,_process:179}],292:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentStartInfoBuilder=void 0;var AgentStartInfoBuilder=function(){function AgentStartInfoBuilder(agentInstanceInfoBuilder,machineInfoBuilder,techSpecificInfoBuilder,ciInfoBuilder){this.agentInstanceInfoBuilder=agentInstanceInfoBuilder;this.machineInfoBuilder=machineInfoBuilder;this.techSpecificInfoBuilder=techSpecificInfoBuilder;this.ciInfoBuilder=ciInfoBuilder}AgentStartInfoBuilder.prototype.fillData=function(){};AgentStartInfoBuilder.prototype.build=function(){return{agentInfo:this.agentInstanceInfoBuilder.build(),machineInfo:this.machineInfoBuilder.build(),techSpecificInfo:this.techSpecificInfoBuilder.build(),ciInfo:this.ciInfoBuilder.build()}};return AgentStartInfoBuilder}();exports.AgentStartInfoBuilder=AgentStartInfoBuilder})},{}],293:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CiInfoBuilder=void 0;var JENKINS_JOB_NAME_ENV="JOB_NAME";var JENKINS_JOB_ID_ENV="BUILD_ID";var JENKINS_JOB_URL_ENV="BUILD_URL";var CiInfoBuilder=function(){function CiInfoBuilder(){this.info={}}CiInfoBuilder.prototype.fillData=function(){if(this.isJenkins()){this.info.jobId=process.env[JENKINS_JOB_ID_ENV];this.info.jobName=process.env[JENKINS_JOB_NAME_ENV];this.info.jobUrl=process.env[JENKINS_JOB_URL_ENV]}};CiInfoBuilder.prototype.isJenkins=function(){return process.env[JENKINS_JOB_ID_ENV]&&process.env[JENKINS_JOB_NAME_ENV]&&process.env[JENKINS_JOB_URL_ENV]};CiInfoBuilder.prototype.build=function(){this.fillData();return this.info};return CiInfoBuilder}();exports.CiInfoBuilder=CiInfoBuilder})}).call(this)}).call(this,require("_process"))},{_process:179}],294:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-events-controller","./dry-run-agent-events-controller"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CockpitNotifier=void 0;var agent_events_controller_1=require("./agent-events-controller");var dry_run_agent_events_controller_1=require("./dry-run-agent-events-controller");var CockpitNotifier=function(){function CockpitNotifier(){}CockpitNotifier.notifyStart=function(agentConfig,agentInstanceData,logger,packageJsonFile,backendProxy,tool){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:CockpitNotifier.controller=new agent_events_controller_1.AgentEventsController(agentConfig,agentInstanceData,logger,backendProxy,tool);return[4,CockpitNotifier.controller.submitAgentStartedEvent(packageJsonFile)];case 1:_a.sent();return[2]}})})};CockpitNotifier.notifyShutdown=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:CockpitNotifier.verifyControllerInitialized();return[4,CockpitNotifier.controller.submitAgentShutdownEvent()];case 1:_a.sent();return[2]}})})};CockpitNotifier.sendGenericMessage=function(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitGenericMessage(message)};CockpitNotifier.sendWarning=function(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitWarning(message)};CockpitNotifier.sendError=function(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitError(message)};CockpitNotifier.sendErrorsBatch=function(messages){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitErrorsBatch(messages)};CockpitNotifier.sendEvent=function(code){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitEvent(code)};CockpitNotifier.sendEventOnce=function(code){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitEventOnce(code)};CockpitNotifier.verifyControllerInitialized=function(){if(!CockpitNotifier.controller&&!CockpitNotifier.isDryRunMode){throw new Error("'Agent started' event was not sent. Disabling!")}};CockpitNotifier.reset=function(){CockpitNotifier.controller=undefined;CockpitNotifier.controllerNullLogged=false;CockpitNotifier.isDryRunMode=false};CockpitNotifier.setDryRunMode=function(logger,proxy){CockpitNotifier.isDryRunMode=true;CockpitNotifier.controller=new dry_run_agent_events_controller_1.DryRunAgentEventsController(logger,proxy)};CockpitNotifier.controllerNullLogged=false;return CockpitNotifier}();exports.CockpitNotifier=CockpitNotifier})},{"./agent-events-controller":290,"./dry-run-agent-events-controller":295}],295:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-events-conracts","./agent-events-controller","../config-process/config","../agent-instance-data"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DryRunAgentEventsController=void 0;var agent_events_conracts_1=require("./agent-events-conracts");var agent_events_controller_1=require("./agent-events-controller");var config_1=require("../config-process/config");var agent_instance_data_1=require("../agent-instance-data");var DryRunAgentEventsController=function(_super){__extends(DryRunAgentEventsController,_super);function DryRunAgentEventsController(logger,proxy){return _super.call(this,new config_1.AgentConfig,new agent_instance_data_1.AgentInstanceData(agent_events_conracts_1.AgentType.SLNODEJS,agent_events_conracts_1.Technology.NODEJS),logger,proxy,null)||this}DryRunAgentEventsController.prototype.submitAgentStartedEvent=function(packageJsonFile){return Promise.resolve(undefined)};return DryRunAgentEventsController}(agent_events_controller_1.AgentEventsController);exports.DryRunAgentEventsController=DryRunAgentEventsController})},{"../agent-instance-data":299,"../config-process/config":302,"./agent-events-conracts":289,"./agent-events-controller":290}],296:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","os","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MachineInfoBuilder=void 0;var os=require("os");var system_date_1=require("../system-date");var MachineInfoBuilder=function(){function MachineInfoBuilder(){this.info={}}MachineInfoBuilder.prototype.fillData=function(){var currentDate=system_date_1.getSystemDate();this.info.machineName=os.hostname();this.info.arch=os.arch();this.info.os=os.platform();this.info.localDateTime=currentDate.toString();this.info.localDateTimeUnix_s=currentDate.getTime();this.info.runtime=process.version;this.info.ipAddress=this.extractIpAddresses()};MachineInfoBuilder.prototype.build=function(){this.fillData();return this.info};MachineInfoBuilder.prototype.extractIpAddresses=function(){var ipAddresses=[];var interfaces=os.networkInterfaces();Object.keys(interfaces).forEach(function(key){var addressesArr=interfaces[key];ipAddresses=ipAddresses.concat(addressesArr.map(function(addressObject){return addressObject.address}))});return ipAddresses};return MachineInfoBuilder}();exports.MachineInfoBuilder=MachineInfoBuilder})}).call(this)}).call(this,require("_process"))},{"../system-date":332,_process:179,os:154}],297:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NodejsEnvInfoBuilder=void 0;var NodejsEnvInfoBuilder=function(){function NodejsEnvInfoBuilder(dependencies){this.info={};this.dependencies=dependencies||{}}NodejsEnvInfoBuilder.prototype.fillData=function(){this.info.indexJsonDeps=this.dependencies;this.info.nodeVersion=process.versions.node};NodejsEnvInfoBuilder.prototype.build=function(){this.fillData();return this.info};return NodejsEnvInfoBuilder}();exports.NodejsEnvInfoBuilder=NodejsEnvInfoBuilder})}).call(this)}).call(this,require("_process"))},{_process:179}],298:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isSensitive=void 0;var secretKeysRegexes={"Slack Token":"(xox[p|b|o|a]-[0-9]{12}-[0-9]{12}-[0-9]{12}-[a-z0-9]{32})","RSA private key":"-----BEGIN RSA PRIVATE KEY-----","SSH (DSA) private key":"-----BEGIN DSA PRIVATE KEY-----","SSH (EC) private key":"-----BEGIN EC PRIVATE KEY-----","PGP private key block":"-----BEGIN PGP PRIVATE KEY BLOCK-----","Amazon AWS Access Key ID":"AKIA[0-9A-Z]{16}","Amazon MWS Auth Token":"amzn\\.mws\\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}","AWS API Key":"AKIA[0-9A-Z]{16}","Facebook Access Token":"EAACEdEose0cBA[0-9A-Za-z]+","Facebook OAuth":"[f|F][a|A][c|C][e|E][b|B][o|O][o|O][k|K].*['|\"][0-9a-f]{32}['|\"]",GitHub:"[g|G][i|I][t|T][h|H][u|U][b|B].*['|\"][0-9a-zA-Z]{35,40}['|\"]","Generic API Key":"[a|A][p|P][i|I][_]?[k|K][e|E][y|Y].*['|\"][0-9a-zA-Z]{32,45}['|\"]","Generic Secret":"[s|S][e|E][c|C][r|R][e|E][t|T].*['|\"][0-9a-zA-Z]{32,45}['|\"]","Google API Key":"AIza[0-9A-Za-z\\-_]{35}","Google Cloud Platform API Key":"AIza[0-9A-Za-z\\-_]{35}","Google Cloud Platform OAuth":"[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com","Google Drive API Key":"AIza[0-9A-Za-z\\-_]{35}","Google Drive OAuth":"[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com","Google (GCP) Service-account":'"type": "service_account"',"Google Gmail API Key":"AIza[0-9A-Za-z\\-_]{35}","Google Gmail OAuth":"[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com","Google OAuth Access Token":"ya29\\.[0-9A-Za-z\\-_]+","Google YouTube API Key":"AIza[0-9A-Za-z\\-_]{35}","Google YouTube OAuth":"[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com","Heroku API Key":"[h|H][e|E][r|R][o|O][k|K][u|U].*[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}","MailChimp API Key":"[0-9a-f]{32}-us[0-9]{1,2}","Mailgun API Key":"key-[0-9a-zA-Z]{32}","Password in URL":"[a-zA-Z]{3,10}://[^/\\s:@]{3,20}:[^/\\s:@]{3,20}@.{1,100}[\"'\\s]","PayPal Braintree Access Token":"access_token\\$production\\$[0-9a-z]{16}\\$[0-9a-f]{32}","Picatic API Key":"sk_live_[0-9a-z]{32}","Slack Webhook":"https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}","Stripe API Key":"sk_live_[0-9a-zA-Z]{24}","Stripe Restricted API Key":"rk_live_[0-9a-zA-Z]{24}","Square Access Token":"sq0atp-[0-9A-Za-z\\-_]{22}","Square OAuth Secret":"sq0csp-[0-9A-Za-z\\-_]{43}","Twilio API Key":"SK[0-9a-fA-F]{32}","Twitter Access Token":"[t|T][w|W][i|I][t|T][t|T][e|E][r|R].*[1-9][0-9]+-[0-9a-zA-Z]{40}","Twitter OAuth":"[t|T][w|W][i|I][t|T][t|T][e|E][r|R].*['|\"][0-9a-zA-Z]{35,44}['|\"]"};function isSensitive(envVar,value,logger){for(var _i=0,_a=Object.entries(secretKeysRegexes);_i<_a.length;_i++){var _b=_a[_i],key=_b[0],regex=_b[1];if(new RegExp(regex).test(value)){logger.debug("Value for key "+envVar+" filtered out since it suspected to contains data fpr "+key);return true}}return false}exports.isSensitive=isSensitive})},{}],299:[function(require,module,exports){(function(__dirname){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","uuid","./agent-events/agent-events-conracts","./utils/files-utils","fs","./agent-events/agent-instance-info-builder"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentInstanceData=void 0;var uuid=require("uuid");var agent_events_conracts_1=require("./agent-events/agent-events-conracts");var files_utils_1=require("./utils/files-utils");var fs_1=require("fs");var agent_instance_info_builder_1=require("./agent-events/agent-instance-info-builder");var AgentInstanceData=function(){function AgentInstanceData(agentType,technology){this.agentType=agentType;this.technology=technology;this.agentId=uuid();this.agentVersion=this.resolveAgentVersion()}AgentInstanceData.prototype.resolveAgentVersion=function(){if(this.technology===agent_events_conracts_1.Technology.BROWSER){return this.resolveAgentVersionForBrowserAgent()}var packageJsonFilePath=files_utils_1.FilesUtils.findFileUp("package.json",__dirname);if(packageJsonFilePath){try{var packageJson=fs_1.readFileSync(packageJsonFilePath).toString();var parsed=JSON.parse(packageJson);return parsed.version}catch(e){console.warn("Failed to resolve agent version, Error: '"+e);return null}}return null};AgentInstanceData.prototype.resolveAgentVersionForBrowserAgent=function(){return window&&window[agent_instance_info_builder_1.AgentInstanceInfoBuilder.SEALIGHTS_WINDOW_OBJECT]&&window[agent_instance_info_builder_1.AgentInstanceInfoBuilder.SEALIGHTS_WINDOW_OBJECT].agentVersion||agent_instance_info_builder_1.AgentInstanceInfoBuilder.DEFAULT_BROWSER_AGENT_VERSION};return AgentInstanceData}();exports.AgentInstanceData=AgentInstanceData})}).call(this)}).call(this,"/tsOutputs/common")},{"./agent-events/agent-events-conracts":289,"./agent-events/agent-instance-info-builder":291,"./utils/files-utils":333,fs:69,uuid:506}],300:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./config-system","fs","jwt-decode","./config"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigLoader=void 0;var config_system_1=require("./config-system");var fs=require("fs");var jwtDecode=require("jwt-decode");var config_1=require("./config");var ConfigLoader=function(){function ConfigLoader(logger){this.logger=logger}ConfigLoader.prototype.loadAgentConfiguration=function(initialJsonConfig){var agentCfg=new config_1.AgentConfig;if(process.env.SL_CONFIGURATION){try{var jsonCfg=JSON.parse(process.env.SL_CONFIGURATION);agentCfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(jsonCfg))}catch(e){console.error("Error parsing agent configuration %s",e)}}agentCfg.loadConfiguration(new config_system_1.EnvVariableConfigurationProvider("SL_"));if(initialJsonConfig){agentCfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(initialJsonConfig))}if(!agentCfg.token.hasValue&&agentCfg.tokenFile.hasValue){try{agentCfg.token.value=fs.readFileSync(agentCfg.tokenFile.value).toString()}catch(err){}}if(agentCfg.token.hasValue){this.loadConfigFromToken(agentCfg,agentCfg.token.value)}this.printConfiguration(agentCfg);return agentCfg};ConfigLoader.prototype.printConfiguration=function(agentCfg){if(!this.logger)return;this.logger.info("****************************************************");this.logger.info("Current config");this.logger.info("****************************************************");this.logger.info(agentCfg.toJsonObject())};ConfigLoader.prototype.loadConfigFromToken=function(agentCfg,token){if(!token)return null;try{var tokenData=jwtDecode(token);if(!tokenData["x-sl-server"]){throw new Error("Token Is Invalid. Doesn't Contain Server")}if(!tokenData["subject"]){throw new Error("Token Is Invalid. Doesn't Contain Subject")}var customerId=tokenData["subject"];var subjectParts=tokenData["subject"].split("@");if(subjectParts.length>=1){customerId=subjectParts[0]}if(!agentCfg.server.hasValue){agentCfg.server.value=tokenData["x-sl-server"]}agentCfg.customerId.value=customerId}catch(err){}};return ConfigLoader}();exports.ConfigLoader=ConfigLoader})}).call(this)}).call(this,require("_process"))},{"./config":302,"./config-system":301,_process:179,fs:69,"jwt-decode":440}],301:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","fs"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BaseConfiguration=exports.BooleanConfigKey=exports.NumberConfigKey=exports.StringConfigKey=exports.AgentConfigKey=exports.JsonConfigFileConfigurationProvider=exports.ConfigProviderAggregator=exports.EnvVariableConfigurationProvider=exports.JsonObjectConfigurationProvider=void 0;var fs=require("fs");var JsonObjectConfigurationProvider=function(){function JsonObjectConfigurationProvider(configObject){this.configObject=configObject;this.configObject=configObject||{}}JsonObjectConfigurationProvider.prototype.getAllKeyValues=function(callback){return callback(null,this.configObject)};JsonObjectConfigurationProvider.prototype.getName=function(){return"JSON Object"};return JsonObjectConfigurationProvider}();exports.JsonObjectConfigurationProvider=JsonObjectConfigurationProvider;var EnvVariableConfigurationProvider=function(){function EnvVariableConfigurationProvider(prefix){this.prefix=prefix}EnvVariableConfigurationProvider.prototype.getAllKeyValues=function(callback){if(this.prefix){var ret={};for(var key in process.env){if(key.indexOf(this.prefix)==0){ret[key.substr(this.prefix.length)]=process.env[key]}}callback(null,ret)}else{return callback(null,process.env)}};EnvVariableConfigurationProvider.prototype.getName=function(){return"Environment Variables"};return EnvVariableConfigurationProvider}();exports.EnvVariableConfigurationProvider=EnvVariableConfigurationProvider;var ConfigProviderAggregator=function(){function ConfigProviderAggregator(providers){this.providers=providers;if(!providers)throw new Error("no provider was specified")}ConfigProviderAggregator.prototype.getAllKeyValues=function(callback){var flattenedConfiguration={};var remainingProviders=[].concat(this.providers);var attemptNext=function(){if(remainingProviders.length==0){return callback(null,flattenedConfiguration)}var nextProvider=remainingProviders.shift();nextProvider.getAllKeyValues(function(err,keysAndValues){if(err)return attemptNext();Object.keys(keysAndValues).forEach(function(k){if(!flattenedConfiguration.hasOwnProperty(k))flattenedConfiguration[k]=keysAndValues[k]});return attemptNext()})};attemptNext()};ConfigProviderAggregator.prototype.getName=function(){return"Aggregated config from multiple providers: "+this.providers.map(function(t){return t.getName()})};return ConfigProviderAggregator}();exports.ConfigProviderAggregator=ConfigProviderAggregator;var JsonConfigFileConfigurationProvider=function(){function JsonConfigFileConfigurationProvider(filename){this.filename=filename;if(!filename)throw new Error("filename is required")}JsonConfigFileConfigurationProvider.prototype.getAllKeyValues=function(callback){try{var cfg=JSON.parse(fs.readFileSync(this.filename).toString().trim());return callback(null,cfg)}catch(e){return callback(e,null)}};JsonConfigFileConfigurationProvider.prototype.getName=function(){return"Config filename: "+this.filename};return JsonConfigFileConfigurationProvider}();exports.JsonConfigFileConfigurationProvider=JsonConfigFileConfigurationProvider;var AgentConfigKey=function(){function AgentConfigKey(){}return AgentConfigKey}();exports.AgentConfigKey=AgentConfigKey;var StringConfigKey=function(){function StringConfigKey(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"string"};if(defaultValue!==undefined){this.value=defaultValue}}Object.defineProperty(StringConfigKey.prototype,"value",{get:function(){return this._value},set:function(value){this._value=value;this.hasValue=true},enumerable:false,configurable:true});StringConfigKey.prototype.loadFromRawData=function(s){this.value=s;this.hasValue=true};return StringConfigKey}();exports.StringConfigKey=StringConfigKey;var NumberConfigKey=function(){function NumberConfigKey(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"number"};if(defaultValue!==undefined){this.value=defaultValue}}Object.defineProperty(NumberConfigKey.prototype,"value",{get:function(){return this._value},set:function(value){this._value=value;this.hasValue=true},enumerable:false,configurable:true});NumberConfigKey.prototype.loadFromRawData=function(s){var parsed=parseInt(s);if(isNaN(parsed))throw new Error(s+" is not a valid number");this.value=parsed;this.hasValue=true};return NumberConfigKey}();exports.NumberConfigKey=NumberConfigKey;var BooleanConfigKey=function(){function BooleanConfigKey(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"boolean"};if(defaultValue!==undefined){this.value=defaultValue}}Object.defineProperty(BooleanConfigKey.prototype,"value",{get:function(){return this._value},set:function(value){this._value=value;this.hasValue=true},enumerable:false,configurable:true});BooleanConfigKey.prototype.loadFromRawData=function(s){if(s==null)s="";if(typeof s==="boolean")s=String(s);s=s.toLowerCase();switch(s){case"true":this.value=true;this.hasValue=true;return;case"false":this.value=false;this.hasValue=true;return;case"undefined":this.value=false;this.hasValue=false;return;default:throw new Error("Invalid boolean value: "+s)}};return BooleanConfigKey}();exports.BooleanConfigKey=BooleanConfigKey;var BaseConfiguration=function(){function BaseConfiguration(){}BaseConfiguration.prototype.loadConfigurationFromMultipleProviders=function(configProviders,callback){var provider=new ConfigProviderAggregator(configProviders);this.loadConfiguration(provider,callback)};BaseConfiguration.prototype.loadConfiguration=function(configProvider,callback,dbg){var _this=this;try{configProvider.getAllKeyValues(function(err,keysAndValues){if(err){if(callback){callback(err)}return}keysAndValues=keysAndValues||{};var knownKeys=Object.keys(_this);var hadError=false;var keyWithError="";knownKeys.forEach(function(keyName){if(hadError){console.log("[Sealights Test Listener] - Failed to load configuration due to invalid value in '"+keyWithError+"' field'.");return}var cfgKey=_this[keyName];if(!cfgKey.isConfigKey)return;var rawValue=keysAndValues[keyName];if(cfgKey.metadata.required&&rawValue==undefined){var msg="Required configuration is missing: "+keyName+", provider:"+configProvider.getName();hadError=true;if(callback){callback(new Error(msg))}}if(rawValue==undefined)return;try{cfgKey.loadFromRawData(rawValue)}catch(e){var msg="Invalid configuration for key="+keyName+", value="+rawValue+ +", provider="+configProvider.getName()+": "+e.toString();console.log("[Sealights Test Listener] - "+msg);hadError=true;keyWithError=keyName;if(callback){callback(new Error(msg))}}});if(!hadError){if(callback){callback(null)}return}})}catch(e){if(callback){callback(e)}return}};BaseConfiguration.prototype.toJsonObject=function(){var _this=this;var ret={};var knownKeys=Object.keys(this);knownKeys.forEach(function(keyName){var cfgKey=_this[keyName];if(cfgKey.isConfigKey&&cfgKey.hasValue){ret[keyName]=cfgKey.value}});return ret};BaseConfiguration.prototype.getLowerCaseToKeyMap=function(){var lowerCaseMap={};Object.keys(this).forEach(function(key){lowerCaseMap[key.toLowerCase()]=key});return lowerCaseMap};return BaseConfiguration}();exports.BaseConfiguration=BaseConfiguration})}).call(this)}).call(this,require("_process"))},{_process:179,fs:69}],302:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./config-system"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentConfigWithRuntimeArgs=exports.AgentConfig=void 0;var config_system_1=require("./config-system");var AgentConfig=function(_super){__extends(AgentConfig,_super);function AgentConfig(){var _this=_super!==null&&_super.apply(this,arguments)||this
29
+ ;_this.token=new config_system_1.StringConfigKey(false);_this.buildSessionId=new config_system_1.StringConfigKey(false);_this.tokenFile=new config_system_1.StringConfigKey(false);_this.server=new config_system_1.StringConfigKey(false);_this.proxy=new config_system_1.StringConfigKey(false);_this.interval=new config_system_1.NumberConfigKey(false,1e4);_this.testStatusCheckInterval=new config_system_1.NumberConfigKey(false,3e4);_this.enabled=new config_system_1.BooleanConfigKey(false,true);_this.sendFootprints=new config_system_1.BooleanConfigKey(false,true);_this.sendEvents=new config_system_1.BooleanConfigKey(false,true);_this.sendLogs=new config_system_1.BooleanConfigKey(false,false);_this.customerId=new config_system_1.StringConfigKey(false);_this.appName=new config_system_1.StringConfigKey(false);_this.branch=new config_system_1.StringConfigKey(false);_this.build=new config_system_1.StringConfigKey(false);_this.environmentName=new config_system_1.StringConfigKey(false);_this.useBranchCoverage=new config_system_1.BooleanConfigKey(false,false);_this.labId=new config_system_1.StringConfigKey(false);_this.testStage=new config_system_1.StringConfigKey(false);_this.httpServerColoring=new config_system_1.BooleanConfigKey(false,false);_this.httpClientColoring=new config_system_1.BooleanConfigKey(false,false);_this.useInitialColor=new config_system_1.BooleanConfigKey(false,true);_this.gzip=new config_system_1.BooleanConfigKey(false,true);_this.useIstanbul=new config_system_1.BooleanConfigKey(false,false);_this.enableChildProcessPatcher=new config_system_1.BooleanConfigKey(false,false);_this.loggers=new config_system_1.StringConfigKey(false,"");_this.httpListeningPort=new config_system_1.NumberConfigKey(false,0);_this.useFootprintsV3=new config_system_1.BooleanConfigKey(false,true);_this.extendedFootprints=new config_system_1.BooleanConfigKey(false,false);_this.projectRoot=new config_system_1.StringConfigKey(false);_this.enforceFullRun=new config_system_1.BooleanConfigKey(false,false);_this.footprintsEnableV6=new config_system_1.BooleanConfigKey(false,true);_this.footprintsBufferThresholdMb=new config_system_1.NumberConfigKey(false,10);_this.executionQueryIntervalSecs=new config_system_1.NumberConfigKey(false,10);_this.footprintsQueueSize=new config_system_1.NumberConfigKey(false,2);_this.footprintsSendIntervalSecs=new config_system_1.NumberConfigKey(false,10);_this.footprintsCollectIntervalSecs=new config_system_1.NumberConfigKey(false,10);_this.shouldCheckForActiveExecutionOnStartUp=new config_system_1.BooleanConfigKey(false,true);return _this}return AgentConfig}(config_system_1.BaseConfiguration);exports.AgentConfig=AgentConfig;var AgentConfigWithRuntimeArgs=function(_super){__extends(AgentConfigWithRuntimeArgs,_super);function AgentConfigWithRuntimeArgs(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.cfg=new config_system_1.StringConfigKey(false);return _this}return AgentConfigWithRuntimeArgs}(AgentConfig);exports.AgentConfigWithRuntimeArgs=AgentConfigWithRuntimeArgs})},{"./config-system":301}],303:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","events","./config-system","object-assign","jwt-decode"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigProcess=void 0;var events=require("events");var config_system_1=require("./config-system");var assign=require("object-assign");var jwtDecode=require("jwt-decode");var ConfigProcess=function(_super){__extends(ConfigProcess,_super);function ConfigProcess(cfg,watchdog,backendProxy,logger){var _this=_super.call(this)||this;_this.cfg=cfg;_this.watchdog=watchdog;_this.backendProxy=backendProxy;_this.logger=logger;_this.isRunning=false;if(!cfg)throw new Error("cfg is required");_this.initialCfg=assign({},cfg.toJsonObject());if(!watchdog)throw new Error("watchdog is required");if(!backendProxy)throw new Error("backendProxy is required");if(!logger){throw new Error("logger is required")}watchdog.on("alarm",function(){watchdog.stop();_this.reloadConfigFromServer()});_this.initCfg();return _this}ConfigProcess.prototype.reloadConfigFromServer=function(callback){var _this=this;this.backendProxy.getRemoteConfig({appName:this.cfg.appName.value,branch:this.cfg.branch.value,build:this.cfg.build.value,labId:this.cfg.labId.value,testStage:this.cfg.testStage.value},function(err,updatedCfg){if(!err&&updatedCfg){_this.mergeConfigFromServerAndFireEvent(updatedCfg)}_this.watchdog.start();if(callback){callback(err)}})};ConfigProcess.prototype.mergeConfigFromServerAndFireEvent=function(updatedCfgObject){var configChanged=false;this.cfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(this.initialCfg));for(var key in updatedCfgObject){if(this.cfg[key]&&this.cfg[key].isConfigKey&&this.cfg[key].value!=updatedCfgObject[key]){configChanged=true;break}}if(configChanged){this.cfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(updatedCfgObject));this.emit("configuration_changed",this.cfg)}};ConfigProcess.prototype.getConfiguration=function(){return this.cfg};ConfigProcess.prototype.initCfg=function(){if(this.cfg.token.hasValue){try{var tokenData=jwtDecode(this.cfg.token.value);if(!tokenData["x-sl-server"]){throw new Error("Token Is Invalid. Doesn't Contain Server")}if(!this.cfg.server.hasValue)this.cfg.server.value=tokenData["x-sl-server"];if(!tokenData["subject"]){throw new Error("Token Is Invalid. Doesn't Contain Subject")}var customerId=tokenData["subject"];var subjectParts=tokenData["subject"].split("@");customerId=subjectParts[0];this.cfg.customerId.value=this.cfg.customerId.value||customerId}catch(err){this.cfg.enabled.value=false;this.logger.error("Error loading configuration. Agent will be disabled. %s",err)}}};ConfigProcess.prototype.start=function(callback){if(this.isRunning)return;if(!this.cfg.enabled.value)return;if(!this.cfg.server.value||!this.cfg.token.hasValue)return;this.reloadConfigFromServer(callback);this.isRunning=true};ConfigProcess.prototype.stop=function(callback){this.watchdog.stop();this.isRunning=false;return callback()};return ConfigProcess}(events.EventEmitter);exports.ConfigProcess=ConfigProcess})},{"./config-system":301,events:110,"jwt-decode":440,"object-assign":153}],304:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Constants=void 0;var Constants=function(){function Constants(){}var _a;Constants.TRUE="true";Constants.FALSE="false";Constants.BUILD_SESSION_ID="buildSessionId";Constants.REQUEST="request";Constants.FOOTPRINTS_PACKET="footprintsPacket";Constants.TEST_STAGE="testStage";Constants.EXECUTION_BSID="executionBsid";Constants.CALLBACK="callback";Constants.PULL_REQUEST_PARAMS="pullRequestParams";Constants.SL_WINDOW_OBJECT="window.$Sealights";Constants.SKIP_BROWSER_AGENT=Constants.SL_WINDOW_OBJECT+".skipSlAgent";Constants.Messages=(_a=function(){function class_1(){}return class_1}(),_a.CANNOT_BE_NULL_OR_UNDEFINED="cannot be null or undefined.",_a.CANNOT_BE_EMPTY_STRING="cannot be empty string",_a);return Constants}();exports.Constants=Constants})},{}],305:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../utils/parsing-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SlEnvVars=void 0;var parsing_utils_1=require("../utils/parsing-utils");var SlEnvVars=function(){function SlEnvVars(){}SlEnvVars.getHttpTimeout=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.HTTP_TIMEOUT)};SlEnvVars.getHttpMaxAttempts=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.HTTP_MAX_ATTEMPTS)};SlEnvVars.getHttpAttemptInterval=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.HTTP_ATTEMPT_INTERVAL)};SlEnvVars.inProductionListenerMode=function(){return!!process.env[SlEnvVars.PRODUCTION_LISTENER]};SlEnvVars.getProductionListenerModes=function(){return(process.env[SlEnvVars.PRODUCTION_LISTENER]||"").split(",")};SlEnvVars.getFileStorage=function(){return process.env[SlEnvVars.FILE_STORAGE]};SlEnvVars.getBasePath=function(){return process.env[SlEnvVars.BASE_PATH]};SlEnvVars.isUseNewUniqueId=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.NEW_UNIQUE_ID)};SlEnvVars.isUseIstanbul=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.USE_ISTANBUL)};SlEnvVars.enableFootprintsV6=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.ENABLE_FOOTPRINTS_V6)};SlEnvVars.getFootprintsCollectIntervalSecs=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.FOOTPRINTS_COLLECTION_INTERVAL_SECS)};SlEnvVars.getFootprintsSendMaxIntervalSecs=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.FOOTPRINTS_SEND_MAX_INTERVAL_SECS)};SlEnvVars.getFootprintsQueueSize=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.FOOTPRINTS_QUEUE_SIZE)};SlEnvVars.getExecutionQueryIntervalSecs=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.EXECUTION_QUERY_INTERVAL_SEC)};SlEnvVars.getFootprintsBufferThresholdMb=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.FOOTPRINTS_BUFFER_THRESHOLD_MB)};SlEnvVars.blockBrowserHttpTraffic=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.BLOCK_BROWSER_HTTP_TRAFFIC)};SlEnvVars.getDisableHookDependencyGuard=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.DISABLE_HOOK_DEPENDENCY_GUARD)};var _a;SlEnvVars.HTTP_TIMEOUT="SL_httpTimeout";SlEnvVars.HTTP_MAX_ATTEMPTS="SL_HttpMaxAttempts";SlEnvVars.HTTP_ATTEMPT_INTERVAL="SL_HttpAttemptInterval";SlEnvVars.PRODUCTION_LISTENER="SL_production";SlEnvVars.FILE_STORAGE="SL_fileStorage";SlEnvVars.NEW_UNIQUE_ID="SL_newUniqueId";SlEnvVars.BASE_PATH="SL_basePath";SlEnvVars.USE_ISTANBUL="SL_useIstanbul";SlEnvVars.ENABLE_FOOTPRINTS_V6="SL_footprintsEnableV6";SlEnvVars.FOOTPRINTS_COLLECTION_INTERVAL_SECS="SL_footprintsCollectIntervalSecs";SlEnvVars.FOOTPRINTS_SEND_MAX_INTERVAL_SECS="SL_footprintsSendIntervalSecs";SlEnvVars.FOOTPRINTS_QUEUE_SIZE="SL_footprintsQueueSize";SlEnvVars.EXECUTION_QUERY_INTERVAL_SEC="SL_executionQueryIntervalSecs";SlEnvVars.FOOTPRINTS_BUFFER_THRESHOLD_MB="SL_footprintsBufferThresholdMb";SlEnvVars.BLOCK_BROWSER_HTTP_TRAFFIC="SL_blockBrowserHttpTraffic";SlEnvVars.DISABLE_HOOK_DEPENDENCY_GUARD="SL_disableHookDependencyGuard";SlEnvVars.CIA=(_a=function(){function class_1(){}class_1.getFileExtensions=function(){return process.env[SlEnvVars.CIA.FILE_EXTENSIONS]};class_1.getSourceRoot=function(){return process.env[SlEnvVars.CIA.SL_SOURCE_ROOT]};class_1.getSlMappingPath=function(){return process.env[SlEnvVars.CIA.SL_MAPPING_PATH]};class_1.getSlMappingUrl=function(){return process.env[SlEnvVars.CIA.SL_MAPPING_URL]};class_1.reduceInstrumentedFileSize=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.CIA.REDUCE_INSTRUMENTED_FILE_SIZE)};class_1.minifyInstrumentedOutput=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.CIA.MINIFY_INSTRUMENTED_OUTPUT)};class_1.inProcessInstrumentation=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.CIA.IN_PROCESS_INSTRUMENTATION)};class_1.getMaxBuffer=function(){var oneMB=1024*1024;var bufferInBytes=parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.CIA.MAX_BUFFER);if(bufferInBytes!==null){return bufferInBytes*oneMB}return bufferInBytes};return class_1}(),_a.FILE_EXTENSIONS="SL_fileExtensions",_a.SL_SOURCE_ROOT="SL_sourceRoot",_a.SL_MAPPING_PATH="SL_mappingPath",_a.SL_MAPPING_URL="SL_mappingUrl",_a.REDUCE_INSTRUMENTED_FILE_SIZE="SL_reduceInstrumentedFileSize",_a.MINIFY_INSTRUMENTED_OUTPUT="SL_minifyInstrumentedOutput",_a.IN_PROCESS_INSTRUMENTATION="SL_inProcessInstrumentation",_a.MAX_BUFFER="SL_maxBuffer",_a);return SlEnvVars}();exports.SlEnvVars=SlEnvVars})}).call(this)}).call(this,require("_process"))},{"../utils/parsing-utils":334,_process:179}],306:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ElementType=void 0;var ElementType;(function(ElementType){ElementType["METHOD"]="method";ElementType["BRANCH"]="branch"})(ElementType=exports.ElementType||(exports.ElementType={}))})},{}],307:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FileElement=void 0;var validation_utils_1=require("../utils/validation-utils");var FileElement=function(){function FileElement(type,startPosition,endPosition,uniqueIdKey,filename){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(type,"type");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(startPosition,"startPosition");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(endPosition,"endPosition");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(uniqueIdKey,"uniqueIdKey");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(filename,"filename");this._type=type;this._startPosition=startPosition;this._endPosition=endPosition;this._uniqueIdKey=uniqueIdKey;this._filename=filename}Object.defineProperty(FileElement.prototype,"type",{get:function(){return this._type},set:function(value){this._type=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"startPosition",{get:function(){return this._startPosition},set:function(value){this._startPosition=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"endPosition",{get:function(){return this._endPosition},set:function(value){this._endPosition=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"uniqueIdKey",{get:function(){return this._uniqueIdKey},set:function(value){this._uniqueIdKey=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"uniqueIdKey_decl",{get:function(){return this._uniqueIdKey_decl},set:function(value){this._uniqueIdKey_decl=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"filename",{get:function(){return this._filename},set:function(value){this._filename=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"uniqueId",{get:function(){return this._uniqueId},set:function(value){this._uniqueId=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"parentPosition",{get:function(){return this._parentPosition},set:function(value){this._parentPosition=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"index",{get:function(){return this._index},set:function(value){this._index=value},enumerable:false,configurable:true});FileElement.prototype.isStartsAfter=function(fileElement){if(parseInt(this._startPosition.line.toString())<parseInt(fileElement.startPosition.line.toString())){return false}if(parseInt(this._startPosition.line.toString())>parseInt(fileElement.startPosition.line.toString())){return true}if(parseInt(this._startPosition.column.toString())>parseInt(fileElement.startPosition.column.toString())){return true}return false};FileElement.prototype.isStartsBefore=function(fileElement){if(parseInt(this._startPosition.line.toString())>parseInt(fileElement.startPosition.line.toString())){return false}if(parseInt(this._startPosition.line.toString())<parseInt(fileElement.startPosition.line.toString())){return true}if(parseInt(this._startPosition.column.toString())<parseInt(fileElement.startPosition.column.toString())){return true}return false};FileElement.prototype.isEndsAfter=function(fileElement){if(parseInt(this._endPosition.line.toString())<parseInt(fileElement.endPosition.line.toString())){return false}if(parseInt(this._endPosition.line.toString())>parseInt(fileElement.endPosition.line.toString())){return true}if(parseInt(this._endPosition.column.toString())>parseInt(fileElement.endPosition.column.toString())){return true}return false};FileElement.prototype.isEndsBefore=function(fileElement){if(parseInt(this._endPosition.line.toString())>parseInt(fileElement.endPosition.line.toString())){return false}if(parseInt(this._endPosition.line.toString())<parseInt(fileElement.endPosition.line.toString())){return true}if(parseInt(this._endPosition.column.toString())<parseInt(fileElement.endPosition.column.toString())){return true}return false};return FileElement}();exports.FileElement=FileElement})},{"../utils/validation-utils":336}],308:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./contracts","./unique-id-converter"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.IstanbulUniqueIdConverter=void 0;var contracts_1=require("./contracts");var unique_id_converter_1=require("./unique-id-converter");var IstanbulUniqueIdConverter=function(_super){__extends(IstanbulUniqueIdConverter,_super);function IstanbulUniqueIdConverter(filename,logger){return _super.call(this,filename,logger)||this}IstanbulUniqueIdConverter.prototype.createElementsArray=function(file){var _this=this;file.fnMap=file.fnMap||{};file.branchMap=file.branchMap||{};var methodsArr=Object.keys(file.fnMap).map(function(key){return _this.formatMethod(file.fnMap[key])});var branchesArr=this.createBranchElements(file.branchMap);this.fillFileElementsArray(methodsArr,this.methodsArray,contracts_1.ElementType.METHOD);this.fillFileElementsArray(branchesArr,this.branchesArray,contracts_1.ElementType.BRANCH)};IstanbulUniqueIdConverter.prototype.createElementPosition=function(position){return position};IstanbulUniqueIdConverter.prototype.createBranchElements=function(branchesMap){var branchesMapArr=Object.keys(branchesMap).map(function(key){return branchesMap[key]});var branchesArr=[];for(var _i=0,branchesMapArr_1=branchesMapArr;_i<branchesMapArr_1.length;_i++){var branch=branchesMapArr_1[_i];branchesArr=branchesArr.concat(this.extractBranchParts(branch))}return branchesArr};IstanbulUniqueIdConverter.prototype.extractBranchParts=function(branch){var formattedBranches=[];var locations=branch.locations;for(var i=0;i<locations.length;i++){var element={};element.position=locations[i].start;element.endPosition=locations[i].end;element.uniqueId=this.filename+"|"+this.formatLoc(element.position)+"|"+i;formattedBranches.push(element)}return formattedBranches};IstanbulUniqueIdConverter.prototype.formatMethod=function(method){var element={};element.position=method.loc.start;element.endPosition=method.loc.end;element.uniqueId=this.filename+"@"+this.formatLoc(method.loc.start);if(method.decl&&method.decl.start){element.uniqueId_decl=this.filename+"@"+this.formatLoc(method.decl.start);if(method.decl.start.line<method.loc.start.line){element.position=method.decl.start}}return element};IstanbulUniqueIdConverter.prototype.formatLoc=function(loc){return loc.line+","+loc.column};return IstanbulUniqueIdConverter}(unique_id_converter_1.UniqueIdConverter);exports.IstanbulUniqueIdConverter=IstanbulUniqueIdConverter})},{"./contracts":306,"./unique-id-converter":311}],309:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","path","../system-date","../utils/files-utils","./istanbul-unique-id-converter"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.resolveNewId=void 0;var path_1=require("path");var system_date_1=require("../system-date");var files_utils_1=require("../utils/files-utils");var istanbul_unique_id_converter_1=require("./istanbul-unique-id-converter");function resolveNewId(uniqueIdKey,moduleName,relativePath,coverageObject,logger){moduleName=path_1.normalize(moduleName);var moduleData=resolveModule(coverageObject,moduleName,logger);if(!moduleData){return}if(!moduleData.uniqueIdsMap){logger.debug("building uniqueids map for "+moduleData.path);var before_1=system_date_1.getSystemDateValueOf();logger.debug("file "+moduleData.path+" not contains uniqueIdMaps, trying to reload");createSLMapping(moduleData.path,relativePath,coverageObject,logger);var after_1=system_date_1.getSystemDateValueOf();logger.debug("*******************************create unique id map ******************************************");logger.debug(after_1-before_1);logger.debug("*******************************create unique id map ******************************************")}var newUniqueId=moduleData.uniqueIdsMap[uniqueIdKey];if(!newUniqueId){logger.error("could not generate new uniqueId for '"+uniqueIdKey+"'")}return newUniqueId}exports.resolveNewId=resolveNewId;function resolveModule(coverageObject,moduleName,logger){var withLeftSlashes=files_utils_1.FilesUtils.adjustPathSlashes(moduleName);var moduleData=coverageObject[moduleName]||coverageObject[withLeftSlashes];if(!moduleData){logger.warn("Coverage object not contains data for "+moduleName+" or "+withLeftSlashes)}return moduleData}function createSLMapping(fullPath,relativePath,coverageObject,logger){var module=coverageObject[fullPath];var converter=new istanbul_unique_id_converter_1.IstanbulUniqueIdConverter(relativePath,logger);converter.createElementsArray(module);converter.process();coverageObject[fullPath].uniqueIdsMap=converter.uniqueIdsMap}})},{"../system-date":332,"../utils/files-utils":333,"./istanbul-unique-id-converter":308,path:171}],310:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../utils/validation-utils","../utils/files-utils","../source-maps-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.OriginalModuleLoader=void 0;var validation_utils_1=require("../utils/validation-utils");var files_utils_1=require("../utils/files-utils");var source_maps_utils_1=require("../source-maps-utils");var BRANCHES_MAP_KEY="branchMap";var METHODS_MAP_KEY="fnMap";var OriginalModuleLoader=function(){function OriginalModuleLoader(coverageObject,logger){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(coverageObject,"coverageObject");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this.coverageObject=coverageObject;this.logger=logger;this._fileToSourceMapConsumer={}}OriginalModuleLoader.prototype.load=function(){var _this=this;var modules=Object.keys(this.coverageObject);modules.map(function(moduleName){return _this.tryLoadOriginalModule(moduleName)})};OriginalModuleLoader.prototype.tryLoadOriginalModule=function(istanbulModule){if(!this.getSourceMapForFile(istanbulModule)){return}this.readOriginalModule(istanbulModule)};OriginalModuleLoader.prototype.readOriginalModule=function(moduleName){var _this=this;var sourceMapsReader=this.getSourceMapForFile(moduleName);var module=this.coverageObject[moduleName];Object.keys(module.branchMap).forEach(function(key){return _this.resolveAndAddBranch(module.branchMap[key],sourceMapsReader,moduleName)});Object.keys(module.fnMap).map(function(key){return _this.resolveAndAddMethod(module.fnMap[key],sourceMapsReader,moduleName)})};OriginalModuleLoader.prototype.resolveAndAddMethod=function(method,sourceMapsReader,moduleName){var originalMethod=this.createEmptyMethodObject();originalMethod.name=method.name;var originalModuleName=this.loadOriginalDataForElement(sourceMapsReader,method,moduleName,originalMethod);if(originalModuleName){this.addElementToModule(originalModuleName,originalMethod,METHODS_MAP_KEY)}};OriginalModuleLoader.prototype.resolveAndAddBranch=function(branch,sourceMapsReader,moduleName){var _this=this;var originalBranch=this.createEmptyBranchObject();originalBranch.type=branch.type;var originalModuleName=this.loadOriginalDataForElement(sourceMapsReader,branch,moduleName,originalBranch);if(originalModuleName){var originalLocations=branch.locations.map(function(locationElement){return _this.createElementSourceData(locationElement,sourceMapsReader,moduleName)});originalBranch.locations=originalLocations;this.addElementToModule(originalModuleName,originalBranch,BRANCHES_MAP_KEY)}};OriginalModuleLoader.prototype.loadOriginalDataForElement=function(sourceMapsReader,element,moduleName,originalElement){var sourceMapDataForStart=this.readSourceMapData(sourceMapsReader,element.loc.start,moduleName);var sourceMapDataForEnd=this.readSourceMapData(sourceMapsReader,element.loc.end,moduleName);if(!sourceMapDataForStart){return}originalElement.loc.start=sourceMapDataForStart.originalPosition;originalElement.line=sourceMapDataForStart.originalPosition.line;var originalModuleName=sourceMapDataForStart.originalFilename;if(sourceMapDataForEnd){originalElement.loc.end=sourceMapDataForEnd.originalPosition}if(element.decl){originalElement.decl={};var sourceMapDataForDeclStart=this.readSourceMapData(sourceMapsReader,element.decl.start,moduleName);var sourceMapDataForDeclEnd=this.readSourceMapData(sourceMapsReader,element.decl.end,moduleName);if(sourceMapDataForDeclStart){originalElement.decl.start=sourceMapDataForDeclStart.originalPosition}if(sourceMapDataForDeclEnd){originalElement.decl.end=sourceMapDataForDeclEnd.originalPosition}}return originalModuleName};OriginalModuleLoader.prototype.addElementToModule=function(moduleName,element,mapObjectKey){var module=this.getOrCreateIstanbulModule(moduleName);var key=this.createElementKey(element);if(!module[mapObjectKey][key]){module[mapObjectKey][key]=element}};OriginalModuleLoader.prototype.createElementSourceData=function(locationElement,sourceMapsReader,moduleName){var sourceMapDataForStart=this.readSourceMapData(sourceMapsReader,locationElement.start,moduleName);var sourceMapDataForEnd=this.readSourceMapData(sourceMapsReader,locationElement.end,moduleName);if(!sourceMapDataForStart&&!sourceMapDataForEnd){return{}}var sourceLocationElement={start:sourceMapDataForStart.originalPosition,end:sourceMapDataForEnd.originalPosition};return sourceLocationElement};OriginalModuleLoader.prototype.getOrCreateIstanbulModule=function(moduleName){var module=this.coverageObject[moduleName];if(!module){module=this.createIstanbulModule(moduleName);this.coverageObject[moduleName]=module}return module};OriginalModuleLoader.prototype.getSourceMapForFile=function(fullPath){if(!this._fileToSourceMapConsumer[fullPath]){this._fileToSourceMapConsumer[fullPath]=source_maps_utils_1.SourceMapsUtils.readSourceMaps(fullPath);this.logger.debug("Read source maps for file':"+fullPath+"'")}var sourceMap=this._fileToSourceMapConsumer[fullPath];return sourceMap};OriginalModuleLoader.prototype.readSourceMapData=function(sourceMaps,start,fullPath){if(!sourceMaps)return null;try{var originalPosition=sourceMaps.originalPositionFor(start);if(originalPosition&&originalPosition.source&&originalPosition.line!==null&&originalPosition.column!==null){var originalFilename=originalPosition.source;if(originalFilename.indexOf("webpack:///webpack/")===-1&&originalFilename.indexOf("webpack:///external")===-1){if(originalFilename.indexOf("webpack:///")===0){originalFilename=originalFilename.substring(11)}originalFilename=files_utils_1.FilesUtils.resolveOriginalFullFileName(fullPath,originalFilename);var originalPositionObj={line:originalPosition.line,column:originalPosition.column};var result={originalFilename:originalFilename,originalPosition:originalPositionObj};return result}}}catch(e){console.log(e)}return null};OriginalModuleLoader.prototype.createElementKey=function(element){return element.loc.start.line+":"+element.loc.start.column};OriginalModuleLoader.prototype.createEmptyBranchObject=function(){return{loc:{},locations:[],type:"",line:null}};OriginalModuleLoader.prototype.createEmptyMethodObject=function(){return{loc:{},name:"",line:null}};OriginalModuleLoader.prototype.createIstanbulModule=function(path){return{s:{},f:{},b:{},fnMap:{},statementMap:{},branchMap:{},path:path,uniqueIdsMap:null}};Object.defineProperty(OriginalModuleLoader.prototype,"fileToSourceMapConsumer",{get:function(){return this._fileToSourceMapConsumer},set:function(value){this._fileToSourceMapConsumer=value},enumerable:false,configurable:true});return OriginalModuleLoader}();exports.OriginalModuleLoader=OriginalModuleLoader})},{"../source-maps-utils":330,"../utils/files-utils":333,"../utils/validation-utils":336}],311:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./contracts","./file-element"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.UniqueIdConverter=void 0;var contracts_1=require("./contracts");var file_element_1=require("./file-element");var METHOD_DELIMITER="@";var BRANCH_DELIMITER="|";var NULL_PARAM_MESSAGE="cannot be null or undefined";var UniqueIdConverter=function(){function UniqueIdConverter(filename,logger){if(!filename){throw new Error("'filename' "+NULL_PARAM_MESSAGE)}if(!logger){throw new Error("'logger' "+NULL_PARAM_MESSAGE)}this._filename=filename;this.logger=logger;this._uniqueIdsMap={};this._methodsArray=[];this._branchesArray=[]}UniqueIdConverter.prototype.sortElements=function(){this._methodsArray=this._methodsArray.sort(this.comparePosition);this._branchesArray=this._branchesArray.sort(this.comparePosition)};UniqueIdConverter.prototype.createElementsArray=function(file){file.methods=file.methods||[]
30
+ ;file.branches=file.branches||[];this.fillFileElementsArray(file.methods,this._methodsArray,contracts_1.ElementType.METHOD);this.fillFileElementsArray(file.branches,this._branchesArray,contracts_1.ElementType.BRANCH)};UniqueIdConverter.prototype.createFileElement=function(element,filename,type){var startPosition=this.createElementPosition(element.position);var endPosition=this.createElementPosition(element.endPosition);var fileElement=new file_element_1.FileElement(type,startPosition,endPosition,element.uniqueId,filename);if(element.uniqueId_decl){fileElement.uniqueIdKey_decl=element.uniqueId_decl}if(element.parentPosition){var index=element.index||0;fileElement.startPosition=this.createElementPosition(element.parentPosition);fileElement.index=index}return fileElement};UniqueIdConverter.prototype.process=function(){this.removeDuplicateElements(this._methodsArray);this.removeDuplicateElements(this._branchesArray);this.sortElements();this.logger.debug("sorted "+this._branchesArray.length+" branches");this.logger.debug("sorted "+this._methodsArray.length+" methods");this.fillUniqueIdsMap()};UniqueIdConverter.prototype.setAndInitFile=function(file){this.createElementsArray(file)};UniqueIdConverter.prototype.createElementPosition=function(position){var line;var column;if(Array.isArray(position)&&position.length===2){line=parseInt(position[0]);column=parseInt(position[1])}else{throw new Error("element has no correct startPosition array, cannot resolve startPosition")}return{column:column,line:line}};UniqueIdConverter.prototype.fillFileElementsArray=function(elements,array,type){for(var _i=0,elements_1=elements;_i<elements_1.length;_i++){var element=elements_1[_i];array.push(this.createFileElement(element,this._filename,type))}};UniqueIdConverter.prototype.fillUniqueIdsMap=function(){this.createNewUniqueIds(this._methodsArray,METHOD_DELIMITER);this.createNewUniqueIds(this._branchesArray,BRANCH_DELIMITER)};UniqueIdConverter.prototype.createNewUniqueIds=function(array,delimiter){var aggregatedByLine=this.aggregateElementsByLine(array);var lines=Object.keys(aggregatedByLine);for(var _i=0,lines_1=lines;_i<lines_1.length;_i++){var line=lines_1[_i];var indexesArray=aggregatedByLine[line];for(var i=0;i<indexesArray.length;i++){var currentIndex=indexesArray[i];var currentElement=array[currentIndex];currentElement.uniqueId=currentElement.filename+delimiter+line+","+i;this.logger.debug("[UniqueIdConverter] uniqueId "+currentElement.uniqueIdKey+" converted to \n "+currentElement.uniqueId);this._uniqueIdsMap[currentElement.uniqueIdKey]=currentElement.uniqueId;if(currentElement.uniqueIdKey_decl){this._uniqueIdsMap[currentElement.uniqueIdKey_decl]=currentElement.uniqueId}}}};UniqueIdConverter.prototype.comparePosition=function(elm1,elm2){if(elm1.startPosition.line<elm2.startPosition.line){return-1}if(elm1.startPosition.line>elm2.startPosition.line){return 1}if(elm1.startPosition.column<elm2.startPosition.column){return-1}if(elm1.startPosition.column>elm2.startPosition.column){return 1}if(elm1.index<elm2.index){return-1}if(elm1.index>elm2.index){return 1}return 0};Object.defineProperty(UniqueIdConverter.prototype,"uniqueIdsMap",{get:function(){return this._uniqueIdsMap},enumerable:false,configurable:true});Object.defineProperty(UniqueIdConverter.prototype,"methodsArray",{get:function(){return this._methodsArray},set:function(value){this._methodsArray=value},enumerable:false,configurable:true});Object.defineProperty(UniqueIdConverter.prototype,"branchesArray",{get:function(){return this._branchesArray},set:function(value){this._branchesArray=value},enumerable:false,configurable:true});Object.defineProperty(UniqueIdConverter.prototype,"filename",{get:function(){return this._filename},enumerable:false,configurable:true});UniqueIdConverter.prototype.removeDuplicateElements=function(elementsArray){var _this=this;var existedKeys={};elementsArray=elementsArray.filter(function(element){return _this.filterDuplicates(element,existedKeys)})};UniqueIdConverter.prototype.filterDuplicates=function(element,existedKeys){if(existedKeys[element.uniqueIdKey]||element.uniqueIdKey_decl&&existedKeys[element.uniqueIdKey_decl]){return false}existedKeys[element.uniqueIdKey]=true;if(element.uniqueIdKey_decl){existedKeys[element.uniqueIdKey_decl]=true}return true};UniqueIdConverter.prototype.removeBranchesOutOfMethods=function(){var validBranches=[];var methodsIndex=0;for(var _i=0,_a=this._branchesArray;_i<_a.length;_i++){var branch=_a[_i];for(var i=methodsIndex;i<this._methodsArray.length;i++){var currentMethod=this._methodsArray[i];var branchPosition=this.checkBranchPosition(branch,currentMethod);if(branchPosition===0){validBranches.push(branch);break}if(branchPosition===1){methodsIndex++}}}this._branchesArray=validBranches.sort(this.comparePosition)};UniqueIdConverter.prototype.checkBranchPosition=function(branch,method){if(branch.isStartsAfter(method)&&branch.isEndsBefore(method)){return 0}if(branch.isStartsBefore(method)&&branch.isEndsBefore(method)){return-1}if(branch.isStartsAfter(method)&&branch.isEndsAfter(method)){return 1}this.logger.warn("branch started at '"+branch.startPosition.line+","+branch.startPosition.column+"' in file '"+this._filename+"' located across methods, probably some error");return 0};UniqueIdConverter.prototype.aggregateElementsByLine=function(elements){var aggregated={};for(var i=0;i<elements.length;i++){var element=elements[i];var lineNumber=element.startPosition.line;if(!aggregated[lineNumber]){aggregated[lineNumber]=[]}aggregated[lineNumber].push(i)}return aggregated};return UniqueIdConverter}();exports.UniqueIdConverter=UniqueIdConverter})},{"./contracts":306,"./file-element":307}],312:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TestSelectionStatus=exports.EventTypes=void 0;var EventTypes;(function(EventTypes){EventTypes["AgentStarted"]="agentStarted";EventTypes["ExecutionIdStarted"]="executionIdStarted";EventTypes["ExecutionIdEnded"]="executionIdEnded";EventTypes["TestStart"]="testStart";EventTypes["TestEnd"]="testEnd"})(EventTypes=exports.EventTypes||(exports.EventTypes={}));var TestSelectionStatus;(function(TestSelectionStatus){TestSelectionStatus["RECOMMENDED_TESTS"]="recommendedTests";TestSelectionStatus["DISABLED"]="disabled";TestSelectionStatus["DISABLED_BY_CONFIGURATION"]="disabledByConfiguration";TestSelectionStatus["RECOMMENDATIONS_TIMEOUT"]="recommendationsTimeout";TestSelectionStatus["ERROR"]="error"})(TestSelectionStatus=exports.TestSelectionStatus||(exports.TestSelectionStatus={}))})},{}],313:[function(require,module,exports){var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./events-contracts","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EventsCreator=void 0;var events_contracts_1=require("./events-contracts");var system_date_1=require("../system-date");var EventsCreator=function(){function EventsCreator(){}EventsCreator.createTestStartedEvent=function(executionId,framework,testName,duration){var eventBase=this.createEvent(events_contracts_1.EventTypes.TestStart,executionId,framework);var startTimeStamp=system_date_1.getSystemDateValueOf()-duration;eventBase.localTime=startTimeStamp;return __assign(__assign({},eventBase),{testName:testName})};EventsCreator.createTestEndEvent=function(executionId,framework,testName,result,duration){var eventBase=this.createEvent(events_contracts_1.EventTypes.TestEnd,executionId,framework);return __assign(__assign({},eventBase),{result:result,duration:duration,testName:testName})};EventsCreator.createEvent=function(type,executionId,framework){return{type:type,executionId:executionId,framework:framework,localTime:system_date_1.getSystemDateValueOf()}};return EventsCreator}();exports.EventsCreator=EventsCreator})},{"../system-date":332,"./events-contracts":312}],314:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../utils/validation-utils","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EventsProcess=void 0;var validation_utils_1=require("../utils/validation-utils");var system_date_1=require("../system-date");var EventsProcess=function(){function EventsProcess(configuration,agentInstanceData,sendToServerWatchdog,keepAliveWatchdog,environmentDataService,backendProxy,eventsQueue,logger){this._isRunning=false;this.sequence=0;this._onGoingRequests=[];validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(configuration,"configuration");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentInstanceData,"agentInstanceData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(sendToServerWatchdog,"sendToServerWatchdog");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(keepAliveWatchdog,"keepAliveWatchdog");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(environmentDataService,"environmentData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(backendProxy,"backendProxy");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(eventsQueue,"eventsQueue");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this._configuration=configuration;this._agentInstanceData=agentInstanceData;this._sendToServerWatchdog=sendToServerWatchdog;this.keepAliveWatchdog=keepAliveWatchdog;this.environmentData=environmentDataService;this._backendProxy=backendProxy;this._logger=logger;this._eventsQueue=eventsQueue;this.init()}EventsProcess.prototype.enqueueEvent=function(evt){evt.localTime=evt.localTime||system_date_1.getSystemDateValueOf();this._eventsQueue.enqueue(evt);if(this.isRunning&&this.configuration.sendEvents.value&&this.configuration.enabled.value){this.ensureKeepaliveThreadRunning()}};EventsProcess.prototype.start=function(){if(this._isRunning||!this._configuration.enabled.value){return}this._sendToServerWatchdog.start();if(this._eventsQueue.getQueueSize()>0){this.ensureKeepaliveThreadRunning()}this._isRunning=true};EventsProcess.prototype.stop=function(){return __awaiter(this,void 0,void 0,function(){var e_1;return __generator(this,function(_a){switch(_a.label){case 0:this._sendToServerWatchdog.stop();this.keepAliveWatchdog.stop();if(this._configuration.enabled.value===false||this._configuration.sendEvents.value===false){return[2]}_a.label=1;case 1:_a.trys.push([1,4,,5]);return[4,Promise.all(this._onGoingRequests)];case 2:_a.sent();return[4,this.submitEventsSync()];case 3:_a.sent();return[3,5];case 4:e_1=_a.sent();this._logger.warn("Error while stopping EventsProcess: ",e_1);return[3,5];case 5:this._isRunning=false;return[2]}})})};EventsProcess.prototype.getQueueSize=function(){return this._eventsQueue.getQueueSize()};EventsProcess.prototype.submitEvents=function(){var _this=this;if(!this._isRunning||!this._configuration.sendEvents.value||!this._configuration.enabled.value||this._eventsQueue.getQueueSize()==0){return}var items=this._eventsQueue.dequeue(EventsProcess.ITEMS_TO_DEQUE);var packet=this.createEventsPacket(items);var promise=this._backendProxy.submitEventsPromise(packet);this._onGoingRequests.push(promise);promise.then(function(){if(_this._eventsQueue.getQueueSize()>0){_this.submitEvents()}_this.removeRequest(promise)}).catch(function(err){_this._logger.warn("Error while submitting events, "+err);_this._eventsQueue.requeue(items);_this.removeRequest(promise)})};EventsProcess.prototype.submitEventsSync=function(){return __awaiter(this,void 0,void 0,function(){var items,packet,e_2;return __generator(this,function(_a){switch(_a.label){case 0:_a.trys.push([0,4,,5]);_a.label=1;case 1:if(!(this._eventsQueue.getQueueSize()>0))return[3,3];items=this._eventsQueue.dequeue(EventsProcess.ITEMS_TO_DEQUE);packet=this.createEventsPacket(items);return[4,this._backendProxy.submitEventsPromise(packet)];case 2:_a.sent();return[3,1];case 3:return[3,5];case 4:e_2=_a.sent();this._logger.warn("Error while sending events synchronously. "+e_2);return[3,5];case 5:return[2]}})})};EventsProcess.prototype.createEventsPacket=function(items){return{customerId:this._configuration.customerId.value,appName:this._configuration.appName.value,build:this._configuration.build.value,branch:this._configuration.branch.value,environment:this.environmentData,configurationData:this._configuration.toJsonObject,testSelectionStatus:this._testSelectionStatus,events:items,meta:{sequence:++this.sequence,generated:system_date_1.getSystemDateValueOf(),agentId:this._agentInstanceData.agentId}}};EventsProcess.prototype.init=function(){var _this=this;this._sendToServerWatchdog.on("alarm",function(){return _this.submitEvents()});this._eventsQueue.on("full",function(){return _this.submitEvents()});this.keepAliveWatchdog.on("alarm",function(){if(_this.eventsQueue.getQueueSize()==0){_this.keepAliveWatchdog.stop()}})};EventsProcess.prototype.ensureKeepaliveThreadRunning=function(){this.keepAliveWatchdog.start()};EventsProcess.prototype.removeRequest=function(request){var index=this._onGoingRequests.indexOf(request);this._onGoingRequests.splice(index,1)};Object.defineProperty(EventsProcess.prototype,"onGoingRequests",{get:function(){return this._onGoingRequests},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"configuration",{get:function(){return this._configuration},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"logger",{get:function(){return this._logger},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"isRunning",{get:function(){return this._isRunning},set:function(value){this._isRunning=value},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"sendToServerWatchdog",{get:function(){return this._sendToServerWatchdog},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"backendProxy",{get:function(){return this._backendProxy},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"eventsQueue",{get:function(){return this._eventsQueue},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"testSelectionStatus",{get:function(){return this._testSelectionStatus},set:function(testSelectionStatus){this._testSelectionStatus=testSelectionStatus},enumerable:false,configurable:true});EventsProcess.ITEMS_TO_DEQUE=1e3;return EventsProcess}();exports.EventsProcess=EventsProcess})},{"../system-date":332,"../utils/validation-utils":336}],315:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./location-formatter","../../common/footprints-process-v6/hits-converter","../utils/files-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BaseBrowserHitsConverter=void 0;var location_formatter_1=require("./location-formatter");var hits_converter_1=require("../../common/footprints-process-v6/hits-converter");var files_utils_1=require("../utils/files-utils");var BaseBrowserHitsConverter=function(_super){__extends(BaseBrowserHitsConverter,_super);function BaseBrowserHitsConverter(relativePathResolver,buildSessionId,logger){var _this=_super.call(this,relativePathResolver,{},{},logger)||this;_this.buildSessionId=buildSessionId;return _this}BaseBrowserHitsConverter.prototype.getMethodUniqueId=function(startLoc,relativePath,absolutePath){var uniqueId=absolutePath+hits_converter_1.HitsConverter.METHOD_ID_DEL+this.formatLoc(startLoc);return this.tryGetUniqueIdFromSlMapping(uniqueId)};BaseBrowserHitsConverter.prototype.getBranchUniqueId=function(startLoc,relativePath,absolutePath,leaveIndex){var uniqueId=absolutePath+hits_converter_1.HitsConverter.BRANCH_ID_DEL+this.formatLoc(startLoc)+hits_converter_1.HitsConverter.BRANCH_ID_DEL+leaveIndex;return this.tryGetUniqueIdFromSlMapping(uniqueId)};BaseBrowserHitsConverter.prototype.getDeclStart=function(hit){var decl=this.getDecl(hit);return decl.start||decl.st};BaseBrowserHitsConverter.prototype.getDecl=function(hit){return hit.decl||hit.d};BaseBrowserHitsConverter.prototype.getStartLoc=function(hit){var loc=hit.loc||hit.lc;return loc.start||loc.st};BaseBrowserHitsConverter.prototype.getLeaveStartLoc=function(hit,leaveIdx){var locations=hit.branchData.locations||hit.branchData.lcs;return locations[leaveIdx].start||locations[leaveIdx].st};BaseBrowserHitsConverter.prototype.formatLoc=function(loc){return location_formatter_1.formatLocation(loc,this.logger)};BaseBrowserHitsConverter.prototype.tryGetUniqueIdFromSlMapping=function(rawUniqueId){rawUniqueId=files_utils_1.FilesUtils.adjustPathSlashes(rawUniqueId);var mapping=this.getSlMapping()||{};return mapping[rawUniqueId]||rawUniqueId};return BaseBrowserHitsConverter}(hits_converter_1.HitsConverter);exports.BaseBrowserHitsConverter=BaseBrowserHitsConverter})},{"../../common/footprints-process-v6/hits-converter":319,"../utils/files-utils":333,"./location-formatter":321}],316:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BufferSizeHelper=void 0;var BufferSizeHelper=function(){function BufferSizeHelper(){this.uniqueIdsLengthSum=0;this.testNamesCount=0;this.testNamesLengthSum=0;this.hitCount=0;this.indicesCount=0;this.uniqueIdsCount=0}BufferSizeHelper.prototype.calculateBufferSize=function(){var sizeInBytes=this.uniqueIdsCount*BufferSizeHelper.FOUR_BYTES+this.uniqueIdsLengthSum+(this.testNamesCount*BufferSizeHelper.FOUR_BYTES+this.testNamesLengthSum)+this.hitCount*BufferSizeHelper.APPROX_HIT_SIZE+this.indicesCount*BufferSizeHelper.EIGHT_BYTES;return sizeInBytes/BufferSizeHelper.MB};BufferSizeHelper.prototype.incrementSizeCounters=function(testName,methodIndicesSize,branchIndicesSize){this.hitCount++;this.indicesCount+=methodIndicesSize+branchIndicesSize;if(testName){this.testNamesCount++;this.testNamesLengthSum+=testName.length}};BufferSizeHelper.FOUR_BYTES=4;BufferSizeHelper.EIGHT_BYTES=8;BufferSizeHelper.APPROX_HIT_SIZE=128;BufferSizeHelper.MB=1024*1024;return BufferSizeHelper}();exports.BufferSizeHelper=BufferSizeHelper})},{}],317:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../agent-events/cockpit-notifier","../agent-events/agent-events-conracts","events","./buffer-size-helper"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsBuffer=void 0;var cockpit_notifier_1=require("../agent-events/cockpit-notifier");var agent_events_conracts_1=require("../agent-events/agent-events-conracts");var events=require("events");var buffer_size_helper_1=require("./buffer-size-helper");var FootprintsBuffer=function(_super){__extends(FootprintsBuffer,_super);function FootprintsBuffer(agentInstanceData,agentConfig){var _this=_super.call(this)||this;_this.formatVersion="6.0";_this.agentInstanceData=agentInstanceData;_this._agentConfig=agentConfig;_this.currentBufferSize=0;_this.resetState();_this.meta={agentId:_this.agentInstanceData.agentId,intervals:{timedFootprintsCollectionIntervalSeconds:_this._agentConfig.footprintsCollectIntervalSecs.value},labId:_this._agentConfig.labId.value};return _this}FootprintsBuffer.prototype.addHit=function(footprints,collectionInterval,executionId,testName,isInitFootprints,isFinalFootprints){cockpit_notifier_1.CockpitNotifier.sendEventOnce(agent_events_conracts_1.AgentEventCode.FIRST_TIME_COLLECTED_FP);var methodIndices=this.addOrGetIndices(footprints.methods,true);var branchIndices=this.addOrGetIndices(footprints.branches,false);var executionIdx=this.addOrGetExecutionIndex(executionId);this.executions[executionIdx].hits.push({branches:branchIndices,methods:methodIndices,start:collectionInterval.start,end:collectionInterval.end,testName:testName,isInitFootprints:isInitFootprints,isFinalFootprints:isFinalFootprints});this.bufferSizeHelper.incrementSizeCounters(testName,methodIndices.length,branchIndices.length);this.verifyBufferSize()};FootprintsBuffer.prototype.createPacket=function(){var packet=this.toJson();this.resetState();return packet};FootprintsBuffer.prototype.resetState=function(){this.branches=[];this.methods=[];this.executions=[];this.methodIdToIndex=new Map;this.branchIdToIndex=new Map;this.bufferSizeHelper=new buffer_size_helper_1.BufferSizeHelper};FootprintsBuffer.prototype.hasHitsInBuffer=function(){return this.executions.length>0};Object.defineProperty(FootprintsBuffer.prototype,"agentConfig",{get:function(){return this._agentConfig},set:function(value){this._agentConfig=value},enumerable:false,configurable:true});FootprintsBuffer.prototype.toJson=function(){if(!this.executions||!this.executions.length){return null}return{formatVersion:this.formatVersion,branches:this.branches,executions:this.executions,meta:this.meta,methods:this.methods,moduleName:this.moduleName}};FootprintsBuffer.prototype.addOrGetIndices=function(elementIds,isMethods){var _this=this;var map=isMethods?this.methodIdToIndex:this.branchIdToIndex;var arr=isMethods?this.methods:this.branches;var indices=[];elementIds.forEach(function(id){if(!map.get(id)){_this.bufferSizeHelper.uniqueIdsLengthSum+=id.length;_this.bufferSizeHelper.uniqueIdsCount++;var position=arr.push(id);map.set(id,position-1)}indices.push(map.get(id))});return indices};FootprintsBuffer.prototype.addOrGetExecutionIndex=function(executionId){var index=-1;this.executions.every(function(execution,idx){if(executionId==execution.executionId){index=idx;return false}return true});return index!=-1?index:this.executions.push({executionId:executionId,hits:[]})-1};FootprintsBuffer.prototype.verifyBufferSize=function(){if(this.bufferSizeHelper.calculateBufferSize()>=this._agentConfig.footprintsBufferThresholdMb.value){this.emit(FootprintsBuffer.BUFFER_FULL)}};FootprintsBuffer.BUFFER_FULL="bufferFull";return FootprintsBuffer}(events.EventEmitter);exports.FootprintsBuffer=FootprintsBuffer})},{"../agent-events/agent-events-conracts":289,"../agent-events/cockpit-notifier":294,"./buffer-size-helper":316,events:110}],318:[function(require,module,exports){(function(global){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../constants/sl-env-vars","../coverage-elements/original-module-loader"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HitsCollector=void 0;var sl_env_vars_1=require("../constants/sl-env-vars");var original_module_loader_1=require("../coverage-elements/original-module-loader");var GLOBAL_ISTANBUL_CONTAINER_NAMES=["__coverage__"];var HitsCollector=function(){function HitsCollector(logger,globalCoverageObject){this.logger=logger;this._globalCoverageObject=globalCoverageObject;this.latestCoverageSnapshot={}}HitsCollector.prototype.getHitElements=function(){var hitFilesData=[];var globalCoverage=this.getGlobalCoverageObject();if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){new original_module_loader_1.OriginalModuleLoader(globalCoverage,this.logger).load()}for(var filename in globalCoverage){var _a=this.getFileCoverageObjects(filename),fileCoverageSnapshot=_a.fileCoverageSnapshot,currentFileCoverage=_a.currentFileCoverage,shouldResolveRelativePath=_a.shouldResolveRelativePath;var hitMethods=this.getHitMethods(currentFileCoverage,fileCoverageSnapshot);var hitBranches=this.getHitBranches(currentFileCoverage,fileCoverageSnapshot);if(hitMethods.length||hitBranches.length){hitFilesData.push({filename:filename,hitMethods:hitMethods,hitBranches:hitBranches,shouldResolveRelativePath:shouldResolveRelativePath})}}this.updateCoverageSnapshot(globalCoverage);return hitFilesData};Object.defineProperty(HitsCollector.prototype,"latestCoverageSnapshot",{get:function(){return this._latestCoverageSnapshot},set:function(value){this._latestCoverageSnapshot=value},enumerable:false,configurable:true});Object.defineProperty(HitsCollector.prototype,"globalCoverageObject",{get:function(){return this._globalCoverageObject},set:function(value){this._globalCoverageObject=value},enumerable:false,configurable:true});HitsCollector.prototype.getHitMethods=function(currentHits,snapshotHits){var hitMethodsIndices=Object.keys(currentHits.f).filter(function(id){snapshotHits.f[id]=snapshotHits.f[id]||0;return currentHits.f[id]>snapshotHits.f[id]});return hitMethodsIndices.map(function(id){return currentHits.fnMap[id]})};HitsCollector.prototype.dropHits=function(){this.updateCoverageSnapshot(this.getGlobalCoverageObject())};HitsCollector.prototype.getHitLeaves=function(currentLeaveHits,snapshotLeaveHits){var hitLeavesIndices=[];snapshotLeaveHits=snapshotLeaveHits||Array(currentLeaveHits.length).fill(0);currentLeaveHits.forEach(function(leaveHit,leaveIdx){if(currentLeaveHits[leaveIdx]>snapshotLeaveHits[leaveIdx]){hitLeavesIndices.push(leaveIdx)}});return hitLeavesIndices};HitsCollector.prototype.getHitBranches=function(currentHits,fileHitSnapshot){var hitBranches=[];for(var branchIdx in currentHits.b){var hitLeaves=this.getHitLeaves(currentHits.b[branchIdx],fileHitSnapshot.b[branchIdx]);if(hitLeaves.length>0){var branchData=currentHits.branchMap[branchIdx];hitBranches.push({branchData:branchData,hitLeaves:hitLeaves})}}return hitBranches};HitsCollector.prototype.createEmptyIstanbulModule=function(path,useDataKey){if(useDataKey===void 0){useDataKey=false}var emptyModule={f:{},fnMap:{},b:{},branchMap:{},path:path,s:{}};if(useDataKey){return{data:emptyModule}}return emptyModule};HitsCollector.prototype.getFileCoverageObjects=function(filename){var fileCoverageSnapshot=this._latestCoverageSnapshot[filename]||this.createEmptyIstanbulModule(filename);var currentFileCoverage=this._globalCoverageObject[filename];var shouldResolveRelativePath=true;if(!fileCoverageSnapshot.f&&fileCoverageSnapshot.data){fileCoverageSnapshot=fileCoverageSnapshot.data;shouldResolveRelativePath=false}if(!currentFileCoverage.f&&currentFileCoverage.data){currentFileCoverage=currentFileCoverage.data}return{fileCoverageSnapshot:fileCoverageSnapshot,currentFileCoverage:currentFileCoverage,shouldResolveRelativePath:shouldResolveRelativePath}};HitsCollector.prototype.getGlobalCoverageObject=function(){if(this._globalCoverageObject)return this._globalCoverageObject;this._globalCoverageObject=HitsCollector.resolveGlobalCoverageObject();if(!this._globalCoverageObject){this.logger.warn("Coverage object not found")}return this._globalCoverageObject};HitsCollector.resolveGlobalCoverageObject=function(){var re=/^\$\$cov_[0-9]+\$\$$/;var keys=Object.keys(global);for(var i=0;i<keys.length;i++){var k=keys[i];if(re.exec(k)!==null||GLOBAL_ISTANBUL_CONTAINER_NAMES.indexOf(k)>=0){return global[k]}}};HitsCollector.prototype.updateCoverageSnapshot=function(currentCounters){for(var istanbulModule in currentCounters){var useDataKey=currentCounters[istanbulModule].data!==undefined;this._latestCoverageSnapshot[istanbulModule]=this._latestCoverageSnapshot[istanbulModule]||this.createEmptyIstanbulModule(istanbulModule,useDataKey);var f=currentCounters[istanbulModule].f||currentCounters[istanbulModule].data.f;var b=currentCounters[istanbulModule].b||currentCounters[istanbulModule].data.b;for(var funcId in f){this.setFunctionHit(istanbulModule,funcId,f,useDataKey)}for(var branchId in b){this.setBranchHit(b,branchId,istanbulModule,useDataKey)}}};HitsCollector.prototype.setBranchHit=function(b,branchId,istanbulModule,useDataKey){var currentBranchesHits=b[branchId];this._latestCoverageSnapshot[istanbulModule].b[branchId]=this._latestCoverageSnapshot[istanbulModule].b[branchId]||[];for(var i=0;i<currentBranchesHits.length;i++){if(useDataKey){this._latestCoverageSnapshot[istanbulModule].data.b[branchId][i]=currentBranchesHits[i]}else{
31
+ this._latestCoverageSnapshot[istanbulModule].b[branchId][i]=currentBranchesHits[i]}}};HitsCollector.prototype.setFunctionHit=function(istanbulModule,funcId,f,useDataKey){if(useDataKey){this._latestCoverageSnapshot[istanbulModule].data.f[funcId]=f[funcId]}else{this._latestCoverageSnapshot[istanbulModule].f[funcId]=f[funcId]}};return HitsCollector}();exports.HitsCollector=HitsCollector})}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../constants/sl-env-vars":305,"../coverage-elements/original-module-loader":310}],319:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../constants/sl-env-vars","../coverage-elements/original-module-loader","./hits-collector","../coverage-elements/new-id-resolver","../agent-events/cockpit-notifier"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HitsConverter=void 0;var sl_env_vars_1=require("../constants/sl-env-vars");var original_module_loader_1=require("../coverage-elements/original-module-loader");var hits_collector_1=require("./hits-collector");var new_id_resolver_1=require("../coverage-elements/new-id-resolver");var cockpit_notifier_1=require("../agent-events/cockpit-notifier");var HitsConverter=function(){function HitsConverter(relativePathResolver,sourceMapData,projectRoot,logger){this.conversionErrors=[];this.relativePathResolver=relativePathResolver;this.sourceMapData=sourceMapData;this.projectRoot=projectRoot;this.logger=logger}HitsConverter.prototype.convertHits=function(hitFilesData){var _this=this;var methodUniqueIds=[];var branchUniqueIds=[];if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){new original_module_loader_1.OriginalModuleLoader(hits_collector_1.HitsCollector.resolveGlobalCoverageObject(),this.logger).load()}hitFilesData.forEach(function(fileHit){var relativePath=fileHit.filename;if(fileHit.shouldResolveRelativePath){relativePath=_this.relativePathResolver.getRelativePath(fileHit.filename)}methodUniqueIds=methodUniqueIds.concat(_this.createMethodIds(fileHit.hitMethods,relativePath,fileHit.filename));branchUniqueIds=branchUniqueIds.concat(_this.createBranchIds(fileHit.hitBranches,relativePath,fileHit.filename))});this.sendConversionErrors();return{branches:branchUniqueIds,methods:methodUniqueIds}};HitsConverter.prototype.createMethodIds=function(hitFunctions,relativePath,absolutePath){var _this=this;var methodIds=[];hitFunctions.forEach(function(hit){methodIds.push(_this.getMethodUniqueId(_this.getStartLoc(hit),relativePath,absolutePath));if(_this.getDecl(hit)&&_this.getDeclStart(hit)){methodIds.push(_this.getMethodUniqueId(_this.getDeclStart(hit),relativePath,absolutePath))}});return methodIds};HitsConverter.prototype.getDeclStart=function(hit){return hit.decl.start};HitsConverter.prototype.getDecl=function(hit){return hit.decl};HitsConverter.prototype.getStartLoc=function(hit){return hit.loc.start};HitsConverter.prototype.getLeaveStartLoc=function(hit,leaveIdx,absolutePath){var _a;var position=hit.branchData.locations[leaveIdx].start;var parentPosition=(_a=hit.branchData.loc)===null||_a===void 0?void 0:_a.start;if(!parentPosition){if(!sl_env_vars_1.SlEnvVars.isUseIstanbul()){var message="'SL_useIstanbul' was set to 'false' but could not find 'loc' object. branch in file '"+absolutePath+"' at '"+JSON.stringify(position)+"'";this.logger.error(message);this.conversionErrors.push(message)}else{this.logger.debug("Using branch position from 'locations' object due to 'SL_useIstanbul' set to 'true'")}return position}var newInstrumentation=parentPosition.line!=position.line||parentPosition.column!=position.column;if(hit.branchData.type==="if"){var message=newInstrumentation?"Instrumented done by istanbul-lib-instrumenter greater or equal than 5.1.0 enforcing parent positions for the else leave":"Instrumented done by istanbul-lib-instrumenter lower than 5.1.0 using parent positions for the else leave";this.logger.debug(message);return parentPosition}return position};HitsConverter.prototype.createBranchIds=function(hitFunctions,relativePath,absolutePath){var _this=this;var branchIds=[];hitFunctions.forEach(function(hit){hit.hitLeaves.forEach(function(leaveIdx){branchIds.push(_this.getBranchUniqueId(_this.getLeaveStartLoc(hit,leaveIdx,absolutePath),relativePath,absolutePath,leaveIdx))})});return branchIds};HitsConverter.prototype.getMethodUniqueId=function(startLoc,relativePath,absolutePath){var idParts=this.resolveIdParts(startLoc,relativePath,absolutePath);if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){var uniqueIdKey=idParts.relativePath+"@"+this.formatLoc(idParts.start);var uniqueId=new_id_resolver_1.resolveNewId(uniqueIdKey,idParts.absolutePath,idParts.relativePath,hits_collector_1.HitsCollector.resolveGlobalCoverageObject(),this.logger);if(uniqueId){return uniqueId}}return this.buildMethodUniqueId(idParts)};HitsConverter.prototype.getBranchUniqueId=function(startLoc,relativePath,absolutePath,leaveIndex){var uniqueId;var parts=this.resolveIdParts(startLoc,relativePath,absolutePath);if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){var uniqueIdKey=parts.relativePath+"|"+this.formatLoc(parts.start)+"|"+leaveIndex;uniqueId=new_id_resolver_1.resolveNewId(uniqueIdKey,parts.absolutePath,parts.relativePath,hits_collector_1.HitsCollector.resolveGlobalCoverageObject(),this.logger)}if(!uniqueId){uniqueId=parts.relativePath+HitsConverter.BRANCH_ID_DEL+this.formatLoc(parts.start)+HitsConverter.BRANCH_ID_DEL+leaveIndex}return uniqueId};HitsConverter.prototype.resolveIdParts=function(startLoc,relativePath,absolutePath){var sourcePosition=this.sourceMapData.getSourcePosition(relativePath,absolutePath,startLoc,this.projectRoot);return sourcePosition?sourcePosition:{relativePath:relativePath,start:startLoc,absolutePath:absolutePath}};HitsConverter.prototype.buildMethodUniqueId=function(parts){return parts.relativePath+HitsConverter.METHOD_ID_DEL+this.formatLoc(parts.start)};HitsConverter.prototype.sendConversionErrors=function(){if(this.conversionErrors.length>0){cockpit_notifier_1.CockpitNotifier.sendErrorsBatch(this.conversionErrors);this.conversionErrors=[]}};HitsConverter.prototype.formatLoc=function(loc){return loc.line+","+loc.column};HitsConverter.METHOD_ID_DEL="@";HitsConverter.BRANCH_ID_DEL="|";return HitsConverter}();exports.HitsConverter=HitsConverter})},{"../agent-events/cockpit-notifier":294,"../constants/sl-env-vars":305,"../coverage-elements/new-id-resolver":309,"../coverage-elements/original-module-loader":310,"./hits-collector":318}],320:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./footprints-buffer","../footprints-process/collection-interval","../state-tracker","../agent-events/cockpit-notifier","../agent-events/agent-events-conracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsProcess=void 0;var footprints_buffer_1=require("./footprints-buffer");var collection_interval_1=require("../footprints-process/collection-interval");var state_tracker_1=require("../state-tracker");var cockpit_notifier_1=require("../agent-events/cockpit-notifier");var agent_events_conracts_1=require("../agent-events/agent-events-conracts");var FootprintsProcess=function(){function FootprintsProcess(cfg,sendToServerWatchdog,keepaliveWatchdog,logger,hitsCollector,hitsConverter,footprintsBuffer,backendProxy,stateTracker){this.isRunning=false;this.ongoingRequestsCounter=0;this.footprintsEnqueueOnce=false;this.cfg=cfg;this.sendToServerWatchdog=sendToServerWatchdog;this.keepaliveWatchdog=keepaliveWatchdog;this.footprintsBuffer=footprintsBuffer;this.hitsConverter=hitsConverter;this.hitsCollector=hitsCollector;this.backendProxy=backendProxy;this.collectionInterval=new collection_interval_1.CollectionInterval(cfg.interval.value);this.stateTracker=stateTracker;this.logger=logger;this.delegateEvents()}FootprintsProcess.prototype.enqueueCurrentFootprints=function(executionId,testName,executionBsid,isFinalFootprints){if(isFinalFootprints===void 0){isFinalFootprints=false}this.currentExecutionBsid=executionBsid;this.collectionInterval.next();var hitFilesData=this.hitsCollector.getHitElements();if(hitFilesData.length){this.logger.info("Collecting hits for '"+hitFilesData.length+"' files");var convertedHits=this.hitsConverter.convertHits(hitFilesData);this.footprintsBuffer.addHit(convertedHits,this.collectionInterval.toJson(),executionId,testName,this.isInitFootprints(),isFinalFootprints)}else{this.logger.info("No files were hits, not collecting footprints")}if(this.isRunning&&this.cfg.sendFootprints.value&&this.cfg.enabled.value){this.ensureKeepaliveThreadRunning();this.sendToServerWatchdog.start()}this.footprintsEnqueueOnce=true};FootprintsProcess.prototype.updateConfig=function(updatedCfg){this.cfg=updatedCfg;if(updatedCfg.sendFootprints.value===false||updatedCfg.enabled.value===false){cockpit_notifier_1.CockpitNotifier.sendEvent(agent_events_conracts_1.AgentEventCode.AGENT_MUTED);this.footprintsBuffer.resetState();this.stop(function(){})}this.sendToServerWatchdog.setInterval(this.cfg.footprintsSendIntervalSecs.value);this.footprintsBuffer.agentConfig=updatedCfg};FootprintsProcess.prototype.ensureKeepaliveThreadRunning=function(){this.keepaliveWatchdog.start()};FootprintsProcess.prototype.submitQueuedFootprints=function(){return __awaiter(this,void 0,void 0,function(){var packet,e_1;return __generator(this,function(_a){switch(_a.label){case 0:if(!this.shouldSubmitFootprints()){return[2]}packet=this.footprintsBuffer.createPacket();if(!packet)return[3,6];this.ongoingRequestsCounter++;_a.label=1;case 1:_a.trys.push([1,3,4,5]);return[4,this.backendProxy.submitFootprintsV6(packet,this.currentExecutionBsid,this.stateTracker.getTestStage(),this.cfg.buildSessionId.value)];case 2:_a.sent();this.logger.info("Footprints packet submitted successfully. packet contains "+packet.methods.length+" methods, "+packet.branches.length+" branches in "+packet.executions.length+" executions");return[3,5];case 3:e_1=_a.sent();this.logger.error("Error while submitting footprints '"+e_1+"'");cockpit_notifier_1.CockpitNotifier.sendEvent(agent_events_conracts_1.AgentEventCode.FOOTPRINTS_LOSS);return[3,5];case 4:this.ongoingRequestsCounter--;return[7];case 5:return[3,7];case 6:this.logger.info("No hits collected nothing to submit");_a.label=7;case 7:return[2]}})})};FootprintsProcess.prototype.shouldSubmitFootprints=function(){if(!this.isRunning){this.logger.info("Agent is not running, not sending footprints");return false}if(this.cfg.sendFootprints.value===false){this.logger.info("Not sending footprints since agent is configured to not send.");return false}return true};FootprintsProcess.prototype.start=function(){if(this.isRunning)return;if(this.cfg.enabled.value==false)return;this.isRunning=true;this.sendToServerWatchdog.start();if(this.footprintsBuffer.hasHitsInBuffer()){this.ensureKeepaliveThreadRunning()}};FootprintsProcess.prototype.stop=function(callback){var _this=this;this.sendToServerWatchdog.stop();if(!this.shouldSubmitFootprints()){this.isRunning=false;return callback()}this.isRunning=false;this.flushCurrentFootprints(true);var packet=this.footprintsBuffer.createPacket();if(!packet){this.logger.info("No hits collected, nothing to submit");return callback()}this.logger.debug("Start submitting footprints, triggered by stop event.");this.backendProxy.submitFootprintsV6(packet,this.currentExecutionBsid,this.stateTracker.getTestStage(),this.cfg.buildSessionId.value).then(callback).catch(function(err){_this.logger.error(err);return callback()})};FootprintsProcess.prototype.handleTestIdChanged=function(newTestIdentifier,previousTestIdentifier){if(previousTestIdentifier==null){this.logger.info("Test identifier changed, previous identifier wasn't set, meaning that we didn't have active test. Skip enqueuing footprints process.")}else{if(!this.stateTracker.shouldCollectHits()){this.logger.info("Test identifier changed, couldn't find active execution for anonymous footprints. Skip enqueuing footprints process.");return}this.logger.debug("Test identifier changed, start enqueuing footprints process.");var prevTestIdentifierParts=state_tracker_1.StateTracker.splitTestIdToExecutionAndTestName(previousTestIdentifier);this.enqueueCurrentFootprints(this.stateTracker.currentExecution.executionId,prevTestIdentifierParts.testName,this.stateTracker.currentExecution.buildSessionId)}};FootprintsProcess.prototype.delegateEvents=function(){var _this=this;this.sendToServerWatchdog.on(FootprintsProcess.ALARM_FIRED,function(){_this.logger.debug("Start submitting footprints, triggered by send to server watchdog.");_this.submitQueuedFootprints()});this.keepaliveWatchdog.on(FootprintsProcess.ALARM_FIRED,function(){if(!_this.hasOngoingRequests()&&!_this.footprintsBuffer.hasHitsInBuffer()){_this.keepaliveWatchdog.stop()}});this.footprintsBuffer.on(footprints_buffer_1.FootprintsBuffer.BUFFER_FULL,function(){_this.submitQueuedFootprints()});this.stateTracker.on(state_tracker_1.StateTracker.EXECUTION_BSID_CHANGED,function(prevExecution,newBuildSession){_this.logger.warn("Execution points to different build session '"+newBuildSession+"'. Collecting and submitting previous footprints");_this.enqueueAndSubmit(prevExecution)});this.stateTracker.on(state_tracker_1.StateTracker.EXECUTION_ID_CHANGED,function(prevExecution,newExecutionId){_this.logger.warn("Execution id changed to'"+newExecutionId+"'. Collecting previous footprints");_this.enqueueCurrentFootprints(prevExecution.executionId,null,prevExecution.buildSessionId)});this.stateTracker.on(state_tracker_1.StateTracker.TEST_STAGE_CHANGED,function(prevExecution,newTestStage){_this.logger.warn("Execution points to different test stage '"+newTestStage+"'. Collecting and submitting previous footprints");_this.enqueueAndSubmit(prevExecution)})};FootprintsProcess.prototype.enqueueAndSubmit=function(executionData,isFinalFootprints){if(isFinalFootprints===void 0){isFinalFootprints=false}this.enqueueCurrentFootprints(executionData.executionId,null,executionData.buildSessionId,isFinalFootprints);this.submitQueuedFootprints()};FootprintsProcess.prototype.flushCurrentFootprints=function(isFinalFootprints){if(isFinalFootprints===void 0){isFinalFootprints=false}var currentTestIdentifier=this.stateTracker.getCurrentTestIdentifier();if(currentTestIdentifier){var testIdentifierParts=state_tracker_1.StateTracker.splitTestIdToExecutionAndTestName(currentTestIdentifier);this.logger.debug("Enqueue footprints interval - start enqueuing process. currentTestIdentifier: '%s'",currentTestIdentifier);this.enqueueCurrentFootprints(this.stateTracker.currentExecution.executionId,testIdentifierParts.testName,this.stateTracker.currentExecution.buildSessionId,isFinalFootprints)}else if(this.stateTracker.shouldCollectHits()){this.logger.debug("Enqueue footprints interval - start enqueuing process. anonymous footprints");this.enqueueCurrentFootprints(this.stateTracker.currentExecution.executionId,null,this.stateTracker.currentExecution.buildSessionId,isFinalFootprints)}else{this.logger.info("Enqueue footprints interval - no active execution. skip enqueuing process.");this.handleNoExecutionFound()}};FootprintsProcess.prototype.handleNoExecutionFound=function(){if(this.stateTracker.openExecutionFoundOnce){this.logger.debug("No active execution and not in initFootprints mode, updating coverage snapshot");this.hitsCollector.dropHits()}};FootprintsProcess.prototype.isInitFootprints=function(){return this.stateTracker.openExecutionFoundOnce&&!this.footprintsEnqueueOnce};FootprintsProcess.prototype.hasOngoingRequests=function(){return this.ongoingRequestsCounter>0};FootprintsProcess.ALARM_FIRED="alarm";return FootprintsProcess}();exports.FootprintsProcess=FootprintsProcess})},{"../agent-events/agent-events-conracts":289,"../agent-events/cockpit-notifier":294,"../footprints-process/collection-interval":323,"../state-tracker":331,"./footprints-buffer":317}],321:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.formatLocation=void 0;function formatLocation(position,logger){if(position.hasOwnProperty("line")&&position.hasOwnProperty("column")){return position.line+","+position.column}else if(position.hasOwnProperty("l")&&position.hasOwnProperty("c")){return position.l+","+position.c}logger.error("Position is not in a valid format got '"+tryStringifyPosition(position)+"', returning -1 for line and column");return"-1,-1"}exports.formatLocation=formatLocation;function tryStringifyPosition(position){try{return JSON.stringify(position)}catch(e){"failed to stringify position '"+e+"'"}}})},{}],322:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RelativePathResolver=void 0;var RelativePathResolver=function(){function RelativePathResolver(projectRoot){this.absoluteToRelativePath=new Map;this.projectRoot=projectRoot}RelativePathResolver.prototype.getRelativePath=function(absolutePath){if(!this.absoluteToRelativePath.get(absolutePath)){absolutePath=this.adjustPathSlashes(absolutePath);var relativePath=absolutePath.replace(this.resolveProjectRoot(),"");if(relativePath.indexOf("/")===0){relativePath=relativePath.substring(1)}this.absoluteToRelativePath.set(absolutePath,relativePath)}return this.absoluteToRelativePath.get(absolutePath)};RelativePathResolver.prototype.adjustPathSlashes=function(filePath){return(filePath||"").replace(/\\/g,"/")};RelativePathResolver.prototype.resolveProjectRoot=function(){return(this.projectRoot||process.cwd()).replace(/\\/g,"/")};return RelativePathResolver}();exports.RelativePathResolver=RelativePathResolver})}).call(this)}).call(this,require("_process"))},{_process:179}],323:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CollectionInterval=void 0;var system_date_1=require("../system-date");var CollectionInterval=function(){function CollectionInterval(intervalInMS){this.intervalInSeconds=this.toSeconds(intervalInMS);this.start=this.toSeconds(system_date_1.getSystemDateValueOf())}CollectionInterval.prototype.next=function(){if(this.end){this.start=this.end}this.end=this.toSeconds(system_date_1.getSystemDateValueOf());if(this.end-this.start>this.intervalInSeconds){this.start=this.end-this.intervalInSeconds}};CollectionInterval.prototype.toJson=function(){return{start:this.start,end:this.end}};CollectionInterval.prototype.toSeconds=function(time){return Math.floor(time/1e3)};return CollectionInterval}();exports.CollectionInterval=CollectionInterval})},{"../system-date":332}],324:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./contracts","./http-client","./sl-routes","../utils/validation-utils","./entities-mapper","../constants/constants","../constants/sl-env-vars","../utils/timer-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BackendProxy=void 0;var contracts_1=require("./contracts");var http_client_1=require("./http-client");var sl_routes_1=require("./sl-routes");var validation_utils_1=require("../utils/validation-utils");var entities_mapper_1=require("./entities-mapper");var constants_1=require("../constants/constants");var sl_env_vars_1=require("../constants/sl-env-vars");var timer_utils_1=require("../utils/timer-utils");var BackendProxy=function(){function BackendProxy(agentInstanceData,config,logger,httpClient){this.agentInstanceData=agentInstanceData;this.config=config;this.logger=logger;this.client=httpClient||new http_client_1.HttpClient(this.config,this.logger)}BackendProxy.prototype.getBuildSession=function(buildSessionId,callback){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(buildSessionId,constants_1.Constants.BUILD_SESSION_ID);var url=sl_routes_1.SLRoutes.buildSessionV2(buildSessionId);this.client.get(url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.createBuildSessionId=function(request,callback){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.buildSessionV2();this.client.post(request,url,function(err,body){_this.invokeCallback(callback,err,body,entities_mapper_1.EntitiesMapper.toCreateBuildSessionIdResponse)})};BackendProxy.prototype.createBuildSessionIdPromise=function(request){return __awaiter(this,void 0,void 0,function(){var url;var _this=this;return __generator(this,function(_a){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);url=constants_1.Constants.PULL_REQUEST_PARAMS in request?sl_routes_1.SLRoutes.prBuildSession():sl_routes_1.SLRoutes.buildSessionV2();return[2,new Promise(function(resolve,reject){_this.client.post(request,url,function(err,body){if(err){return reject(err)}return resolve(body)})})]})})};BackendProxy.prototype.getRecommendedVersion=function(request){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.recommendedAgentV2(request.componentName,request.customerId,request.appName,request.branchName,request.testStage);return new Promise(function(resolve,reject){_this.client.get(url,function(err,body){if(err){return reject(err)}else if(body&&body.agent&&body.agent){return resolve(body.agent)}else{return reject(new Error("Failed to get recommended version due to unexpected response from the server."))}})})};BackendProxy.prototype.submitBuildMapping=function(request){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.buildMappingV4();return this.submitPostRequestWithRetries(request,url)};BackendProxy.prototype.submitLogs=function(request,callback){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.logSubmissionV2();this.client.post(request,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.getRemoteConfig=function(request,callback){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.configV3(this.agentInstanceData,request.appName,request.branch,request.build,request.testStage,request.labId);this.client.get(url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.getRemoteConfigPromise=function(request){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);return new Promise(function(resolve,reject){var url=sl_routes_1.SLRoutes.configV3(_this.agentInstanceData,request.appName,request.branch,request.build,request.testStage,request.labId);_this.client.get(url,function(err,body){if(err){reject(err)}resolve(body)})})};BackendProxy.prototype.startExecution=function(request,callback){var _this=this;var url=sl_routes_1.SLRoutes.testExecution();this.client.post(request,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.startColoredExecution=function(request){var _this=this;return new Promise(function(resolve,reject){var url=sl_routes_1.SLRoutes.testExecution();_this.client.post(request,url,function(err){if(err){reject(err)}resolve()})})};BackendProxy.prototype.testExecutionV4=function(labId,async,executionId){var _this=this;if(async===void 0){async=true}return new Promise(function(resolve,reject){var url=sl_routes_1.SLRoutes.testExecutionV4(labId);_this.client.get(url,function(err,body){if(err){reject(err)}resolve(body)},false,async)})};BackendProxy.prototype.uploadReport=function(request,callback){var _this=this;var url=sl_routes_1.SLRoutes.externalData();this.client.postMultipart(request,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.externalReport=function(request,callback){var _this=this;var url=sl_routes_1.SLRoutes.externalReport();this.client.post(request,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.endExecution=function(request,callback){var _this=this;var url=sl_routes_1.SLRoutes.endExecution(request.customerId,request.appName,request.buildName,request.branchName,request.environment);var body=request.executionIds?{executionIds:request.executionIds}:null;this.client.delete(body,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.endExecutionPromise=function(request){var _this=this;var url=sl_routes_1.SLRoutes.endExecution(request.customerId,request.appName,request.buildName,request.branchName,request.environment);var body=request.executionIds?{executionIds:request.executionIds}:null;return new Promise(function(resolve,reject){_this.client.delete(body,url,function(err){err?reject(err):resolve()})})};BackendProxy.prototype.submitEvents=function(packetToSend,callback,async){if(async===void 0){async=true}var url=sl_routes_1.SLRoutes.eventsV2();this.client.post(packetToSend,url,callback)};BackendProxy.prototype.submitEventsPromise=function(packetToSend){var _this=this;return new Promise(function(resolve,reject){var url=sl_routes_1.SLRoutes.eventsV2();_this.client.post(packetToSend,url,function(err){if(err){reject(err)}resolve()})})};BackendProxy.prototype.submitBlobAsync=function(body,buildSessionId,blobId){var _this=this;var url=sl_routes_1.SLRoutes.blobs(buildSessionId,blobId);return new Promise(function(res,rej){_this.client.post(body,url,function(error){rej(error)},true,contracts_1.ContentType.OCTET_STREAM);res(null)})};BackendProxy.prototype.submitBlob=function(body,buildSessionId,blobId,callback){var url=sl_routes_1.SLRoutes.blobs(buildSessionId,blobId);this.client.post(body,url,callback,true,contracts_1.ContentType.OCTET_STREAM)};BackendProxy.prototype.getBlobsAsJson=function(buildSessionId){return __awaiter(this,void 0,void 0,function(){var slMapping,url,e_1;return __generator(this,function(_a){switch(_a.label){case 0:slMapping=[];_a.label=1;case 1:_a.trys.push([1,3,,4]);url=sl_routes_1.SLRoutes.blobsForBsidAsJson(buildSessionId);return[4,this.submitGetRequestWithRetries(url)];case 2:slMapping=_a.sent();return[3,4];case 3:e_1=_a.sent();this.logger.error(e_1);return[3,4];case 4:return[2,slMapping]}})})};BackendProxy.prototype.submitAgentEvent=function(body){var _this=this;var url=sl_routes_1.SLRoutes.agentEvents();return new Promise(function(resolve,reject){_this.client.post(body,url,function(error,response){if(error){return reject(error)}return resolve()})})};BackendProxy.prototype.getTestsRecommendation=function(buildSessionId,stage){var url=sl_routes_1.SLRoutes.testsRecommendations(buildSessionId,stage);return this.submitGetRequestWithRetries(url,null,null,[400,404],false)};BackendProxy.prototype.addOrUpdateIntegrationBuildComponents=function(buildSessionId,components,agentId){var url=sl_routes_1.SLRoutes.integrationBuildComponents(buildSessionId);return this.submitPutRequestWithRetries({components:components,agentId:agentId},url)}
32
+ ;BackendProxy.prototype.deleteIntegrationBuildComponents=function(buildSessionId,components,agentId){var url=sl_routes_1.SLRoutes.integrationBuildComponents(buildSessionId);return this.submitDelRequestWithRetries({components:components,agentId:agentId},url)};BackendProxy.prototype.buildEnd=function(data){return this.submitPostRequestWithRetries(data,sl_routes_1.SLRoutes.buildEnd())};BackendProxy.prototype.submitFootprintsV6=function(footprintsPacket,executionBsid,testStage,buildSessionId){return __awaiter(this,void 0,void 0,function(){var url;return __generator(this,function(_a){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(footprintsPacket,constants_1.Constants.FOOTPRINTS_PACKET);validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(executionBsid,constants_1.Constants.EXECUTION_BSID);validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(testStage,constants_1.Constants.TEST_STAGE);validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(buildSessionId,constants_1.Constants.BUILD_SESSION_ID);url=sl_routes_1.SLRoutes.footprintsV6(executionBsid,testStage,buildSessionId);return[2,this.submitPostRequestWithRetries(footprintsPacket,url,null,null,true,contracts_1.ContentType.OCTET_STREAM)]})})};BackendProxy.prototype.getBuildSessionData=function(buildSessionId){return __awaiter(this,void 0,void 0,function(){var _this=this;return __generator(this,function(_a){return[2,new Promise(function(resolve,reject){_this.getBuildSession(buildSessionId,function(err,response){err?reject(err):resolve(response)})})]})})};BackendProxy.prototype.getRecommendedAgent=function(configuration){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,{}]})})};BackendProxy.prototype.getBuildSessionDataFromLabId=function(labid){return __awaiter(this,void 0,void 0,function(){var url;return __generator(this,function(_a){url=sl_routes_1.SLRoutes.activeBuildSessionId(labid);return[2,this.submitGetRequestWithRetries(url)]})})};BackendProxy.prototype.invokeCallback=function(callback,err,body,map){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(callback,constants_1.Constants.CALLBACK);if(err!=null){return callback(err,body)}if(map==null){return callback(null,body)}var apiResponse=map(body);return callback(null,apiResponse)};BackendProxy.prototype.submitPostRequestWithRetries=function(body,url,retries,delayBetweenRetires,async,contentType){var _this=this;return this.makeRequestWithRetries(function(callback){_this.client.post(body,url,callback,async,contentType)},retries,delayBetweenRetires)};BackendProxy.prototype.submitPutRequestWithRetries=function(body,url,retries,delayBetweenRetires){var _this=this;return this.makeRequestWithRetries(function(callback){_this.client.put(body,url,callback)},retries,delayBetweenRetires)};BackendProxy.prototype.submitDelRequestWithRetries=function(body,url,retries,delayBetweenRetires){var _this=this;return this.makeRequestWithRetries(function(callback){_this.client.delete(body,url,callback)},retries,delayBetweenRetires)};BackendProxy.prototype.submitGetRequestWithRetries=function(url,retries,delayBetweenRetires,statusesForRetry,isNotFoundAcceptable){var _this=this;if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}return this.makeRequestWithRetries(function(callback){_this.client.get(url,callback,isNotFoundAcceptable)},retries,delayBetweenRetires,statusesForRetry)};BackendProxy.prototype.makeRequestWithRetries=function(doSingleRequest,retries,delayBetweenRetires,statusesForRetry){return __awaiter(this,void 0,void 0,function(){var retriesLeft,intervalBetweenRetries,lastError,bodyAndStatusCode,errAndStatusCode_1;return __generator(this,function(_a){switch(_a.label){case 0:retriesLeft=retries||sl_env_vars_1.SlEnvVars.getHttpMaxAttempts()||BackendProxy.DEFAULT_HTTP_MAX_ATTEMPTS;intervalBetweenRetries=delayBetweenRetires||sl_env_vars_1.SlEnvVars.getHttpAttemptInterval()||BackendProxy.DEFAULT_HTTP_ATTEMPT_INTERVAL;lastError=undefined;_a.label=1;case 1:_a.trys.push([1,3,,4]);retriesLeft--;return[4,new Promise(function(resolve,reject){doSingleRequest(function(err,body,statusCode){err?reject({err:err,statusCode:statusCode}):resolve({body:body,statusCode:statusCode})})})];case 2:bodyAndStatusCode=_a.sent();return[2,bodyAndStatusCode.body];case 3:errAndStatusCode_1=_a.sent();this.logger.info(errAndStatusCode_1);lastError=errAndStatusCode_1.err;if(!this.shouldRetryRequest(errAndStatusCode_1.statusCode,statusesForRetry)){return[3,7]}return[3,4];case 4:return[4,timer_utils_1.TimerUtils.sleep(intervalBetweenRetries)];case 5:_a.sent();_a.label=6;case 6:if(retriesLeft>0)return[3,1];_a.label=7;case 7:throw lastError}})})};BackendProxy.prototype.shouldRetryRequest=function(statusCode,statusesForRetry){if(statusesForRetry===void 0){statusesForRetry=[]}if(statusCode>=500||statusCode&&statusesForRetry.includes(statusCode))return true;return false};BackendProxy.DEFAULT_HTTP_MAX_ATTEMPTS=6;BackendProxy.DEFAULT_HTTP_ATTEMPT_INTERVAL=5*1e3;return BackendProxy}();exports.BackendProxy=BackendProxy})},{"../constants/constants":304,"../constants/sl-env-vars":305,"../utils/timer-utils":335,"../utils/validation-utils":336,"./contracts":325,"./entities-mapper":326,"./http-client":327,"./sl-routes":329}],325:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ContentType=exports.RecommendationSetStatus=exports.RecommendedTestReason=exports.UploadReportsBody=exports.EnvironmentData=exports.AgentData=exports.UploadReportRequest=exports.EndExecutionRequest=exports.StartExecutionRequest=exports.BaseRequest=exports.SubmitLogsRequest=exports.GetRemoteConfigRequest=exports.FileData=exports.DependencyData=exports.BuildMappingRequest=exports.VersionMetaQuery=exports.VersionMeta=exports.AgentInfo=exports.GetVersionResponse=exports.GetVersionRequest=exports.CreateBuildSessionIdResponse=exports.HttpClientConfigData=void 0;var system_date_1=require("../system-date");var HttpClientConfigData=function(){function HttpClientConfigData(){}return HttpClientConfigData}();exports.HttpClientConfigData=HttpClientConfigData;var CreateBuildSessionIdResponse=function(){function CreateBuildSessionIdResponse(){}return CreateBuildSessionIdResponse}();exports.CreateBuildSessionIdResponse=CreateBuildSessionIdResponse;var GetVersionRequest=function(){function GetVersionRequest(){}return GetVersionRequest}();exports.GetVersionRequest=GetVersionRequest;var GetVersionResponse=function(){function GetVersionResponse(){}return GetVersionResponse}();exports.GetVersionResponse=GetVersionResponse;var AgentInfo=function(){function AgentInfo(){}return AgentInfo}();exports.AgentInfo=AgentInfo;var VersionMeta=function(){function VersionMeta(){}return VersionMeta}();exports.VersionMeta=VersionMeta;var VersionMetaQuery=function(){function VersionMetaQuery(){}return VersionMetaQuery}();exports.VersionMetaQuery=VersionMetaQuery;var BuildMappingRequest=function(){function BuildMappingRequest(){}return BuildMappingRequest}();exports.BuildMappingRequest=BuildMappingRequest;var DependencyData=function(){function DependencyData(){}return DependencyData}();exports.DependencyData=DependencyData;var FileData=function(){function FileData(){}return FileData}();exports.FileData=FileData;var GetRemoteConfigRequest=function(){function GetRemoteConfigRequest(){}return GetRemoteConfigRequest}();exports.GetRemoteConfigRequest=GetRemoteConfigRequest;var SubmitLogsRequest=function(){function SubmitLogsRequest(){this.creationTime=system_date_1.getSystemDateValueOf()}return SubmitLogsRequest}();exports.SubmitLogsRequest=SubmitLogsRequest;var BaseRequest=function(){function BaseRequest(){}return BaseRequest}();exports.BaseRequest=BaseRequest;var StartExecutionRequest=function(_super){__extends(StartExecutionRequest,_super);function StartExecutionRequest(){return _super!==null&&_super.apply(this,arguments)||this}return StartExecutionRequest}(BaseRequest);exports.StartExecutionRequest=StartExecutionRequest;var EndExecutionRequest=function(_super){__extends(EndExecutionRequest,_super);function EndExecutionRequest(){return _super!==null&&_super.apply(this,arguments)||this}return EndExecutionRequest}(BaseRequest);exports.EndExecutionRequest=EndExecutionRequest;var UploadReportRequest=function(_super){__extends(UploadReportRequest,_super);function UploadReportRequest(){return _super!==null&&_super.apply(this,arguments)||this}return UploadReportRequest}(BaseRequest);exports.UploadReportRequest=UploadReportRequest;var AgentData=function(){function AgentData(){}return AgentData}();exports.AgentData=AgentData;var EnvironmentData=function(){function EnvironmentData(){}return EnvironmentData}();exports.EnvironmentData=EnvironmentData;var UploadReportsBody=function(){function UploadReportsBody(){}return UploadReportsBody}();exports.UploadReportsBody=UploadReportsBody;var RecommendedTestReason;(function(RecommendedTestReason){RecommendedTestReason["PINNED"]="pinned";RecommendedTestReason["IMPACTED"]="impacted";RecommendedTestReason["FAILED"]="failed"})(RecommendedTestReason=exports.RecommendedTestReason||(exports.RecommendedTestReason={}));var RecommendationSetStatus;(function(RecommendationSetStatus){RecommendationSetStatus["NOT_READY"]="notReady";RecommendationSetStatus["READY"]="ready";RecommendationSetStatus["NO_HISTORY"]="noHistory";RecommendationSetStatus["ERROR"]="error"})(RecommendationSetStatus=exports.RecommendationSetStatus||(exports.RecommendationSetStatus={}));var ContentType;(function(ContentType){ContentType["OCTET_STREAM"]="application/octet-stream";ContentType["JSON"]="application/json"})(ContentType=exports.ContentType||(exports.ContentType={}))})},{"../system-date":332}],326:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EntitiesMapper=void 0;var contracts_1=require("./contracts");var EntitiesMapper=function(){function EntitiesMapper(){}EntitiesMapper.toCreateBuildSessionIdResponse=function(body){if(body==null)return null;var response=new contracts_1.CreateBuildSessionIdResponse;response.buildSessionId=body;return response};return EntitiesMapper}();exports.EntitiesMapper=EntitiesMapper})},{"./contracts":325}],327:[function(require,module,exports){(function(process,Buffer){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./contracts","request","zlib","uuid/v1","../constants/sl-env-vars","./http-verb","../utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpClient=void 0;var contracts_1=require("./contracts");var request=require("request");var zlib=require("zlib");var uuid=require("uuid/v1");var sl_env_vars_1=require("../constants/sl-env-vars");var http_verb_1=require("./http-verb");var validation_utils_1=require("../utils/validation-utils");var HttpClient=function(){function HttpClient(cfg,logger){this.cfg=cfg;this.logger=logger;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(cfg,"cfg");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this.defaultTimeout=this.getDefaultTimeout()}HttpClient.prototype.get=function(urlPath,callback,isNotFoundAcceptable){if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}this.invokeHttpRequest(http_verb_1.HttpVerb.GET,urlPath,callback,null,null,null,isNotFoundAcceptable)};HttpClient.prototype.delete=function(body,urlPath,callback){this.invokeHttpRequest(http_verb_1.HttpVerb.DELETE,urlPath,callback,null,body)};HttpClient.prototype.put=function(requestData,urlPath,callback,async,contentType){return this.submitRequestWithBody(http_verb_1.HttpVerb.PUT,requestData,urlPath,callback,async,contentType)};HttpClient.prototype.post=function(requestData,urlPath,callback,async,contentType){return this.submitRequestWithBody(http_verb_1.HttpVerb.POST,requestData,urlPath,callback,async,contentType)};HttpClient.prototype.postMultipart=function(requestData,urlPath,callback){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(requestData,"requestData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(requestData.agentData,"requestData.agentData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(requestData.reportFile,"requestData.reportFile");var agentData=requestData.agentData;var reportFile=requestData.reportFile;try{var opts=this.createDefaultOptions(urlPath);var id=uuid();var onRequestCallback=this.createOnRequestCallback(http_verb_1.HttpVerb.POST,id,callback);this.logger.info("Sending "+http_verb_1.HttpVerb.POST+" request. Url: '"+opts.url+"', requestId: '"+id+"'");var req=request.post(opts,onRequestCallback);var form=req.form();form.append("file",JSON.stringify(agentData),{filename:"agentData",contentType:"multipart/form-data"});form.append("file",reportFile.buffer.toString(),{filename:"report",contentType:"multipart/form-data"})}catch(err){this.logger.error("Failed sending Http "+http_verb_1.HttpVerb.POST+" request to:'"+urlPath+"'. Error: '"+err+"'");return callback(err,null,null)}};HttpClient.prototype.submitRequestWithBody=function(verb,requestData,urlPath,callback,async,contentType){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(requestData,"requestData");var bufferToSend=Buffer.from(JSON.stringify(requestData));var shouldZip=this.cfg.compressRequests!=null?this.cfg.compressRequests:true;this.logger.debug("Sending buffer:"+bufferToSend.toString());if(shouldZip){zlib.gzip(bufferToSend,function(err,compressedBuf){if(err){_this.logger.warn("Failed while trying to compress the request data. Sending uncompressed data instead. Error: ",err);_this.invokeHttpRequest(verb,urlPath,callback,null,bufferToSend,contentType)}else{_this.invokeHttpRequest(verb,urlPath,callback,{"Content-Encoding":"gzip"},compressedBuf,contentType)}})}else{this.invokeHttpRequest(verb,urlPath,callback,null,bufferToSend,contentType)}};HttpClient.prototype.invokeHttpRequest=function(httpVerb,urlPath,callback,additionalHeaders,buffer,contentType,isNotFoundAcceptable){if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(httpVerb,"httpVerb");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(urlPath,"urlPath");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(callback,"callback");try{var opts=this.createDefaultOptions(urlPath,contentType);if(additionalHeaders){for(var header in additionalHeaders){opts.headers[header]=additionalHeaders[header]}}var id=uuid();var onRequestCallback=this.createOnRequestCallback(httpVerb,id,callback,isNotFoundAcceptable);this.logger.info("Sending "+httpVerb+" request. Url: '"+opts.url+"', requestId: '"+id+"'");if(httpVerb===http_verb_1.HttpVerb.GET){opts.json=true;request.get(opts,onRequestCallback)}else if(httpVerb===http_verb_1.HttpVerb.DELETE){if(buffer)opts.body=buffer;opts.json=true;request.delete(opts,onRequestCallback)}else if(httpVerb===http_verb_1.HttpVerb.POST){opts.body=buffer;request.post(opts,onRequestCallback)}else if(httpVerb===http_verb_1.HttpVerb.PUT){opts.body=buffer;request.put(opts,onRequestCallback)}else{new Error(httpVerb+" is not implemented yet.")}}catch(err){this.logger.error("Failed sending Http "+httpVerb+" request to:'"+urlPath+"'. Error: '"+err+"'");return callback(err,null,null)}};HttpClient.prototype.createOnRequestCallback=function(httpVerb,requestId,callback,isNotFoundAcceptable){var _this=this;if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}var handler=function(err,requestResponse,body){var txId=requestResponse&&requestResponse.headers&&requestResponse.headers["x-sl-txid"];if(err||requestResponse!=null&&(requestResponse.statusCode<200||requestResponse.statusCode>=400)){var statusCode=-1;if(requestResponse!=null){statusCode=requestResponse.statusCode;_this.logger.warn("Got "+statusCode+" in '"+httpVerb+"' request. Request id:'"+requestId+"', Transaction ID:'"+txId+"'.")}if(err){err=new Error("HttpClient failed. Error: "+err.message+", StatusCode: "+statusCode+", Stack: "+err.stack)}else if(statusCode===404&&isNotFoundAcceptable){err=null}else{var errorMessage="Server returned: "+statusCode+" status code in '"+httpVerb+"' request. Transaction ID:'"+txId+"'.";if(body)errorMessage+=Object.entries(JSON.parse(body)).map(function(_a){var key=_a[0],val=_a[1];return"\n\t"+key+": "+val}).join("");err=new Error(errorMessage)}return callback(err,body,statusCode)}_this.logger.debug("'"+httpVerb+"' request was completed successfully. Request id:'"+requestId+"'. statusCode: "+requestResponse.statusCode+" body: "+body+", Transaction ID: "+txId);if(body&&body.length>0&&typeof body=="string"){body=JSON.parse(body)}return callback(null,body,requestResponse.statusCode)};return handler};HttpClient.prototype.allowUntrustedCertificates=function(){process.env["NODE_TLS_REJECT_UNAUTHORIZED"]="0"};HttpClient.prototype.createDefaultOptions=function(urlPath,contentType){if(contentType===void 0){contentType=contracts_1.ContentType.JSON}var opts={url:this.cfg.server+urlPath,headers:{"Content-Type":contentType,Authorization:"Bearer "+this.cfg.token},timeout:this.defaultTimeout};opts["compressed"]=true;if(this.cfg.proxy!=null){opts.proxy=this.cfg.proxy;this.allowUntrustedCertificates()}return opts};HttpClient.prototype.getDefaultTimeout=function(){var timeout=sl_env_vars_1.SlEnvVars.getHttpTimeout();if(timeout==null){timeout=60*1e3*2}timeout=Number(timeout);this.logger.debug("Http timeout value is '"+timeout+"'.");return timeout};return HttpClient}();exports.HttpClient=HttpClient})}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{"../constants/sl-env-vars":305,"../utils/validation-utils":336,"./contracts":325,"./http-verb":328,_process:179,buffer:71,request:453,"uuid/v1":509,zlib:68}],328:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpVerb=void 0;var HttpVerb;(function(HttpVerb){HttpVerb["GET"]="GET";HttpVerb["POST"]="POST";HttpVerb["DELETE"]="DELETE";HttpVerb["PUT"]="PUT"})(HttpVerb=exports.HttpVerb||(exports.HttpVerb={}))})},{}],329:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../constants/constants","../utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SLRoutes=void 0;var constants_1=require("../constants/constants");var validation_utils_1=require("../utils/validation-utils");var SLRoutes=function(){function SLRoutes(){}SLRoutes.agentsV1=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV2=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V2)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV3=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV4=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V4)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV5=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V5)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV6=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V6)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.testExecution=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.toUri(SLRoutes.TEST_EXECUTION)};SLRoutes.testExecutionV4=function(labId,executionId){var url=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V4)+SLRoutes.toUri(SLRoutes.TEST_EXECUTION)+SLRoutes.toUri(labId);if(executionId){url+=SLRoutes.buildQueryParams({executionId:executionId})}return url};SLRoutes.endExecution=function(customerId,appName,buildName,branchName,environment){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(appName,"appName");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(customerId,"customerId");var result=SLRoutes.testExecution();var query={customerId:customerId,appName:appName,buildName:buildName,branchName:branchName,environment:environment};result+=SLRoutes.buildQueryParams(query);return result};SLRoutes.externalData=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.toUri(SLRoutes.EXTERNAL_DATA)};SLRoutes.externalReport=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.EXTERNAL_REPORT)};SLRoutes.configV3=function(agentInstanceData,appName,branchName,buildName,testStage,labId){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentInstanceData,"agentInstanceData");var result=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.CONFIG;var query={agentType:agentInstanceData.agentType,agentVersion:agentInstanceData.agentVersion,agentId:agentInstanceData.agentId};if(appName)query.appName=appName;if(branchName)query.branchName=branchName;if(buildName)query.buildName=buildName;if(testStage)query.testStage=testStage;if(labId)query.labId=labId;result+=SLRoutes.buildQueryParams(query);return result};SLRoutes.buildSessionV2=function(buildSessionId){var result=SLRoutes.agentsV2()+SLRoutes.toUri(SLRoutes.BUILD_SESSION_ID)+SLRoutes.toUri(buildSessionId);return result};SLRoutes.prBuildSession=function(){return SLRoutes.buildSessionV2()+SLRoutes.toUri(SLRoutes.PULL_REQUEST)};SLRoutes.logSubmissionV2=function(){var result=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V2)+SLRoutes.LOG_SUBMISSION;return result};SLRoutes.buildMappingV4=function(){var result=SLRoutes.agentsV4()+SLRoutes.toUri(SLRoutes.BUILD_MAPPING);return result};SLRoutes.footprintsV5=function(){var result=SLRoutes.agentsV5()+SLRoutes.toUri(SLRoutes.FOOTPRINTS);return result};SLRoutes.footprintsV6=function(executionBsid,testStage,buildSessionId){return SLRoutes.agentsV6()+SLRoutes.toUri(executionBsid)+SLRoutes.toUri(SLRoutes.FOOTPRINTS)+SLRoutes.toUri(testStage)+SLRoutes.toUri(buildSessionId)};SLRoutes.eventsV2=function(){return SLRoutes.agentsV2()+SLRoutes.toUri(SLRoutes.EVENTS)};SLRoutes.productionV1=function(buildSessionId){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(buildSessionId,"buildSessionId");var result=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.AGENTS)+SLRoutes.toUri(SLRoutes.PRODUCTION)+SLRoutes.toUri(SLRoutes.BSID)+SLRoutes.toUri(buildSessionId);return result};SLRoutes.recommendedAgentV2=function(component,customerId,appName,branchName,testStage){if(!component){throw new Error("'component' "+constants_1.Constants.Messages.CANNOT_BE_NULL_OR_UNDEFINED+".")}var result=SLRoutes.agentsV2()+SLRoutes.toUri(component)+SLRoutes.toUri(SLRoutes.RECOMMENDED_VERSION);var query={customerId:customerId,appName:appName,branch:branchName,envName:testStage};result+=SLRoutes.buildQueryParams(query);return result};SLRoutes.blobs=function(buildSessionId,blobId){return SLRoutes.agentsV1()+SLRoutes.toUri(SLRoutes.BLOBS)+SLRoutes.toUri(buildSessionId)+SLRoutes.toUri(blobId)};SLRoutes.blobsForBsidAsJson=function(buildSessionId){var url=SLRoutes.agentsV1()+SLRoutes.toUri(SLRoutes.BLOBS)+SLRoutes.toUri(buildSessionId);url=url.slice(0,-1);return url+SLRoutes.buildQueryParams({view:"concatJson"})};SLRoutes.agentEvents=function(){return SLRoutes.agentsV3()+SLRoutes.toUri(SLRoutes.AGENT_EVENTS)};SLRoutes.testsRecommendations=function(buildSessionId,stage){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V2)+SLRoutes.toUri(SLRoutes.TEST_EXCLUSIONS)+SLRoutes.toUri(buildSessionId)+SLRoutes.toUri(stage)};SLRoutes.integrationBuildComponents=function(buildSessionId){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.AGENTS+SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.INTEGRATION_BUILDS)+SLRoutes.toUri(buildSessionId)+SLRoutes.COMPONENTS};SLRoutes.buildEnd=function(){return SLRoutes.agentsV3()+SLRoutes.toUri(SLRoutes.BUILD_END)};SLRoutes.activeBuildSessionId=function(labid){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.LAB_IDS)+SLRoutes.toUri(labid)+SLRoutes.toUri(SLRoutes.BUILD_SESSIONS)+SLRoutes.toUri(SLRoutes.ACTIVE)};SLRoutes.toUri=function(uri){if(uri==null||uri.length==null||uri.length===0){return""}return encodeURIComponent(uri)+SLRoutes.SLASH};SLRoutes.buildQueryParams=function(paramsMap){if(!paramsMap){throw new Error("'paramsMap' cannot be null or undefined.")}var queryString="";for(var key in paramsMap){var value=paramsMap[key];queryString+=SLRoutes.addQueryStringValue(key,value)}queryString="?"+queryString;queryString=queryString.substring(0,queryString.length-1);return queryString};SLRoutes.addQueryStringValue=function(key,value){if(!key&&!value)return"";if(!value){value=""}var paramString="";paramString+=encodeURIComponent(key);paramString+="=";paramString+=encodeURIComponent(value);paramString+="&";return paramString};SLRoutes.SLASH="/";SLRoutes.V1="v1";SLRoutes.V2="v2";SLRoutes.V3="v3";SLRoutes.V4="v4";SLRoutes.V5="v5";SLRoutes.V6="v6";SLRoutes.AGENTS="agents";SLRoutes.EVENTS="events";SLRoutes.PRODUCTION="productiondata";SLRoutes.BSID="bsid";SLRoutes.BUILD_SESSION_ID="buildsession";SLRoutes.BUILD_MAPPING="buildmapping";SLRoutes.RECOMMENDED_VERSION="recommended";SLRoutes.CONFIG="config";SLRoutes.LOG_SUBMISSION="logsubmission";SLRoutes.FOOTPRINTS="footprints";SLRoutes.TEST_EXECUTION="testExecution";SLRoutes.EXTERNAL_DATA="externaldata";SLRoutes.EXTERNAL_REPORT="externalreport";SLRoutes.BLOBS="blobs";SLRoutes.AGENT_EVENTS="agent-events";SLRoutes.PULL_REQUEST="pull-request";SLRoutes.TEST_EXCLUSIONS="test-exclusions";SLRoutes.INTEGRATION_BUILDS="integration-builds";SLRoutes.COMPONENTS="components";SLRoutes.BUILD_END="buildend";SLRoutes.LAB_IDS="lab-ids";SLRoutes.BUILD_SESSIONS="build-sessions";SLRoutes.ACTIVE="active";return SLRoutes}();exports.SLRoutes=SLRoutes})},{"../constants/constants":304,"../utils/validation-utils":336}],330:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","fs","source-map"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SourceMapsUtils=void 0;var fs=require("fs");var sourceMap=require("source-map");var SourceMapsUtils=function(){function SourceMapsUtils(){}SourceMapsUtils.readSourceMaps=function(fullFilename){if(!fullFilename)return;var sourceMapsFilename=fullFilename+".map";var contents,rawSourceMapJsonData,consumer;try{contents=fs.readFileSync(sourceMapsFilename).toString()}catch(e){return null}try{rawSourceMapJsonData=JSON.parse(contents)}catch(e){console.error("[Sealights] Ignoring invalid source map: "+sourceMapsFilename);return null}try{consumer=new sourceMap.SourceMapConsumer(rawSourceMapJsonData);return consumer}catch(e){console.error("[Sealights] Error processing source maps for file: "+sourceMapsFilename);return null}};return SourceMapsUtils}();exports.SourceMapsUtils=SourceMapsUtils})},{fs:69,"source-map":228}],331:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","events","./constants/sl-env-vars","./utils/validation-utils","./agent-events/cockpit-notifier","./agent-events/agent-events-conracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StateTracker=void 0;var events=require("events");var sl_env_vars_1=require("./constants/sl-env-vars");var validation_utils_1=require("./utils/validation-utils");var cockpit_notifier_1=require("./agent-events/cockpit-notifier");var agent_events_conracts_1=require("./agent-events/agent-events-conracts");var INITIAL_COLOR="00000000-0000-0000-0000-000000000000/__init";var StateTracker=function(_super){__extends(StateTracker,_super);function StateTracker(cfg,configProcess,checkTestStatusWatchdog,backendProxy,logger){var _this=_super.call(this)||this;_this.currentTestIdentifier=null;_this.isRunning=false;_this._openExecutionFoundOnce=false
33
+ ;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(cfg,"agentConfig");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(configProcess,"configProcess");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(checkTestStatusWatchdog,"watchdog");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(backendProxy,"backendProxy");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");_this.cfg=cfg;_this.configProcess=configProcess;_this.checkTestStatusWatchdog=checkTestStatusWatchdog;_this.backendProxy=backendProxy;_this.logger=logger;if(_this.cfg.useInitialColor.value&&_this.currentTestIdentifier==null){_this.switchToAnonFootprints()}configProcess.on("configuration_changed",function(newCfg){if(newCfg.useInitialColor.value&&_this.currentTestIdentifier==null){_this.switchToAnonFootprints()}_this.cfg=newCfg;_this.checkTestStatusWatchdog.setInterval(newCfg.executionQueryIntervalSecs.value)});_this.startCheckingTestStatusAtServer();return _this}StateTracker.prototype.startCheckingTestStatusAtServer=function(){var _this=this;if(sl_env_vars_1.SlEnvVars.inProductionListenerMode()){this.logger.debug("In production listener, no need to check test status in server");return}this.checkTestStatusWatchdog.on("alarm",function(){_this.checkTestStatusAtServer()});if(this.cfg.shouldCheckForActiveExecutionOnStartUp.value){this.checkTestStatusAtServer(false)}};StateTracker.prototype.checkTestStatusAtServer=function(async){var _this=this;if(async===void 0){async=true}if(!this.currentTestIdentifier){this.logger.info("'currentTestIdentifier' is null. That means that footprints will not be sent.")}else{this.backendProxy.testExecutionV4(this.cfg.labId.value,async,this.getExecutionIdForQuery()).then(function(response){_this.fireExecutionEvents(response.execution);_this.notifyCockpit(response.execution);_this._currentExecution=response.execution}).catch(function(err){_this.logger.warn("Error while checking test execution status "+err)})}};StateTracker.prototype.getExecutionIdForQuery=function(){if(this.isAnonymousColor(this.currentTestIdentifier)||!this.currentExecution){return null}return this.currentExecution.executionId};StateTracker.prototype.hasMappingAtServer=function(){return this._currentExecution!=null};StateTracker.prototype.shouldCollectHits=function(){return this.hasMappingAtServer()};Object.defineProperty(StateTracker.prototype,"currentExecution",{get:function(){return this._currentExecution},set:function(value){this._currentExecution=value},enumerable:false,configurable:true});Object.defineProperty(StateTracker.prototype,"openExecutionFoundOnce",{get:function(){return this._openExecutionFoundOnce},enumerable:false,configurable:true});StateTracker.prototype.isAnonymousColor=function(testIdentifier){return INITIAL_COLOR==testIdentifier};StateTracker.prototype.switchToAnonFootprints=function(){this.logger.info("Switching to anonymous footprints.");this.setTestIdentifier(INITIAL_COLOR,false)};StateTracker.prototype.getCurrentTestIdentifier=function(){return this.currentTestIdentifier};StateTracker.prototype.setTestIdentifier=function(newTestIdentifier,silent){this.logger.info("setting test identifier: "+newTestIdentifier);if(this.currentTestIdentifier==null&&newTestIdentifier!=null||this.currentTestIdentifier!=null&&this.currentTestIdentifier!=newTestIdentifier&&newTestIdentifier!=INITIAL_COLOR){var previousTestIdentifier=this.currentTestIdentifier;this.currentTestIdentifier=newTestIdentifier;if(this.isRunning){if(!silent){this.emit("test_identifier_changed",this.currentTestIdentifier,previousTestIdentifier)}else{this.logger.info("Test identifier changed, running in silent mode not enqueuing footprints")}this.checkTestStatusWatchdog.reset()}}else{this.logger.info("Not setting the color. newTestIdentifier is '"+newTestIdentifier+"' "+"and currentTestIdentifier is '"+this.currentTestIdentifier+"'")}};StateTracker.prototype.setCurrentTestIdentifier=function(newTestIdentifier){this.setTestIdentifier(newTestIdentifier)};StateTracker.prototype.start=function(){if(!this.isRunning){this.checkTestStatusWatchdog.start();this.isRunning=true}};StateTracker.prototype.stop=function(callback){try{if(!this.isRunning){return callback()}this.checkTestStatusWatchdog.stop();this.isRunning=false;callback()}catch(err){this.logger.error("Error while stopping StateTracker. '"+err+"'");return callback()}};StateTracker.prototype.getTestStage=function(){return this.currentExecution&&this.currentExecution.testStage||this.cfg.testStage.value};StateTracker.splitTestIdToExecutionAndTestName=function(testId){testId=testId||"";var executionId=testId.split("/")[0];var testName=testId.indexOf("/")==-1?"":testId.substring(executionId.length+1);if(!executionId){testName=""}return{executionId:executionId,testName:testName}};StateTracker.combineExecutionIdAndTestName=function(executionId,testName){testName=testName||"";if(!executionId){return""}return executionId+"/"+testName};StateTracker.prototype.startColoredExecution=function(executionId){return __awaiter(this,void 0,void 0,function(){var request,e_1;return __generator(this,function(_a){switch(_a.label){case 0:_a.trys.push([0,2,,3]);request={appName:this.cfg.appName.value,branchName:this.cfg.branch.value,buildName:this.cfg.build.value,labId:this.cfg.labId.value,testStage:this.cfg.testStage.value,executionId:executionId};return[4,this.backendProxy.startColoredExecution(request)];case 1:_a.sent();this.currentExecution=__assign(__assign({},request),{buildSessionId:this.cfg.buildSessionId.value,status:StateTracker.EXECUTION_STATUS_CREATED});return[3,3];case 2:e_1=_a.sent();this.logger.error("Failed to create execution, error '"+e_1+"'. Footprints will not be sent");return[3,3];case 3:return[2]}})})};StateTracker.prototype.fireExecutionEvents=function(executionData){if(!executionData){return}if(!this.currentExecution){return}if(this.currentExecution.buildSessionId!=executionData.buildSessionId){this.emit(StateTracker.EXECUTION_BSID_CHANGED,this.currentExecution,executionData.buildSessionId);return}if(this.currentExecution.executionId!=executionData.executionId){this.emit(StateTracker.EXECUTION_ID_CHANGED,this.currentExecution,executionData.buildSessionId);return}if(this.currentExecution.testStage!=executionData.testStage){this.emit(StateTracker.TEST_STAGE_CHANGED,this.currentExecution,executionData.testStage);return}};StateTracker.prototype.notifyCockpit=function(execution){if(!execution){cockpit_notifier_1.CockpitNotifier.sendEventOnce(agent_events_conracts_1.AgentEventCode.FIRST_TIME_NO_EXECUTION)}else{cockpit_notifier_1.CockpitNotifier.sendEventOnce(agent_events_conracts_1.AgentEventCode.FIRST_TIME_HAS_EXECUTION);this._openExecutionFoundOnce=true}};StateTracker.EXECUTION_ENDS="executionEnds";StateTracker.EXECUTION_BSID_CHANGED="executionBsidChanged";StateTracker.EXECUTION_ID_CHANGED="executionIdChanged";StateTracker.TEST_STAGE_CHANGED="testStageChanged";StateTracker.EXECUTION_STATUS_CREATED="created";StateTracker.EXECUTION_STATUS_PENDING_DELETE="pendingDelete";return StateTracker}(events.EventEmitter);exports.StateTracker=StateTracker})},{"./agent-events/agent-events-conracts":289,"./agent-events/cockpit-notifier":294,"./constants/sl-env-vars":305,"./utils/validation-utils":336,events:110}],332:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getSystemDateValueOf=exports.getSystemDate=void 0;var SystemDate=Date;var SystemDateValueOf=Date.prototype.valueOf;function getSystemDate(){return new SystemDate}exports.getSystemDate=getSystemDate;function getSystemDateValueOf(){var date=getSystemDate();return SystemDateValueOf.call(date)}exports.getSystemDateValueOf=getSystemDateValueOf})},{}],333:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","path","fs"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FilesUtils=void 0;var path=require("path");var fs=require("fs");var FilesUtils=function(){function FilesUtils(){}FilesUtils.resolveOriginalFullFileName=function(fullPath,originalFilename){if(path.isAbsolute(originalFilename)){return originalFilename}var generatedDir=path.dirname(fullPath);originalFilename=path.resolve(generatedDir,originalFilename);return originalFilename};FilesUtils.prototype.fixPathAndSpecialChar=function(path){if(path){if(path[0]==="/"||path[0]==="\\"){return path.substr(1).split("\\").join("/")}return path.split("\\").join("/")}return path};FilesUtils.adjustPathSlashes=function(filePath){filePath=(filePath||"").replace(/\\/g,"/");return filePath};FilesUtils.findFileUp=function(file,folder){var parsed=path.parse(folder);var filePath=path.join(folder,file);if(fs.existsSync(filePath)){return filePath}if(path.resolve(folder)===parsed.root||folder==="."){return null}var parentFolder=path.join(folder,"..");parentFolder=path.normalize(parentFolder);return FilesUtils.findFileUp(file,parentFolder)};return FilesUtils}();exports.FilesUtils=FilesUtils})},{fs:69,path:171}],334:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ParsingUtils=void 0;var ParsingUtils=function(){function ParsingUtils(){}ParsingUtils.parseNumber=function(key){var valueFromEnv=process.env[key];if(valueFromEnv!=null){var valueAsNumber=Number.parseFloat(valueFromEnv);if(!isNaN(valueAsNumber)){valueFromEnv=valueAsNumber}else{valueFromEnv=null}}return valueFromEnv};ParsingUtils.parseBoolean=function(key){var valueFromEnv=process.env[key];if(valueFromEnv!=null&&typeof valueFromEnv=="string"){valueFromEnv=valueFromEnv.toLowerCase()}return valueFromEnv=="true"};return ParsingUtils}();exports.ParsingUtils=ParsingUtils})}).call(this)}).call(this,require("_process"))},{_process:179}],335:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TimerUtils=void 0;var TimerUtils=function(){function TimerUtils(){}TimerUtils.sleep=function(timeout){return new Promise(function(resolve){setTimeout(resolve,timeout)})};return TimerUtils}();exports.TimerUtils=TimerUtils})},{}],336:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../constants/constants"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ValidationUtils=void 0;var constants_1=require("../constants/constants");var ValidationUtils=function(){function ValidationUtils(){}ValidationUtils.verifyNotNullOrEmpty=function(value,paramName){if(value===undefined||value===null){throw new Error(paramName+" "+constants_1.Constants.Messages.CANNOT_BE_NULL_OR_UNDEFINED+".")}if(typeof value==="string"&&value.length===0){throw new Error(paramName+" "+constants_1.Constants.Messages.CANNOT_BE_EMPTY_STRING+".")}};return ValidationUtils}();exports.ValidationUtils=ValidationUtils})},{"../constants/constants":304}],337:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","events"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Watchdog=exports.WatchdogOptions=void 0;var events=require("events");var WatchdogOptions=function(){function WatchdogOptions(){}return WatchdogOptions}();exports.WatchdogOptions=WatchdogOptions;var Watchdog=function(_super){__extends(Watchdog,_super);function Watchdog(options,timers){var _this=_super.call(this)||this;_this.options=options;_this.timers=timers;_this.handle=null;_this.pendingAlarmDuringSuspended=false;_this.suspended=false;_this.stopped=true;if(!options){throw new Error("options is required")}if(!timers){throw new Error("timers is required")}return _this}Watchdog.prototype.abort=function(){if(this.handle){this.timers.clearTimeout(this.handle);this.handle=null;this.pendingAlarmDuringSuspended=false}};Watchdog.prototype.reset=function(){this.abort();if(!this.stopped){this.handle=this.timers.setTimeout(this.fireAlarm.bind(this),this.options.interval);if(this.options.unref&&this.handle.unref){this.handle.unref()}}};Watchdog.prototype.stop=function(){this.stopped=true;this.abort()};Watchdog.prototype.start=function(){this.stopped=false;this.reset()};Watchdog.prototype.getStatus=function(){return{pendingAlarmDuringSuspended:this.pendingAlarmDuringSuspended,running:!this.stopped,suspended:this.suspended}};Watchdog.prototype.suspend=function(){this.suspended=true};Watchdog.prototype.resume=function(){this.suspended=false;if(this.pendingAlarmDuringSuspended){this.pendingAlarmDuringSuspended=false;this.fireAlarm()}};Watchdog.prototype.fireAlarm=function(){this.handle=null;if(this.suspended){this.pendingAlarmDuringSuspended=true}else{try{this.emit("alarm",this)}catch(err){}}if(this.options.autoReset){this.reset()}};Watchdog.prototype.setInterval=function(newInterval){if(newInterval<=0)throw new Error("Invalid value for interval: "+newInterval);this.options.interval=newInterval};Watchdog.prototype.getInterval=function(){return this.options.interval};return Watchdog}(events.EventEmitter);exports.Watchdog=Watchdog})},{events:110}],338:[function(require,module,exports){"use strict";var compileSchema=require("./compile"),resolve=require("./compile/resolve"),Cache=require("./cache"),SchemaObject=require("./compile/schema_obj"),stableStringify=require("fast-json-stable-stringify"),formats=require("./compile/formats"),rules=require("./compile/rules"),$dataMetaSchema=require("./data"),util=require("./compile/util");module.exports=Ajv;Ajv.prototype.validate=validate;Ajv.prototype.compile=compile;Ajv.prototype.addSchema=addSchema;Ajv.prototype.addMetaSchema=addMetaSchema;Ajv.prototype.validateSchema=validateSchema;Ajv.prototype.getSchema=getSchema;Ajv.prototype.removeSchema=removeSchema;Ajv.prototype.addFormat=addFormat;Ajv.prototype.errorsText=errorsText;Ajv.prototype._addSchema=_addSchema;Ajv.prototype._compile=_compile;Ajv.prototype.compileAsync=require("./compile/async");var customKeyword=require("./keyword");Ajv.prototype.addKeyword=customKeyword.add;Ajv.prototype.getKeyword=customKeyword.get;Ajv.prototype.removeKeyword=customKeyword.remove;Ajv.prototype.validateKeyword=customKeyword.validate;var errorClasses=require("./compile/error_classes");Ajv.ValidationError=errorClasses.Validation;Ajv.MissingRefError=errorClasses.MissingRef;Ajv.$dataMetaSchema=$dataMetaSchema;var META_SCHEMA_ID="http://json-schema.org/draft-07/schema";var META_IGNORE_OPTIONS=["removeAdditional","useDefaults","coerceTypes","strictDefaults"];var META_SUPPORT_DATA=["/properties"];function Ajv(opts){if(!(this instanceof Ajv))return new Ajv(opts);opts=this._opts=util.copy(opts)||{};setLogger(this);this._schemas={};this._refs={};this._fragments={};this._formats=formats(opts.format);this._cache=opts.cache||new Cache;this._loadingSchemas={};this._compilations=[];this.RULES=rules();this._getId=chooseGetId(opts);opts.loopRequired=opts.loopRequired||Infinity;if(opts.errorDataPath=="property")opts._errorDataPathProperty=true;if(opts.serialize===undefined)opts.serialize=stableStringify;this._metaOpts=getMetaSchemaOptions(this);if(opts.formats)addInitialFormats(this);if(opts.keywords)addInitialKeywords(this);addDefaultMetaSchema(this);if(typeof opts.meta=="object")this.addMetaSchema(opts.meta);if(opts.nullable)this.addKeyword("nullable",{metaSchema:{type:"boolean"}});addInitialSchemas(this)}function validate(schemaKeyRef,data){var v;if(typeof schemaKeyRef=="string"){v=this.getSchema(schemaKeyRef);if(!v)throw new Error('no schema with key or ref "'+schemaKeyRef+'"')}else{var schemaObj=this._addSchema(schemaKeyRef);v=schemaObj.validate||this._compile(schemaObj)}var valid=v(data);if(v.$async!==true)this.errors=v.errors;return valid}function compile(schema,_meta){var schemaObj=this._addSchema(schema,undefined,_meta);return schemaObj.validate||this._compile(schemaObj)}function addSchema(schema,key,_skipValidation,_meta){if(Array.isArray(schema)){for(var i=0;i<schema.length;i++)this.addSchema(schema[i],undefined,_skipValidation,_meta);return this}var id=this._getId(schema);if(id!==undefined&&typeof id!="string")throw new Error("schema id must be string");key=resolve.normalizeId(key||id);checkUnique(this,key);this._schemas[key]=this._addSchema(schema,_skipValidation,_meta,true);return this}function addMetaSchema(schema,key,skipValidation){this.addSchema(schema,key,skipValidation,true);return this}function validateSchema(schema,throwOrLogError){var $schema=schema.$schema;if($schema!==undefined&&typeof $schema!="string")throw new Error("$schema must be a string");$schema=$schema||this._opts.defaultMeta||defaultMeta(this);if(!$schema){this.logger.warn("meta-schema not available");this.errors=null;return true}var valid=this.validate($schema,schema);if(!valid&&throwOrLogError){var message="schema is invalid: "+this.errorsText();if(this._opts.validateSchema=="log")this.logger.error(message);else throw new Error(message)}return valid}function defaultMeta(self){var meta=self._opts.meta;self._opts.defaultMeta=typeof meta=="object"?self._getId(meta)||meta:self.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:undefined;return self._opts.defaultMeta}function getSchema(keyRef){var schemaObj=_getSchemaObj(this,keyRef);switch(typeof schemaObj){case"object":return schemaObj.validate||this._compile(schemaObj);case"string":return this.getSchema(schemaObj);case"undefined":return _getSchemaFragment(this,keyRef)}}function _getSchemaFragment(self,ref){var res=resolve.schema.call(self,{schema:{}},ref);if(res){var schema=res.schema,root=res.root,baseId=res.baseId;var v=compileSchema.call(self,schema,root,undefined,baseId);self._fragments[ref]=new SchemaObject({ref:ref,fragment:true,schema:schema,root:root,baseId:baseId,validate:v});return v}}function _getSchemaObj(self,keyRef){keyRef=resolve.normalizeId(keyRef);return self._schemas[keyRef]||self._refs[keyRef]||self._fragments[keyRef]}function removeSchema(schemaKeyRef){if(schemaKeyRef instanceof RegExp){_removeAllSchemas(this,this._schemas,schemaKeyRef);_removeAllSchemas(this,this._refs,schemaKeyRef);return this}switch(typeof schemaKeyRef){case"undefined":_removeAllSchemas(this,this._schemas);_removeAllSchemas(this,this._refs);this._cache.clear();return this;case"string":var schemaObj=_getSchemaObj(this,schemaKeyRef);if(schemaObj)this._cache.del(schemaObj.cacheKey);delete this._schemas[schemaKeyRef];delete this._refs[schemaKeyRef];return this;case"object":var serialize=this._opts.serialize;var cacheKey=serialize?serialize(schemaKeyRef):schemaKeyRef;this._cache.del(cacheKey);var id=this._getId(schemaKeyRef);if(id){id=resolve.normalizeId(id);delete this._schemas[id];delete this._refs[id]}}return this}function _removeAllSchemas(self,schemas,regex){for(var keyRef in schemas){var schemaObj=schemas[keyRef];if(!schemaObj.meta&&(!regex||regex.test(keyRef))){self._cache.del(schemaObj.cacheKey);delete schemas[keyRef]}}}function _addSchema(schema,skipValidation,meta,shouldAddSchema){if(typeof schema!="object"&&typeof schema!="boolean")throw new Error("schema should be object or boolean");var serialize=this._opts.serialize;var cacheKey=serialize?serialize(schema):schema;var cached=this._cache.get(cacheKey);if(cached)return cached;shouldAddSchema=shouldAddSchema||this._opts.addUsedSchema!==false;var id=resolve.normalizeId(this._getId(schema));if(id&&shouldAddSchema)checkUnique(this,id);var willValidate=this._opts.validateSchema!==false&&!skipValidation;var recursiveMeta;if(willValidate&&!(recursiveMeta=id&&id==resolve.normalizeId(schema.$schema)))this.validateSchema(schema,true);var localRefs=resolve.ids.call(this,schema);var schemaObj=new SchemaObject({id:id,schema:schema,localRefs:localRefs,cacheKey:cacheKey,meta:meta});if(id[0]!="#"&&shouldAddSchema)this._refs[id]=schemaObj;this._cache.put(cacheKey,schemaObj);if(willValidate&&recursiveMeta)this.validateSchema(schema,true);return schemaObj}function _compile(schemaObj,root){if(schemaObj.compiling){schemaObj.validate=callValidate;callValidate.schema=schemaObj.schema;callValidate.errors=null;callValidate.root=root?root:callValidate;if(schemaObj.schema.$async===true)callValidate.$async=true;return callValidate}schemaObj.compiling=true;var currentOpts;if(schemaObj.meta){currentOpts=this._opts;this._opts=this._metaOpts}var v;try{v=compileSchema.call(this,schemaObj.schema,root,schemaObj.localRefs)}catch(e){delete schemaObj.validate;throw e}finally{schemaObj.compiling=false;if(schemaObj.meta)this._opts=currentOpts}schemaObj.validate=v;schemaObj.refs=v.refs;schemaObj.refVal=v.refVal;schemaObj.root=v.root;return v;function callValidate(){var _validate=schemaObj.validate;var result=_validate.apply(this,arguments);callValidate.errors=_validate.errors;return result}}function chooseGetId(opts){switch(opts.schemaId){case"auto":return _get$IdOrId;case"id":return _getId;default:return _get$Id}}function _getId(schema){if(schema.$id)this.logger.warn("schema $id ignored",schema.$id);return schema.id}function _get$Id(schema){if(schema.id)this.logger.warn("schema id ignored",schema.id);return schema.$id}function _get$IdOrId(schema){if(schema.$id&&schema.id&&schema.$id!=schema.id)throw new Error("schema $id is different from id");return schema.$id||schema.id}function errorsText(errors,options){errors=errors||this.errors;if(!errors)return"No errors";options=options||{};var separator=options.separator===undefined?", ":options.separator;var dataVar=options.dataVar===undefined?"data":options.dataVar;var text="";for(var i=0;i<errors.length;i++){var e=errors[i];if(e)text+=dataVar+e.dataPath+" "+e.message+separator}return text.slice(0,-separator.length)}function addFormat(name,format){if(typeof format=="string")format=new RegExp(format);this._formats[name]=format;return this}function addDefaultMetaSchema(self){var $dataSchema;if(self._opts.$data){$dataSchema=require("./refs/data.json");self.addMetaSchema($dataSchema,$dataSchema.$id,true)}if(self._opts.meta===false)return;var metaSchema=require("./refs/json-schema-draft-07.json");if(self._opts.$data)metaSchema=$dataMetaSchema(metaSchema,META_SUPPORT_DATA);self.addMetaSchema(metaSchema,META_SCHEMA_ID,true);self._refs["http://json-schema.org/schema"]=META_SCHEMA_ID}function addInitialSchemas(self){var optsSchemas=self._opts.schemas;if(!optsSchemas)return;if(Array.isArray(optsSchemas))self.addSchema(optsSchemas);else for(var key in optsSchemas)self.addSchema(optsSchemas[key],key)}function addInitialFormats(self){for(var name in self._opts.formats){var format=self._opts.formats[name];self.addFormat(name,format)}}function addInitialKeywords(self){for(var name in self._opts.keywords){var keyword=self._opts.keywords[name];self.addKeyword(name,keyword)}}function checkUnique(self,id){if(self._schemas[id]||self._refs[id])throw new Error('schema with key or id "'+id+'" already exists')}function getMetaSchemaOptions(self){var metaOpts=util.copy(self._opts);for(var i=0;i<META_IGNORE_OPTIONS.length;i++)delete metaOpts[META_IGNORE_OPTIONS[i]];return metaOpts}function setLogger(self){var logger=self._opts.logger;if(logger===false){self.logger={log:noop,warn:noop,error:noop}}else{if(logger===undefined)logger=console;if(!(typeof logger=="object"&&logger.log&&logger.warn&&logger.error))throw new Error("logger must implement log, warn and error methods");self.logger=logger}}function noop(){}},{"./cache":339,"./compile":343,"./compile/async":340,"./compile/error_classes":341,"./compile/formats":342,"./compile/resolve":344,"./compile/rules":345,"./compile/schema_obj":346,"./compile/util":348,"./data":349,"./keyword":377,"./refs/data.json":378,"./refs/json-schema-draft-07.json":380,"fast-json-stable-stringify":402}],339:[function(require,module,exports){"use strict";var Cache=module.exports=function Cache(){this._cache={}};Cache.prototype.put=function Cache_put(key,value){this._cache[key]=value};Cache.prototype.get=function Cache_get(key){return this._cache[key]};Cache.prototype.del=function Cache_del(key){delete this._cache[key]};Cache.prototype.clear=function Cache_clear(){this._cache={}}},{}],340:[function(require,module,exports){"use strict";var MissingRefError=require("./error_classes").MissingRef;module.exports=compileAsync;function compileAsync(schema,meta,callback){var self=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");if(typeof meta=="function"){callback=meta;meta=undefined}var p=loadMetaSchemaOf(schema).then(function(){var schemaObj=self._addSchema(schema,undefined,meta);return schemaObj.validate||_compileAsync(schemaObj)});if(callback){p.then(function(v){callback(null,v)},callback)}return p;function loadMetaSchemaOf(sch){var $schema=sch.$schema;return $schema&&!self.getSchema($schema)?compileAsync.call(self,{$ref:$schema},true):Promise.resolve()}function _compileAsync(schemaObj){try{return self._compile(schemaObj)}catch(e){if(e instanceof MissingRefError)return loadMissingSchema(e);throw e}function loadMissingSchema(e){var ref=e.missingSchema;if(added(ref))throw new Error("Schema "+ref+" is loaded but "+e.missingRef+" cannot be resolved");var schemaPromise=self._loadingSchemas[ref];if(!schemaPromise){schemaPromise=self._loadingSchemas[ref]=self._opts.loadSchema(ref);schemaPromise.then(removePromise,removePromise)}return schemaPromise.then(function(sch){if(!added(ref)){return loadMetaSchemaOf(sch).then(function(){if(!added(ref))self.addSchema(sch,ref,undefined,meta)})}}).then(function(){return _compileAsync(schemaObj)});function removePromise(){delete self._loadingSchemas[ref]}function added(ref){return self._refs[ref]||self._schemas[ref]}}}}},{"./error_classes":341}],341:[function(require,module,exports){"use strict";var resolve=require("./resolve");module.exports={Validation:errorSubclass(ValidationError),MissingRef:errorSubclass(MissingRefError)};function ValidationError(errors){this.message="validation failed";this.errors=errors;this.ajv=this.validation=true}MissingRefError.message=function(baseId,ref){return"can't resolve reference "+ref+" from id "+baseId};function MissingRefError(baseId,ref,message){this.message=message||MissingRefError.message(baseId,ref);this.missingRef=resolve.url(baseId,ref);this.missingSchema=resolve.normalizeId(resolve.fullPath(this.missingRef))}function errorSubclass(Subclass){Subclass.prototype=Object.create(Error.prototype);Subclass.prototype.constructor=Subclass;return Subclass}},{"./resolve":344}],342:[function(require,module,exports){"use strict";var util=require("./util");var DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;var DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31];var TIME=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;var HOSTNAME=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i;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;var URIREF=/^(?:[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;var URITEMPLATE=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#.\/;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i
34
+ ;var URL=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;var UUID=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;var JSON_POINTER=/^(?:\/(?:[^~\/]|~0|~1)*)*$/;var JSON_POINTER_URI_FRAGMENT=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;var RELATIVE_JSON_POINTER=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~\/]|~0|~1)*)*)$/;module.exports=formats;function formats(mode){mode=mode=="full"?"full":"fast";return util.copy(formats[mode])}formats.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":URITEMPLATE,url:URL,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,hostname:HOSTNAME,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,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,regex:regex,uuid:UUID,"json-pointer":JSON_POINTER,"json-pointer-uri-fragment":JSON_POINTER_URI_FRAGMENT,"relative-json-pointer":RELATIVE_JSON_POINTER};formats.full={date:date,time:time,"date-time":date_time,uri:uri,"uri-reference":URIREF,"uri-template":URITEMPLATE,url:URL,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,hostname:HOSTNAME,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,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,regex:regex,uuid:UUID,"json-pointer":JSON_POINTER,"json-pointer-uri-fragment":JSON_POINTER_URI_FRAGMENT,"relative-json-pointer":RELATIVE_JSON_POINTER};function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}function date(str){var matches=str.match(DATE);if(!matches)return false;var year=+matches[1];var month=+matches[2];var day=+matches[3];return month>=1&&month<=12&&day>=1&&day<=(month==2&&isLeapYear(year)?29:DAYS[month])}function time(str,full){var matches=str.match(TIME);if(!matches)return false;var hour=matches[1];var minute=matches[2];var second=matches[3];var timeZone=matches[5];return(hour<=23&&minute<=59&&second<=59||hour==23&&minute==59&&second==60)&&(!full||timeZone)}var DATE_TIME_SEPARATOR=/t|\s/i;function date_time(str){var dateTime=str.split(DATE_TIME_SEPARATOR);return dateTime.length==2&&date(dateTime[0])&&time(dateTime[1],true)}var NOT_URI_FRAGMENT=/\/|:/;function uri(str){return NOT_URI_FRAGMENT.test(str)&&URI.test(str)}var Z_ANCHOR=/[^\\]\\Z/;function regex(str){if(Z_ANCHOR.test(str))return false;try{new RegExp(str);return true}catch(e){return false}}},{"./util":348}],343:[function(require,module,exports){"use strict";var resolve=require("./resolve"),util=require("./util"),errorClasses=require("./error_classes"),stableStringify=require("fast-json-stable-stringify");var validateGenerator=require("../dotjs/validate");var ucs2length=util.ucs2length;var equal=require("fast-deep-equal");var ValidationError=errorClasses.Validation;module.exports=compile;function compile(schema,root,localRefs,baseId){var self=this,opts=this._opts,refVal=[undefined],refs={},patterns=[],patternsHash={},defaults=[],defaultsHash={},customRules=[];root=root||{schema:schema,refVal:refVal,refs:refs};var c=checkCompiling.call(this,schema,root,baseId);var compilation=this._compilations[c.index];if(c.compiling)return compilation.callValidate=callValidate;var formats=this._formats;var RULES=this.RULES;try{var v=localCompile(schema,root,localRefs,baseId);compilation.validate=v;var cv=compilation.callValidate;if(cv){cv.schema=v.schema;cv.errors=null;cv.refs=v.refs;cv.refVal=v.refVal;cv.root=v.root;cv.$async=v.$async;if(opts.sourceCode)cv.source=v.source}return v}finally{endCompiling.call(this,schema,root,baseId)}function callValidate(){var validate=compilation.validate;var result=validate.apply(this,arguments);callValidate.errors=validate.errors;return result}function localCompile(_schema,_root,localRefs,baseId){var isRoot=!_root||_root&&_root.schema==_schema;if(_root.schema!=root.schema)return compile.call(self,_schema,_root,localRefs,baseId);var $async=_schema.$async===true;var sourceCode=validateGenerator({isTop:true,schema:_schema,isRoot:isRoot,baseId:baseId,root:_root,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:errorClasses.MissingRef,RULES:RULES,validate:validateGenerator,util:util,resolve:resolve,resolveRef:resolveRef,usePattern:usePattern,useDefault:useDefault,useCustomRule:useCustomRule,opts:opts,formats:formats,logger:self.logger,self:self});sourceCode=vars(refVal,refValCode)+vars(patterns,patternCode)+vars(defaults,defaultCode)+vars(customRules,customRuleCode)+sourceCode;if(opts.processCode)sourceCode=opts.processCode(sourceCode,_schema);var validate;try{var makeValidate=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",sourceCode);validate=makeValidate(self,RULES,formats,root,refVal,defaults,customRules,equal,ucs2length,ValidationError);refVal[0]=validate}catch(e){self.logger.error("Error compiling schema, function code:",sourceCode);throw e}validate.schema=_schema;validate.errors=null;validate.refs=refs;validate.refVal=refVal;validate.root=isRoot?validate:_root;if($async)validate.$async=true;if(opts.sourceCode===true){validate.source={code:sourceCode,patterns:patterns,defaults:defaults}}return validate}function resolveRef(baseId,ref,isRoot){ref=resolve.url(baseId,ref);var refIndex=refs[ref];var _refVal,refCode;if(refIndex!==undefined){_refVal=refVal[refIndex];refCode="refVal["+refIndex+"]";return resolvedRef(_refVal,refCode)}if(!isRoot&&root.refs){var rootRefId=root.refs[ref];if(rootRefId!==undefined){_refVal=root.refVal[rootRefId];refCode=addLocalRef(ref,_refVal);return resolvedRef(_refVal,refCode)}}refCode=addLocalRef(ref);var v=resolve.call(self,localCompile,root,ref);if(v===undefined){var localSchema=localRefs&&localRefs[ref];if(localSchema){v=resolve.inlineRef(localSchema,opts.inlineRefs)?localSchema:compile.call(self,localSchema,root,localRefs,baseId)}}if(v===undefined){removeLocalRef(ref)}else{replaceLocalRef(ref,v);return resolvedRef(v,refCode)}}function addLocalRef(ref,v){var refId=refVal.length;refVal[refId]=v;refs[ref]=refId;return"refVal"+refId}function removeLocalRef(ref){delete refs[ref]}function replaceLocalRef(ref,v){var refId=refs[ref];refVal[refId]=v}function resolvedRef(refVal,code){return typeof refVal=="object"||typeof refVal=="boolean"?{code:code,schema:refVal,inline:true}:{code:code,$async:refVal&&!!refVal.$async}}function usePattern(regexStr){var index=patternsHash[regexStr];if(index===undefined){index=patternsHash[regexStr]=patterns.length;patterns[index]=regexStr}return"pattern"+index}function useDefault(value){switch(typeof value){case"boolean":case"number":return""+value;case"string":return util.toQuotedString(value);case"object":if(value===null)return"null";var valueStr=stableStringify(value);var index=defaultsHash[valueStr];if(index===undefined){index=defaultsHash[valueStr]=defaults.length;defaults[index]=value}return"default"+index}}function useCustomRule(rule,schema,parentSchema,it){if(self._opts.validateSchema!==false){var deps=rule.definition.dependencies;if(deps&&!deps.every(function(keyword){return Object.prototype.hasOwnProperty.call(parentSchema,keyword)}))throw new Error("parent schema must have all required keywords: "+deps.join(","));var validateSchema=rule.definition.validateSchema;if(validateSchema){var valid=validateSchema(schema);if(!valid){var message="keyword schema is invalid: "+self.errorsText(validateSchema.errors);if(self._opts.validateSchema=="log")self.logger.error(message);else throw new Error(message)}}}var compile=rule.definition.compile,inline=rule.definition.inline,macro=rule.definition.macro;var validate;if(compile){validate=compile.call(self,schema,parentSchema,it)}else if(macro){validate=macro.call(self,schema,parentSchema,it);if(opts.validateSchema!==false)self.validateSchema(validate,true)}else if(inline){validate=inline.call(self,it,rule.keyword,schema,parentSchema)}else{validate=rule.definition.validate;if(!validate)return}if(validate===undefined)throw new Error('custom keyword "'+rule.keyword+'"failed to compile');var index=customRules.length;customRules[index]=validate;return{code:"customRule"+index,validate:validate}}}function checkCompiling(schema,root,baseId){var index=compIndex.call(this,schema,root,baseId);if(index>=0)return{index:index,compiling:true};index=this._compilations.length;this._compilations[index]={schema:schema,root:root,baseId:baseId};return{index:index,compiling:false}}function endCompiling(schema,root,baseId){var i=compIndex.call(this,schema,root,baseId);if(i>=0)this._compilations.splice(i,1)}function compIndex(schema,root,baseId){for(var i=0;i<this._compilations.length;i++){var c=this._compilations[i];if(c.schema==schema&&c.root==root&&c.baseId==baseId)return i}return-1}function patternCode(i,patterns){return"var pattern"+i+" = new RegExp("+util.toQuotedString(patterns[i])+");"}function defaultCode(i){return"var default"+i+" = defaults["+i+"];"}function refValCode(i,refVal){return refVal[i]===undefined?"":"var refVal"+i+" = refVal["+i+"];"}function customRuleCode(i){return"var customRule"+i+" = customRules["+i+"];"}function vars(arr,statement){if(!arr.length)return"";var code="";for(var i=0;i<arr.length;i++)code+=statement(i,arr);return code}},{"../dotjs/validate":376,"./error_classes":341,"./resolve":344,"./util":348,"fast-deep-equal":401,"fast-json-stable-stringify":402}],344:[function(require,module,exports){"use strict";var URI=require("uri-js"),equal=require("fast-deep-equal"),util=require("./util"),SchemaObject=require("./schema_obj"),traverse=require("json-schema-traverse");module.exports=resolve;resolve.normalizeId=normalizeId;resolve.fullPath=getFullPath;resolve.url=resolveUrl;resolve.ids=resolveIds;resolve.inlineRef=inlineRef;resolve.schema=resolveSchema;function resolve(compile,root,ref){var refVal=this._refs[ref];if(typeof refVal=="string"){if(this._refs[refVal])refVal=this._refs[refVal];else return resolve.call(this,compile,root,refVal)}refVal=refVal||this._schemas[ref];if(refVal instanceof SchemaObject){return inlineRef(refVal.schema,this._opts.inlineRefs)?refVal.schema:refVal.validate||this._compile(refVal)}var res=resolveSchema.call(this,root,ref);var schema,v,baseId;if(res){schema=res.schema;root=res.root;baseId=res.baseId}if(schema instanceof SchemaObject){v=schema.validate||compile.call(this,schema.schema,root,undefined,baseId)}else if(schema!==undefined){v=inlineRef(schema,this._opts.inlineRefs)?schema:compile.call(this,schema,root,undefined,baseId)}return v}function resolveSchema(root,ref){var p=URI.parse(ref),refPath=_getFullPath(p),baseId=getFullPath(this._getId(root.schema));if(Object.keys(root.schema).length===0||refPath!==baseId){var id=normalizeId(refPath);var refVal=this._refs[id];if(typeof refVal=="string"){return resolveRecursive.call(this,root,refVal,p)}else if(refVal instanceof SchemaObject){if(!refVal.validate)this._compile(refVal);root=refVal}else{refVal=this._schemas[id];if(refVal instanceof SchemaObject){if(!refVal.validate)this._compile(refVal);if(id==normalizeId(ref))return{schema:refVal,root:root,baseId:baseId};root=refVal}else{return}}if(!root.schema)return;baseId=getFullPath(this._getId(root.schema))}return getJsonPointer.call(this,p,baseId,root.schema,root)}function resolveRecursive(root,ref,parsedRef){var res=resolveSchema.call(this,root,ref);if(res){var schema=res.schema;var baseId=res.baseId;root=res.root;var id=this._getId(schema);if(id)baseId=resolveUrl(baseId,id);return getJsonPointer.call(this,parsedRef,baseId,schema,root)}}var PREVENT_SCOPE_CHANGE=util.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function getJsonPointer(parsedRef,baseId,schema,root){parsedRef.fragment=parsedRef.fragment||"";if(parsedRef.fragment.slice(0,1)!="/")return;var parts=parsedRef.fragment.split("/");for(var i=1;i<parts.length;i++){var part=parts[i];if(part){part=util.unescapeFragment(part);schema=schema[part];if(schema===undefined)break;var id;if(!PREVENT_SCOPE_CHANGE[part]){id=this._getId(schema);if(id)baseId=resolveUrl(baseId,id);if(schema.$ref){var $ref=resolveUrl(baseId,schema.$ref);var res=resolveSchema.call(this,root,$ref);if(res){schema=res.schema;root=res.root;baseId=res.baseId}}}}}if(schema!==undefined&&schema!==root.schema)return{schema:schema,root:root,baseId:baseId}}var SIMPLE_INLINED=util.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function inlineRef(schema,limit){if(limit===false)return false;if(limit===undefined||limit===true)return checkNoRef(schema);else if(limit)return countKeys(schema)<=limit}function checkNoRef(schema){var item;if(Array.isArray(schema)){for(var i=0;i<schema.length;i++){item=schema[i];if(typeof item=="object"&&!checkNoRef(item))return false}}else{for(var key in schema){if(key=="$ref")return false;item=schema[key];if(typeof item=="object"&&!checkNoRef(item))return false}}return true}function countKeys(schema){var count=0,item;if(Array.isArray(schema)){for(var i=0;i<schema.length;i++){item=schema[i];if(typeof item=="object")count+=countKeys(item);if(count==Infinity)return Infinity}}else{for(var key in schema){if(key=="$ref")return Infinity;if(SIMPLE_INLINED[key]){count++}else{item=schema[key];if(typeof item=="object")count+=countKeys(item)+1;if(count==Infinity)return Infinity}}}return count}function getFullPath(id,normalize){if(normalize!==false)id=normalizeId(id);var p=URI.parse(id);return _getFullPath(p)}function _getFullPath(p){return URI.serialize(p).split("#")[0]+"#"}var TRAILING_SLASH_HASH=/#\/?$/;function normalizeId(id){return id?id.replace(TRAILING_SLASH_HASH,""):""}function resolveUrl(baseId,id){id=normalizeId(id);return URI.resolve(baseId,id)}function resolveIds(schema){var schemaId=normalizeId(this._getId(schema));var baseIds={"":schemaId};var fullPaths={"":getFullPath(schemaId,false)};var localRefs={};var self=this;traverse(schema,{allKeys:true},function(sch,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex){if(jsonPtr==="")return;var id=self._getId(sch);var baseId=baseIds[parentJsonPtr];var fullPath=fullPaths[parentJsonPtr]+"/"+parentKeyword;if(keyIndex!==undefined)fullPath+="/"+(typeof keyIndex=="number"?keyIndex:util.escapeFragment(keyIndex));if(typeof id=="string"){id=baseId=normalizeId(baseId?URI.resolve(baseId,id):id);var refVal=self._refs[id];if(typeof refVal=="string")refVal=self._refs[refVal];if(refVal&&refVal.schema){if(!equal(sch,refVal.schema))throw new Error('id "'+id+'" resolves to more than one schema')}else if(id!=normalizeId(fullPath)){if(id[0]=="#"){if(localRefs[id]&&!equal(sch,localRefs[id]))throw new Error('id "'+id+'" resolves to more than one schema');localRefs[id]=sch}else{self._refs[id]=fullPath}}}baseIds[jsonPtr]=baseId;fullPaths[jsonPtr]=fullPath});return localRefs}},{"./schema_obj":346,"./util":348,"fast-deep-equal":401,"json-schema-traverse":434,"uri-js":505}],345:[function(require,module,exports){"use strict";var ruleModules=require("../dotjs"),toHash=require("./util").toHash;module.exports=function rules(){var RULES=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}];var ALL=["type","$comment"];var KEYWORDS=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"];var TYPES=["number","integer","string","array","object","boolean","null"];RULES.all=toHash(ALL);RULES.types=toHash(TYPES);RULES.forEach(function(group){group.rules=group.rules.map(function(keyword){var implKeywords;if(typeof keyword=="object"){var key=Object.keys(keyword)[0];implKeywords=keyword[key];keyword=key;implKeywords.forEach(function(k){ALL.push(k);RULES.all[k]=true})}ALL.push(keyword);var rule=RULES.all[keyword]={keyword:keyword,code:ruleModules[keyword],implements:implKeywords};return rule});RULES.all.$comment={keyword:"$comment",code:ruleModules.$comment};if(group.type)RULES.types[group.type]=group});RULES.keywords=toHash(ALL.concat(KEYWORDS));RULES.custom={};return RULES}},{"../dotjs":365,"./util":348}],346:[function(require,module,exports){"use strict";var util=require("./util");module.exports=SchemaObject;function SchemaObject(obj){util.copy(obj,this)}},{"./util":348}],347:[function(require,module,exports){"use strict";module.exports=function ucs2length(str){var length=0,len=str.length,pos=0,value;while(pos<len){length++;value=str.charCodeAt(pos++);if(value>=55296&&value<=56319&&pos<len){value=str.charCodeAt(pos);if((value&64512)==56320)pos++}}return length}},{}],348:[function(require,module,exports){"use strict";module.exports={copy:copy,checkDataType:checkDataType,checkDataTypes:checkDataTypes,coerceToTypes:coerceToTypes,toHash:toHash,getProperty:getProperty,escapeQuotes:escapeQuotes,equal:require("fast-deep-equal"),ucs2length:require("./ucs2length"),varOccurences:varOccurences,varReplace:varReplace,schemaHasRules:schemaHasRules,schemaHasRulesExcept:schemaHasRulesExcept,schemaUnknownRules:schemaUnknownRules,toQuotedString:toQuotedString,getPathExpr:getPathExpr,getPath:getPath,getData:getData,unescapeFragment:unescapeFragment,unescapeJsonPointer:unescapeJsonPointer,escapeFragment:escapeFragment,escapeJsonPointer:escapeJsonPointer};function copy(o,to){to=to||{};for(var key in o)to[key]=o[key];return to}function checkDataType(dataType,data,strictNumbers,negate){var EQUAL=negate?" !== ":" === ",AND=negate?" || ":" && ",OK=negate?"!":"",NOT=negate?"":"!";switch(dataType){case"null":return data+EQUAL+"null";case"array":return OK+"Array.isArray("+data+")";case"object":return"("+OK+data+AND+"typeof "+data+EQUAL+'"object"'+AND+NOT+"Array.isArray("+data+"))";case"integer":return"(typeof "+data+EQUAL+'"number"'+AND+NOT+"("+data+" % 1)"+AND+data+EQUAL+data+(strictNumbers?AND+OK+"isFinite("+data+")":"")+")";case"number":return"(typeof "+data+EQUAL+'"'+dataType+'"'+(strictNumbers?AND+OK+"isFinite("+data+")":"")+")";default:return"typeof "+data+EQUAL+'"'+dataType+'"'}}function checkDataTypes(dataTypes,data,strictNumbers){switch(dataTypes.length){case 1:return checkDataType(dataTypes[0],data,strictNumbers,true);default:var code="";var types=toHash(dataTypes);if(types.array&&types.object){code=types.null?"(":"(!"+data+" || ";code+="typeof "+data+' !== "object")';delete types.null;delete types.array;delete types.object}if(types.number)delete types.integer;for(var t in types)code+=(code?" && ":"")+checkDataType(t,data,strictNumbers,true);return code}}var COERCE_TO_TYPES=toHash(["string","number","integer","boolean","null"]);function coerceToTypes(optionCoerceTypes,dataTypes){if(Array.isArray(dataTypes)){var types=[];for(var i=0;i<dataTypes.length;i++){var t=dataTypes[i];if(COERCE_TO_TYPES[t])types[types.length]=t;else if(optionCoerceTypes==="array"&&t==="array")types[types.length]=t}if(types.length)return types}else if(COERCE_TO_TYPES[dataTypes]){return[dataTypes]}else if(optionCoerceTypes==="array"&&dataTypes==="array"){return["array"]}}function toHash(arr){var hash={};for(var i=0;i<arr.length;i++)hash[arr[i]]=true;return hash}var IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var SINGLE_QUOTE=/'|\\/g;function getProperty(key){return typeof key=="number"?"["+key+"]":IDENTIFIER.test(key)?"."+key:"['"+escapeQuotes(key)+"']"}function escapeQuotes(str){return str.replace(SINGLE_QUOTE,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function varOccurences(str,dataVar){dataVar+="[^0-9]";var matches=str.match(new RegExp(dataVar,"g"));return matches?matches.length:0}function varReplace(str,dataVar,expr){dataVar+="([^0-9])";expr=expr.replace(/\$/g,"$$$$");return str.replace(new RegExp(dataVar,"g"),expr+"$1")}function schemaHasRules(schema,rules){if(typeof schema=="boolean")return!schema;for(var key in schema)if(rules[key])return true}function schemaHasRulesExcept(schema,rules,exceptKeyword){if(typeof schema=="boolean")return!schema&&exceptKeyword!="not";for(var key in schema)if(key!=exceptKeyword&&rules[key])return true}function schemaUnknownRules(schema,rules){if(typeof schema=="boolean")return;for(var key in schema)if(!rules[key])return key}function toQuotedString(str){return"'"+escapeQuotes(str)+"'"}function getPathExpr(currentPath,expr,jsonPointers,isNumber){var path=jsonPointers?"'/' + "+expr+(isNumber?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):isNumber?"'[' + "+expr+" + ']'":"'[\\'' + "+expr+" + '\\']'";return joinPaths(currentPath,path)}function getPath(currentPath,prop,jsonPointers){var path=jsonPointers?toQuotedString("/"+escapeJsonPointer(prop)):toQuotedString(getProperty(prop));return joinPaths(currentPath,path)}var JSON_POINTER=/^\/(?:[^~]|~0|~1)*$/;var RELATIVE_JSON_POINTER=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function getData($data,lvl,paths){var up,jsonPointer,data,matches;if($data==="")return"rootData";if($data[0]=="/"){if(!JSON_POINTER.test($data))throw new Error("Invalid JSON-pointer: "+$data);jsonPointer=$data;data="rootData"}else{matches=$data.match(RELATIVE_JSON_POINTER);if(!matches)throw new Error("Invalid JSON-pointer: "+$data);up=+matches[1];jsonPointer=matches[2];if(jsonPointer=="#"){if(up>=lvl)throw new Error("Cannot access property/index "+up+" levels up, current level is "+lvl);return paths[lvl-up]}if(up>lvl)throw new Error("Cannot access data "+up+" levels up, current level is "+lvl);data="data"+(lvl-up||"");if(!jsonPointer)return data}var expr=data;var segments=jsonPointer.split("/");for(var i=0;i<segments.length;i++){var segment=segments[i];if(segment){data+=getProperty(unescapeJsonPointer(segment));expr+=" && "+data}}return expr}function joinPaths(a,b){if(a=='""')return b;return(a+" + "+b).replace(/([^\\])' \+ '/g,"$1")}function unescapeFragment(str){return unescapeJsonPointer(decodeURIComponent(str))}function escapeFragment(str){return encodeURIComponent(escapeJsonPointer(str))}function escapeJsonPointer(str){return str.replace(/~/g,"~0").replace(/\//g,"~1")}function unescapeJsonPointer(str){return str.replace(/~1/g,"/").replace(/~0/g,"~")}},{"./ucs2length":347,"fast-deep-equal":401}],349:[function(require,module,exports){"use strict";var KEYWORDS=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];module.exports=function(metaSchema,keywordsJsonPointers){for(var i=0;i<keywordsJsonPointers.length;i++){metaSchema=JSON.parse(JSON.stringify(metaSchema));var segments=keywordsJsonPointers[i].split("/");var keywords=metaSchema;var j;for(j=1;j<segments.length;j++)keywords=keywords[segments[j]];for(j=0;j<KEYWORDS.length;j++){var key=KEYWORDS[j];var schema=keywords[key];if(schema){keywords[key]={anyOf:[schema,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}}}}return metaSchema}},{}],350:[function(require,module,exports){"use strict";var metaSchema=require("./refs/json-schema-draft-07.json");module.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:metaSchema.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:metaSchema.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}}},{"./refs/json-schema-draft-07.json":380}],351:[function(require,module,exports){"use strict";module.exports=function generate__limit(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $isMax=$keyword=="maximum",$exclusiveKeyword=$isMax?"exclusiveMaximum":"exclusiveMinimum",$schemaExcl=it.schema[$exclusiveKeyword],$isDataExcl=it.opts.$data&&$schemaExcl&&$schemaExcl.$data,$op=$isMax?"<":">",$notOp=$isMax?">":"<",$errorKeyword=undefined;if(!($isData||typeof $schema=="number"||$schema===undefined)){throw new Error($keyword+" must be number")}if(!($isDataExcl||$schemaExcl===undefined||typeof $schemaExcl=="number"||typeof $schemaExcl=="boolean")){throw new Error($exclusiveKeyword+" must be number or boolean")}if($isDataExcl){var $schemaValueExcl=it.util.getData($schemaExcl.$data,$dataLvl,it.dataPathArr),$exclusive="exclusive"+$lvl,$exclType="exclType"+$lvl,$exclIsNumber="exclIsNumber"+$lvl,$opExpr="op"+$lvl,$opStr="' + "+$opExpr+" + '";out+=" var schemaExcl"+$lvl+" = "+$schemaValueExcl+"; ";$schemaValueExcl="schemaExcl"+$lvl;out+=" var "+$exclusive+"; var "+$exclType+" = typeof "+$schemaValueExcl+"; if ("+$exclType+" != 'boolean' && "+$exclType+" != 'undefined' && "+$exclType+" != 'number') { ";var $errorKeyword=$exclusiveKeyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: '"+$exclusiveKeyword+" should be boolean' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } else if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}out+=" "+$exclType+" == 'number' ? ( ("+$exclusive+" = "+$schemaValue+" === undefined || "+$schemaValueExcl+" "+$op+"= "+$schemaValue+") ? "+$data+" "+$notOp+"= "+$schemaValueExcl+" : "+$data+" "+$notOp+" "+$schemaValue+" ) : ( ("+$exclusive+" = "+$schemaValueExcl+" === true) ? "+$data+" "+$notOp+"= "+$schemaValue+" : "+$data+" "+$notOp+" "+$schemaValue+" ) || "+$data+" !== "+$data+") { var op"+$lvl+" = "+$exclusive+" ? '"+$op+"' : '"+$op+"='; ";if($schema===undefined){$errorKeyword=$exclusiveKeyword;$errSchemaPath=it.errSchemaPath+"/"+$exclusiveKeyword;$schemaValue=$schemaValueExcl;$isData=$isDataExcl}}else{var $exclIsNumber=typeof $schemaExcl=="number",$opStr=$op;if($exclIsNumber&&$isData){var $opExpr="'"+$opStr+"'";out+=" if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}
35
+ out+=" ( "+$schemaValue+" === undefined || "+$schemaExcl+" "+$op+"= "+$schemaValue+" ? "+$data+" "+$notOp+"= "+$schemaExcl+" : "+$data+" "+$notOp+" "+$schemaValue+" ) || "+$data+" !== "+$data+") { "}else{if($exclIsNumber&&$schema===undefined){$exclusive=true;$errorKeyword=$exclusiveKeyword;$errSchemaPath=it.errSchemaPath+"/"+$exclusiveKeyword;$schemaValue=$schemaExcl;$notOp+="="}else{if($exclIsNumber)$schemaValue=Math[$isMax?"min":"max"]($schemaExcl,$schema);if($schemaExcl===($exclIsNumber?$schemaValue:true)){$exclusive=true;$errorKeyword=$exclusiveKeyword;$errSchemaPath=it.errSchemaPath+"/"+$exclusiveKeyword;$notOp+="="}else{$exclusive=false;$opStr+="="}}var $opExpr="'"+$opStr+"'";out+=" if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}out+=" "+$data+" "+$notOp+" "+$schemaValue+" || "+$data+" !== "+$data+") { "}}$errorKeyword=$errorKeyword||$keyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"_limit")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { comparison: "+$opExpr+", limit: "+$schemaValue+", exclusive: "+$exclusive+" } ";if(it.opts.messages!==false){out+=" , message: 'should be "+$opStr+" ";if($isData){out+="' + "+$schemaValue}else{out+=""+$schemaValue+"'"}}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } ";if($breakOnError){out+=" else { "}return out}},{}],352:[function(require,module,exports){"use strict";module.exports=function generate__limitItems(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(!($isData||typeof $schema=="number")){throw new Error($keyword+" must be number")}var $op=$keyword=="maxItems"?">":"<";out+="if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}out+=" "+$data+".length "+$op+" "+$schemaValue+") { ";var $errorKeyword=$keyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"_limitItems")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { limit: "+$schemaValue+" } ";if(it.opts.messages!==false){out+=" , message: 'should NOT have ";if($keyword=="maxItems"){out+="more"}else{out+="fewer"}out+=" than ";if($isData){out+="' + "+$schemaValue+" + '"}else{out+=""+$schema}out+=" items' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+="} ";if($breakOnError){out+=" else { "}return out}},{}],353:[function(require,module,exports){"use strict";module.exports=function generate__limitLength(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(!($isData||typeof $schema=="number")){throw new Error($keyword+" must be number")}var $op=$keyword=="maxLength"?">":"<";out+="if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}if(it.opts.unicode===false){out+=" "+$data+".length "}else{out+=" ucs2length("+$data+") "}out+=" "+$op+" "+$schemaValue+") { ";var $errorKeyword=$keyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"_limitLength")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { limit: "+$schemaValue+" } ";if(it.opts.messages!==false){out+=" , message: 'should NOT be ";if($keyword=="maxLength"){out+="longer"}else{out+="shorter"}out+=" than ";if($isData){out+="' + "+$schemaValue+" + '"}else{out+=""+$schema}out+=" characters' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+="} ";if($breakOnError){out+=" else { "}return out}},{}],354:[function(require,module,exports){"use strict";module.exports=function generate__limitProperties(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(!($isData||typeof $schema=="number")){throw new Error($keyword+" must be number")}var $op=$keyword=="maxProperties"?">":"<";out+="if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}out+=" Object.keys("+$data+").length "+$op+" "+$schemaValue+") { ";var $errorKeyword=$keyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"_limitProperties")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { limit: "+$schemaValue+" } ";if(it.opts.messages!==false){out+=" , message: 'should NOT have ";if($keyword=="maxProperties"){out+="more"}else{out+="fewer"}out+=" than ";if($isData){out+="' + "+$schemaValue+" + '"}else{out+=""+$schema}out+=" properties' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+="} ";if($breakOnError){out+=" else { "}return out}},{}],355:[function(require,module,exports){"use strict";module.exports=function generate_allOf(it,$keyword,$ruleType){var out=" ";var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $currentBaseId=$it.baseId,$allSchemasEmpty=true;var arr1=$schema;if(arr1){var $sch,$i=-1,l1=arr1.length-1;while($i<l1){$sch=arr1[$i+=1];if(it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)){$allSchemasEmpty=false;$it.schema=$sch;$it.schemaPath=$schemaPath+"["+$i+"]";$it.errSchemaPath=$errSchemaPath+"/"+$i;out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}}}if($breakOnError){if($allSchemasEmpty){out+=" if (true) { "}else{out+=" "+$closingBraces.slice(0,-1)+" "}}return out}},{}],356:[function(require,module,exports){"use strict";module.exports=function generate_anyOf(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $noEmptySchema=$schema.every(function($sch){return it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)});if($noEmptySchema){var $currentBaseId=$it.baseId;out+=" var "+$errs+" = errors; var "+$valid+" = false; ";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;var arr1=$schema;if(arr1){var $sch,$i=-1,l1=arr1.length-1;while($i<l1){$sch=arr1[$i+=1];$it.schema=$sch;$it.schemaPath=$schemaPath+"["+$i+"]";$it.errSchemaPath=$errSchemaPath+"/"+$i;out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;out+=" "+$valid+" = "+$valid+" || "+$nextValid+"; if (!"+$valid+") { ";$closingBraces+="}"}}it.compositeRule=$it.compositeRule=$wasComposite;out+=" "+$closingBraces+" if (!"+$valid+") { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"anyOf"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: 'should match some schema in anyOf' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(vErrors); "}else{out+=" validate.errors = vErrors; return false; "}}out+=" } else { errors = "+$errs+"; if (vErrors !== null) { if ("+$errs+") vErrors.length = "+$errs+"; else vErrors = null; } ";if(it.opts.allErrors){out+=" } "}}else{if($breakOnError){out+=" if (true) { "}}return out}},{}],357:[function(require,module,exports){"use strict";module.exports=function generate_comment(it,$keyword,$ruleType){var out=" ";var $schema=it.schema[$keyword];var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $comment=it.util.toQuotedString($schema);if(it.opts.$comment===true){out+=" console.log("+$comment+");"}else if(typeof it.opts.$comment=="function"){out+=" self._opts.$comment("+$comment+", "+it.util.toQuotedString($errSchemaPath)+", validate.root.schema);"}return out}},{}],358:[function(require,module,exports){"use strict";module.exports=function generate_const(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(!$isData){out+=" var schema"+$lvl+" = validate.schema"+$schemaPath+";"}out+="var "+$valid+" = equal("+$data+", schema"+$lvl+"); if (!"+$valid+") { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"const"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { allowedValue: schema"+$lvl+" } ";if(it.opts.messages!==false){out+=" , message: 'should be equal to constant' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" }";if($breakOnError){out+=" else { "}return out}},{}],359:[function(require,module,exports){"use strict";module.exports=function generate_contains(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $idx="i"+$lvl,$dataNxt=$it.dataLevel=it.dataLevel+1,$nextData="data"+$dataNxt,$currentBaseId=it.baseId,$nonEmptySchema=it.opts.strictKeywords?typeof $schema=="object"&&Object.keys($schema).length>0||$schema===false:it.util.schemaHasRules($schema,it.RULES.all);out+="var "+$errs+" = errors;var "+$valid+";";if($nonEmptySchema){var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;$it.schema=$schema;$it.schemaPath=$schemaPath;$it.errSchemaPath=$errSchemaPath;out+=" var "+$nextValid+" = false; for (var "+$idx+" = 0; "+$idx+" < "+$data+".length; "+$idx+"++) { ";$it.errorPath=it.util.getPathExpr(it.errorPath,$idx,it.opts.jsonPointers,true);var $passData=$data+"["+$idx+"]";$it.dataPathArr[$dataNxt]=$idx;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}out+=" if ("+$nextValid+") break; } ";it.compositeRule=$it.compositeRule=$wasComposite;out+=" "+$closingBraces+" if (!"+$nextValid+") {"}else{out+=" if ("+$data+".length == 0) {"}var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"contains"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: 'should contain a valid item' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } else { ";if($nonEmptySchema){out+=" errors = "+$errs+"; if (vErrors !== null) { if ("+$errs+") vErrors.length = "+$errs+"; else vErrors = null; } "}if(it.opts.allErrors){out+=" } "}return out}},{}],360:[function(require,module,exports){"use strict";module.exports=function generate_custom(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $rule=this,$definition="definition"+$lvl,$rDef=$rule.definition,$closingBraces="";var $compile,$inline,$macro,$ruleValidate,$validateCode;if($isData&&$rDef.$data){$validateCode="keywordValidate"+$lvl;var $validateSchema=$rDef.validateSchema;out+=" var "+$definition+" = RULES.custom['"+$keyword+"'].definition; var "+$validateCode+" = "+$definition+".validate;"}else{$ruleValidate=it.useCustomRule($rule,$schema,it.schema,it);if(!$ruleValidate)return;$schemaValue="validate.schema"+$schemaPath;$validateCode=$ruleValidate.code;$compile=$rDef.compile;$inline=$rDef.inline;$macro=$rDef.macro}var $ruleErrs=$validateCode+".errors",$i="i"+$lvl,$ruleErr="ruleErr"+$lvl,$asyncKeyword=$rDef.async;if($asyncKeyword&&!it.async)throw new Error("async keyword in sync schema");if(!($inline||$macro)){out+=""+$ruleErrs+" = null;"}out+="var "+$errs+" = errors;var "+$valid+";";if($isData&&$rDef.$data){$closingBraces+="}";out+=" if ("+$schemaValue+" === undefined) { "+$valid+" = true; } else { ";if($validateSchema){$closingBraces+="}";out+=" "+$valid+" = "+$definition+".validateSchema("+$schemaValue+"); if ("+$valid+") { "}}if($inline){if($rDef.statements){out+=" "+$ruleValidate.validate+" "}else{out+=" "+$valid+" = "+$ruleValidate.validate+"; "}}else if($macro){var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;$it.schema=$ruleValidate.validate;$it.schemaPath="";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;var $code=it.validate($it).replace(/validate\.schema/g,$validateCode);it.compositeRule=$it.compositeRule=$wasComposite;out+=" "+$code}else{var $$outStack=$$outStack||[];$$outStack.push(out);out="";out+=" "+$validateCode+".call( ";if(it.opts.passContext){out+="this"}else{out+="self"}if($compile||$rDef.schema===false){out+=" , "+$data+" "}else{out+=" , "+$schemaValue+" , "+$data+" , validate.schema"+it.schemaPath+" "}out+=" , (dataPath || '')";if(it.errorPath!='""'){out+=" + "+it.errorPath}var $parentData=$dataLvl?"data"+($dataLvl-1||""):"parentData",$parentDataProperty=$dataLvl?it.dataPathArr[$dataLvl]:"parentDataProperty";out+=" , "+$parentData+" , "+$parentDataProperty+" , rootData ) ";var def_callRuleValidate=out;out=$$outStack.pop();if($rDef.errors===false){out+=" "+$valid+" = ";if($asyncKeyword){out+="await "}out+=""+def_callRuleValidate+"; "}else{if($asyncKeyword){$ruleErrs="customErrors"+$lvl;out+=" var "+$ruleErrs+" = null; try { "+$valid+" = await "+def_callRuleValidate+"; } catch (e) { "+$valid+" = false; if (e instanceof ValidationError) "+$ruleErrs+" = e.errors; else throw e; } "}else{out+=" "+$ruleErrs+" = null; "+$valid+" = "+def_callRuleValidate+"; "}}}if($rDef.modifying){out+=" if ("+$parentData+") "+$data+" = "+$parentData+"["+$parentDataProperty+"];"}out+=""+$closingBraces;if($rDef.valid){if($breakOnError){out+=" if (true) { "}}else{out+=" if ( ";if($rDef.valid===undefined){out+=" !";if($macro){out+=""+$nextValid}else{out+=""+$valid}}else{out+=" "+!$rDef.valid+" "}out+=") { ";$errorKeyword=$rule.keyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"custom")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { keyword: '"+$rule.keyword+"' } ";if(it.opts.messages!==false){out+=" , message: 'should pass \""+$rule.keyword+"\" keyword validation' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}var def_customError=out;out=$$outStack.pop();if($inline){if($rDef.errors){if($rDef.errors!="full"){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+'"; } ';if(it.opts.verbose){out+=" "+$ruleErr+".schema = "+$schemaValue+"; "+$ruleErr+".data = "+$data+"; "}out+=" } "}}else{if($rDef.errors===false){out+=" "+def_customError+" "}else{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+'"; } ';if(it.opts.verbose){out+=" "+$ruleErr+".schema = "+$schemaValue+"; "+$ruleErr+".data = "+$data+"; "}out+=" } } "}}}else if($macro){out+=" var err = ";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"custom")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { keyword: '"+$rule.keyword+"' } ";if(it.opts.messages!==false){out+=" , message: 'should pass \""+$rule.keyword+"\" keyword validation' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(vErrors); "}else{out+=" validate.errors = vErrors; return false; "}}}else{if($rDef.errors===false){out+=" "+def_customError+" "}else{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+'"; ';if(it.opts.verbose){out+=" "+$ruleErr+".schema = "+$schemaValue+"; "+$ruleErr+".data = "+$data+"; "}out+=" } } else { "+def_customError+" } "}}out+=" } ";if($breakOnError){out+=" else { "}}return out}},{}],361:[function(require,module,exports){"use strict";module.exports=function generate_dependencies(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $schemaDeps={},$propertyDeps={},$ownProperties=it.opts.ownProperties;for($property in $schema){if($property=="__proto__")continue;var $sch=$schema[$property];var $deps=Array.isArray($sch)?$propertyDeps:$schemaDeps;$deps[$property]=$sch}out+="var "+$errs+" = errors;";var $currentErrorPath=it.errorPath;out+="var missing"+$lvl+";";for(var $property in $propertyDeps){$deps=$propertyDeps[$property];if($deps.length){out+=" if ( "+$data+it.util.getProperty($property)+" !== undefined ";if($ownProperties){out+=" && Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($property)+"') "}if($breakOnError){out+=" && ( ";var arr1=$deps;if(arr1){var $propertyKey,$i=-1,l1=arr1.length-1;while($i<l1){$propertyKey=arr1[$i+=1];if($i){out+=" || "}var $prop=it.util.getProperty($propertyKey),$useData=$data+$prop;out+=" ( ( "+$useData+" === undefined ";if($ownProperties){out+=" || ! Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($propertyKey)+"') "}out+=") && (missing"+$lvl+" = "+it.util.toQuotedString(it.opts.jsonPointers?$propertyKey:$prop)+") ) "}}out+=")) { ";var $propertyPath="missing"+$lvl,$missingProperty="' + "+$propertyPath+" + '";if(it.opts._errorDataPathProperty){it.errorPath=it.opts.jsonPointers?it.util.getPathExpr($currentErrorPath,$propertyPath,true):$currentErrorPath+" + "+$propertyPath}var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"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(", "))+"' } ";if(it.opts.messages!==false){out+=" , message: 'should have ";if($deps.length==1){out+="property "+it.util.escapeQuotes($deps[0])}else{out+="properties "+it.util.escapeQuotes($deps.join(", "))}out+=" when property "+it.util.escapeQuotes($property)+" is present' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}}else{out+=" ) { ";var arr2=$deps;if(arr2){var $propertyKey,i2=-1,l2=arr2.length-1;while(i2<l2){$propertyKey=arr2[i2+=1];var $prop=it.util.getProperty($propertyKey),$missingProperty=it.util.escapeQuotes($propertyKey),$useData=$data+$prop;if(it.opts._errorDataPathProperty){it.errorPath=it.util.getPath($currentErrorPath,$propertyKey,it.opts.jsonPointers)}out+=" if ( "+$useData+" === undefined ";if($ownProperties){out+=" || ! Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($propertyKey)+"') "}out+=") { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"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(", "))+"' } ";if(it.opts.messages!==false){out+=" , message: 'should have ";if($deps.length==1){out+="property "+it.util.escapeQuotes($deps[0])}else{out+="properties "+it.util.escapeQuotes($deps.join(", "))}out+=" when property "+it.util.escapeQuotes($property)+" is present' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}}out+=" } ";if($breakOnError){$closingBraces+="}";out+=" else { "}}}it.errorPath=$currentErrorPath;var $currentBaseId=$it.baseId;for(var $property in $schemaDeps){var $sch=$schemaDeps[$property];if(it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)){out+=" "+$nextValid+" = true; if ( "+$data+it.util.getProperty($property)+" !== undefined ";if($ownProperties){out+=" && Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($property)+"') "}out+=") { ";$it.schema=$sch;$it.schemaPath=$schemaPath+it.util.getProperty($property);$it.errSchemaPath=$errSchemaPath+"/"+it.util.escapeFragment($property);out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;out+=" } ";if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}}if($breakOnError){out+=" "+$closingBraces+" if ("+$errs+" == errors) {"}return out}},{}],362:[function(require,module,exports){"use strict";module.exports=function generate_enum(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $i="i"+$lvl,$vSchema="schema"+$lvl;if(!$isData){out+=" var "+$vSchema+" = validate.schema"+$schemaPath+";"}out+="var "+$valid+";";if($isData){out+=" if (schema"+$lvl+" === undefined) "+$valid+" = true; else if (!Array.isArray(schema"+$lvl+")) "+$valid+" = false; else {"}out+=""+$valid+" = false;for (var "+$i+"=0; "+$i+"<"+$vSchema+".length; "+$i+"++) if (equal("+$data+", "+$vSchema+"["+$i+"])) { "+$valid+" = true; break; }";if($isData){out+=" } "}out+=" if (!"+$valid+") { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"enum"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { allowedValues: schema"+$lvl+" } ";if(it.opts.messages!==false){out+=" , message: 'should be equal to one of the allowed values' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" }";if($breakOnError){out+=" else { "}return out}},{}],363:[function(require,module,exports){"use strict";module.exports=function generate_format(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");if(it.opts.format===false){if($breakOnError){out+=" if (true) { "}return out}var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $unknownFormats=it.opts.unknownFormats,$allowUnknown=Array.isArray($unknownFormats);if($isData){var $format="format"+$lvl,$isObject="isObject"+$lvl,$formatType="formatType"+$lvl;out+=" var "+$format+" = formats["+$schemaValue+"]; var "+$isObject+" = typeof "+$format+" == 'object' && !("+$format+" instanceof RegExp) && "+$format+".validate; var "+$formatType+" = "+$isObject+" && "+$format+".type || 'string'; if ("+$isObject+") { ";if(it.async){out+=" var async"+$lvl+" = "+$format+".async; "}out+=" "+$format+" = "+$format+".validate; } if ( ";if($isData){
36
+ out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'string') || "}out+=" (";if($unknownFormats!="ignore"){out+=" ("+$schemaValue+" && !"+$format+" ";if($allowUnknown){out+=" && self._opts.unknownFormats.indexOf("+$schemaValue+") == -1 "}out+=") || "}out+=" ("+$format+" && "+$formatType+" == '"+$ruleType+"' && !(typeof "+$format+" == 'function' ? ";if(it.async){out+=" (async"+$lvl+" ? await "+$format+"("+$data+") : "+$format+"("+$data+")) "}else{out+=" "+$format+"("+$data+") "}out+=" : "+$format+".test("+$data+"))))) {"}else{var $format=it.formats[$schema];if(!$format){if($unknownFormats=="ignore"){it.logger.warn('unknown format "'+$schema+'" ignored in schema at path "'+it.errSchemaPath+'"');if($breakOnError){out+=" if (true) { "}return out}else if($allowUnknown&&$unknownFormats.indexOf($schema)>=0){if($breakOnError){out+=" if (true) { "}return out}else{throw new Error('unknown format "'+$schema+'" is used in schema at path "'+it.errSchemaPath+'"')}}var $isObject=typeof $format=="object"&&!($format instanceof RegExp)&&$format.validate;var $formatType=$isObject&&$format.type||"string";if($isObject){var $async=$format.async===true;$format=$format.validate}if($formatType!=$ruleType){if($breakOnError){out+=" if (true) { "}return out}if($async){if(!it.async)throw new Error("async format in sync schema");var $formatRef="formats"+it.util.getProperty($schema)+".validate";out+=" if (!(await "+$formatRef+"("+$data+"))) { "}else{out+=" if (! ";var $formatRef="formats"+it.util.getProperty($schema);if($isObject)$formatRef+=".validate";if(typeof $format=="function"){out+=" "+$formatRef+"("+$data+") "}else{out+=" "+$formatRef+".test("+$data+") "}out+=") { "}}var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"format"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { format: ";if($isData){out+=""+$schemaValue}else{out+=""+it.util.toQuotedString($schema)}out+=" } ";if(it.opts.messages!==false){out+=" , message: 'should match format \"";if($isData){out+="' + "+$schemaValue+" + '"}else{out+=""+it.util.escapeQuotes($schema)}out+="\"' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+it.util.toQuotedString($schema)}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } ";if($breakOnError){out+=" else { "}return out}},{}],364:[function(require,module,exports){"use strict";module.exports=function generate_if(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $it=it.util.copy(it);$it.level++;var $nextValid="valid"+$it.level;var $thenSch=it.schema["then"],$elseSch=it.schema["else"],$thenPresent=$thenSch!==undefined&&(it.opts.strictKeywords?typeof $thenSch=="object"&&Object.keys($thenSch).length>0||$thenSch===false:it.util.schemaHasRules($thenSch,it.RULES.all)),$elsePresent=$elseSch!==undefined&&(it.opts.strictKeywords?typeof $elseSch=="object"&&Object.keys($elseSch).length>0||$elseSch===false:it.util.schemaHasRules($elseSch,it.RULES.all)),$currentBaseId=$it.baseId;if($thenPresent||$elsePresent){var $ifClause;$it.createErrors=false;$it.schema=$schema;$it.schemaPath=$schemaPath;$it.errSchemaPath=$errSchemaPath;out+=" var "+$errs+" = errors; var "+$valid+" = true; ";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;$it.createErrors=true;out+=" errors = "+$errs+"; if (vErrors !== null) { if ("+$errs+") vErrors.length = "+$errs+"; else vErrors = null; } ";it.compositeRule=$it.compositeRule=$wasComposite;if($thenPresent){out+=" if ("+$nextValid+") { ";$it.schema=it.schema["then"];$it.schemaPath=it.schemaPath+".then";$it.errSchemaPath=it.errSchemaPath+"/then";out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;out+=" "+$valid+" = "+$nextValid+"; ";if($thenPresent&&$elsePresent){$ifClause="ifClause"+$lvl;out+=" var "+$ifClause+" = 'then'; "}else{$ifClause="'then'"}out+=" } ";if($elsePresent){out+=" else { "}}else{out+=" if (!"+$nextValid+") { "}if($elsePresent){$it.schema=it.schema["else"];$it.schemaPath=it.schemaPath+".else";$it.errSchemaPath=it.errSchemaPath+"/else";out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;out+=" "+$valid+" = "+$nextValid+"; ";if($thenPresent&&$elsePresent){$ifClause="ifClause"+$lvl;out+=" var "+$ifClause+" = 'else'; "}else{$ifClause="'else'"}out+=" } "}out+=" if (!"+$valid+") { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"if"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { failingKeyword: "+$ifClause+" } ";if(it.opts.messages!==false){out+=" , message: 'should match \"' + "+$ifClause+" + '\" schema' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(vErrors); "}else{out+=" validate.errors = vErrors; return false; "}}out+=" } ";if($breakOnError){out+=" else { "}}else{if($breakOnError){out+=" if (true) { "}}return out}},{}],365:[function(require,module,exports){"use strict";module.exports={$ref:require("./ref"),allOf:require("./allOf"),anyOf:require("./anyOf"),$comment:require("./comment"),const:require("./const"),contains:require("./contains"),dependencies:require("./dependencies"),enum:require("./enum"),format:require("./format"),if:require("./if"),items:require("./items"),maximum:require("./_limit"),minimum:require("./_limit"),maxItems:require("./_limitItems"),minItems:require("./_limitItems"),maxLength:require("./_limitLength"),minLength:require("./_limitLength"),maxProperties:require("./_limitProperties"),minProperties:require("./_limitProperties"),multipleOf:require("./multipleOf"),not:require("./not"),oneOf:require("./oneOf"),pattern:require("./pattern"),properties:require("./properties"),propertyNames:require("./propertyNames"),required:require("./required"),uniqueItems:require("./uniqueItems"),validate:require("./validate")}},{"./_limit":351,"./_limitItems":352,"./_limitLength":353,"./_limitProperties":354,"./allOf":355,"./anyOf":356,"./comment":357,"./const":358,"./contains":359,"./dependencies":361,"./enum":362,"./format":363,"./if":364,"./items":366,"./multipleOf":367,"./not":368,"./oneOf":369,"./pattern":370,"./properties":371,"./propertyNames":372,"./ref":373,"./required":374,"./uniqueItems":375,"./validate":376}],366:[function(require,module,exports){"use strict";module.exports=function generate_items(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $idx="i"+$lvl,$dataNxt=$it.dataLevel=it.dataLevel+1,$nextData="data"+$dataNxt,$currentBaseId=it.baseId;out+="var "+$errs+" = errors;var "+$valid+";";if(Array.isArray($schema)){var $additionalItems=it.schema.additionalItems;if($additionalItems===false){out+=" "+$valid+" = "+$data+".length <= "+$schema.length+"; ";var $currErrSchemaPath=$errSchemaPath;$errSchemaPath=it.errSchemaPath+"/additionalItems";out+=" if (!"+$valid+") { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"additionalItems"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { limit: "+$schema.length+" } ";if(it.opts.messages!==false){out+=" , message: 'should NOT have more than "+$schema.length+" items' "}if(it.opts.verbose){out+=" , schema: false , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } ";$errSchemaPath=$currErrSchemaPath;if($breakOnError){$closingBraces+="}";out+=" else { "}}var arr1=$schema;if(arr1){var $sch,$i=-1,l1=arr1.length-1;while($i<l1){$sch=arr1[$i+=1];if(it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)){out+=" "+$nextValid+" = true; if ("+$data+".length > "+$i+") { ";var $passData=$data+"["+$i+"]";$it.schema=$sch;$it.schemaPath=$schemaPath+"["+$i+"]";$it.errSchemaPath=$errSchemaPath+"/"+$i;$it.errorPath=it.util.getPathExpr(it.errorPath,$i,it.opts.jsonPointers,true);$it.dataPathArr[$dataNxt]=$i;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}out+=" } ";if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}}}if(typeof $additionalItems=="object"&&(it.opts.strictKeywords?typeof $additionalItems=="object"&&Object.keys($additionalItems).length>0||$additionalItems===false:it.util.schemaHasRules($additionalItems,it.RULES.all))){$it.schema=$additionalItems;$it.schemaPath=it.schemaPath+".additionalItems";$it.errSchemaPath=it.errSchemaPath+"/additionalItems";out+=" "+$nextValid+" = true; if ("+$data+".length > "+$schema.length+") { for (var "+$idx+" = "+$schema.length+"; "+$idx+" < "+$data+".length; "+$idx+"++) { ";$it.errorPath=it.util.getPathExpr(it.errorPath,$idx,it.opts.jsonPointers,true);var $passData=$data+"["+$idx+"]";$it.dataPathArr[$dataNxt]=$idx;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}if($breakOnError){out+=" if (!"+$nextValid+") break; "}out+=" } } ";if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}}else if(it.opts.strictKeywords?typeof $schema=="object"&&Object.keys($schema).length>0||$schema===false:it.util.schemaHasRules($schema,it.RULES.all)){$it.schema=$schema;$it.schemaPath=$schemaPath;$it.errSchemaPath=$errSchemaPath;out+=" for (var "+$idx+" = "+0+"; "+$idx+" < "+$data+".length; "+$idx+"++) { ";$it.errorPath=it.util.getPathExpr(it.errorPath,$idx,it.opts.jsonPointers,true);var $passData=$data+"["+$idx+"]";$it.dataPathArr[$dataNxt]=$idx;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}if($breakOnError){out+=" if (!"+$nextValid+") break; "}out+=" }"}if($breakOnError){out+=" "+$closingBraces+" if ("+$errs+" == errors) {"}return out}},{}],367:[function(require,module,exports){"use strict";module.exports=function generate_multipleOf(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(!($isData||typeof $schema=="number")){throw new Error($keyword+" must be number")}out+="var division"+$lvl+";if (";if($isData){out+=" "+$schemaValue+" !== undefined && ( typeof "+$schemaValue+" != 'number' || "}out+=" (division"+$lvl+" = "+$data+" / "+$schemaValue+", ";if(it.opts.multipleOfPrecision){out+=" Math.abs(Math.round(division"+$lvl+") - division"+$lvl+") > 1e-"+it.opts.multipleOfPrecision+" "}else{out+=" division"+$lvl+" !== parseInt(division"+$lvl+") "}out+=" ) ";if($isData){out+=" ) "}out+=" ) { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"multipleOf"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { multipleOf: "+$schemaValue+" } ";if(it.opts.messages!==false){out+=" , message: 'should be multiple of ";if($isData){out+="' + "+$schemaValue}else{out+=""+$schemaValue+"'"}}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+="} ";if($breakOnError){out+=" else { "}return out}},{}],368:[function(require,module,exports){"use strict";module.exports=function generate_not(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $errs="errs__"+$lvl;var $it=it.util.copy(it);$it.level++;var $nextValid="valid"+$it.level;if(it.opts.strictKeywords?typeof $schema=="object"&&Object.keys($schema).length>0||$schema===false:it.util.schemaHasRules($schema,it.RULES.all)){$it.schema=$schema;$it.schemaPath=$schemaPath;$it.errSchemaPath=$errSchemaPath;out+=" var "+$errs+" = errors; ";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;$it.createErrors=false;var $allErrorsOption;if($it.opts.allErrors){$allErrorsOption=$it.opts.allErrors;$it.opts.allErrors=false}out+=" "+it.validate($it)+" ";$it.createErrors=true;if($allErrorsOption)$it.opts.allErrors=$allErrorsOption;it.compositeRule=$it.compositeRule=$wasComposite;out+=" if ("+$nextValid+") { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"not"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: 'should NOT be valid' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } else { errors = "+$errs+"; if (vErrors !== null) { if ("+$errs+") vErrors.length = "+$errs+"; else vErrors = null; } ";if(it.opts.allErrors){out+=" } "}}else{out+=" var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"not"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: 'should NOT be valid' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if($breakOnError){out+=" if (false) { "}}return out}},{}],369:[function(require,module,exports){"use strict";module.exports=function generate_oneOf(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $currentBaseId=$it.baseId,$prevValid="prevValid"+$lvl,$passingSchemas="passingSchemas"+$lvl;out+="var "+$errs+" = errors , "+$prevValid+" = false , "+$valid+" = false , "+$passingSchemas+" = null; ";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;var arr1=$schema;if(arr1){var $sch,$i=-1,l1=arr1.length-1;while($i<l1){$sch=arr1[$i+=1];if(it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)){$it.schema=$sch;$it.schemaPath=$schemaPath+"["+$i+"]";$it.errSchemaPath=$errSchemaPath+"/"+$i;out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId}else{out+=" var "+$nextValid+" = true; "}if($i){out+=" if ("+$nextValid+" && "+$prevValid+") { "+$valid+" = false; "+$passingSchemas+" = ["+$passingSchemas+", "+$i+"]; } else { ";$closingBraces+="}"}out+=" if ("+$nextValid+") { "+$valid+" = "+$prevValid+" = true; "+$passingSchemas+" = "+$i+"; }"}}it.compositeRule=$it.compositeRule=$wasComposite;out+=""+$closingBraces+"if (!"+$valid+") { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"oneOf"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { passingSchemas: "+$passingSchemas+" } ";if(it.opts.messages!==false){out+=" , message: 'should match exactly one schema in oneOf' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(vErrors); "}else{out+=" validate.errors = vErrors; return false; "}}out+="} else { errors = "+$errs+"; if (vErrors !== null) { if ("+$errs+") vErrors.length = "+$errs+"; else vErrors = null; }";if(it.opts.allErrors){out+=" } "}return out}},{}],370:[function(require,module,exports){"use strict";module.exports=function generate_pattern(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $regexp=$isData?"(new RegExp("+$schemaValue+"))":it.usePattern($schema);out+="if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'string') || "}out+=" !"+$regexp+".test("+$data+") ) { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"pattern"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { pattern: ";if($isData){out+=""+$schemaValue}else{out+=""+it.util.toQuotedString($schema)}out+=" } ";if(it.opts.messages!==false){out+=" , message: 'should match pattern \"";if($isData){out+="' + "+$schemaValue+" + '"}else{out+=""+it.util.escapeQuotes($schema)}out+="\"' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+it.util.toQuotedString($schema)}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+="} ";if($breakOnError){out+=" else { "}return out}},{}],371:[function(require,module,exports){"use strict";module.exports=function generate_properties(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $key="key"+$lvl,$idx="idx"+$lvl,$dataNxt=$it.dataLevel=it.dataLevel+1,$nextData="data"+$dataNxt,$dataProperties="dataProperties"+$lvl;var $schemaKeys=Object.keys($schema||{}).filter(notProto),$pProperties=it.schema.patternProperties||{},$pPropertyKeys=Object.keys($pProperties).filter(notProto),$aProperties=it.schema.additionalProperties,$someProperties=$schemaKeys.length||$pPropertyKeys.length,$noAdditional=$aProperties===false,$additionalIsSchema=typeof $aProperties=="object"&&Object.keys($aProperties).length,$removeAdditional=it.opts.removeAdditional,$checkAdditional=$noAdditional||$additionalIsSchema||$removeAdditional,$ownProperties=it.opts.ownProperties,$currentBaseId=it.baseId;var $required=it.schema.required;if($required&&!(it.opts.$data&&$required.$data)&&$required.length<it.opts.loopRequired){var $requiredHash=it.util.toHash($required)}function notProto(p){return p!=="__proto__"}out+="var "+$errs+" = errors;var "+$nextValid+" = true;";if($ownProperties){out+=" var "+$dataProperties+" = undefined;"}if($checkAdditional){if($ownProperties){out+=" "+$dataProperties+" = "+$dataProperties+" || Object.keys("+$data+"); for (var "+$idx+"=0; "+$idx+"<"+$dataProperties+".length; "+$idx+"++) { var "+$key+" = "+$dataProperties+"["+$idx+"]; "}else{out+=" for (var "+$key+" in "+$data+") { "}if($someProperties){out+=" var isAdditional"+$lvl+" = !(false ";if($schemaKeys.length){if($schemaKeys.length>8){out+=" || validate.schema"+$schemaPath+".hasOwnProperty("+$key+") "}else{var arr1=$schemaKeys;if(arr1){var $propertyKey,i1=-1,l1=arr1.length-1;while(i1<l1){$propertyKey=arr1[i1+=1];out+=" || "+$key+" == "+it.util.toQuotedString($propertyKey)+" "}}}}if($pPropertyKeys.length){var arr2=$pPropertyKeys;if(arr2){var $pProperty,$i=-1,l2=arr2.length-1;while($i<l2){$pProperty=arr2[$i+=1];out+=" || "+it.usePattern($pProperty)+".test("+$key+") "}}}out+=" ); if (isAdditional"+$lvl+") { "}if($removeAdditional=="all"){out+=" delete "+$data+"["+$key+"]; "}else{var $currentErrorPath=it.errorPath;var $additionalProperty="' + "+$key+" + '";if(it.opts._errorDataPathProperty){it.errorPath=it.util.getPathExpr(it.errorPath,$key,it.opts.jsonPointers)}if($noAdditional){if($removeAdditional){out+=" delete "+$data+"["+$key+"]; "}else{out+=" "+$nextValid+" = false; ";var $currErrSchemaPath=$errSchemaPath;$errSchemaPath=it.errSchemaPath+"/additionalProperties";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"additionalProperties"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { additionalProperty: '"+$additionalProperty+"' } ";if(it.opts.messages!==false){out+=" , message: '";if(it.opts._errorDataPathProperty){out+="is an invalid additional property"}else{out+="should NOT have additional properties"}out+="' "}if(it.opts.verbose){out+=" , schema: false , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}$errSchemaPath=$currErrSchemaPath;if($breakOnError){out+=" break; "}}}else if($additionalIsSchema){if($removeAdditional=="failing"){out+=" var "+$errs+" = errors; ";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;$it.schema=$aProperties;$it.schemaPath=it.schemaPath+".additionalProperties";$it.errSchemaPath=it.errSchemaPath+"/additionalProperties";$it.errorPath=it.opts._errorDataPathProperty?it.errorPath:it.util.getPathExpr(it.errorPath,$key,it.opts.jsonPointers);var $passData=$data+"["+$key+"]";$it.dataPathArr[$dataNxt]=$key;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}out+=" if (!"+$nextValid+") { errors = "+$errs+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+$data+"["+$key+"]; } ";it.compositeRule=$it.compositeRule=$wasComposite}else{$it.schema=$aProperties;$it.schemaPath=it.schemaPath+".additionalProperties";$it.errSchemaPath=it.errSchemaPath+"/additionalProperties";$it.errorPath=it.opts._errorDataPathProperty?it.errorPath:it.util.getPathExpr(it.errorPath,$key,it.opts.jsonPointers);var $passData=$data+"["+$key+"]";$it.dataPathArr[$dataNxt]=$key;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}if($breakOnError){out+=" if (!"+$nextValid+") break; "}}}it.errorPath=$currentErrorPath}if($someProperties){out+=" } "}out+=" } ";if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}var $useDefaults=it.opts.useDefaults&&!it.compositeRule;if($schemaKeys.length){var arr3=$schemaKeys;if(arr3){var $propertyKey,i3=-1,l3=arr3.length-1;while(i3<l3){$propertyKey=arr3[i3+=1];var $sch=$schema[$propertyKey];if(it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)){var $prop=it.util.getProperty($propertyKey),$passData=$data+$prop,$hasDefault=$useDefaults&&$sch.default!==undefined;$it.schema=$sch;$it.schemaPath=$schemaPath+$prop;$it.errSchemaPath=$errSchemaPath+"/"+it.util.escapeFragment($propertyKey);$it.errorPath=it.util.getPath(it.errorPath,$propertyKey,it.opts.jsonPointers);$it.dataPathArr[$dataNxt]=it.util.toQuotedString($propertyKey);var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){$code=it.util.varReplace($code,$nextData,$passData);var $useData=$passData}else{var $useData=$nextData;out+=" var "+$nextData+" = "+$passData+"; "}if($hasDefault){out+=" "+$code+" "}else{if($requiredHash&&$requiredHash[$propertyKey]){out+=" if ( "+$useData+" === undefined ";if($ownProperties){out+=" || ! Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($propertyKey)+"') "}out+=") { "+$nextValid+" = false; ";var $currentErrorPath=it.errorPath,$currErrSchemaPath=$errSchemaPath,$missingProperty=it.util.escapeQuotes($propertyKey);if(it.opts._errorDataPathProperty){it.errorPath=it.util.getPath($currentErrorPath,$propertyKey,it.opts.jsonPointers)}$errSchemaPath=it.errSchemaPath+"/required";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { missingProperty: '"+$missingProperty+"' } ";if(it.opts.messages!==false){out+=" , message: '";if(it.opts._errorDataPathProperty){out+="is a required property"}else{out+="should have required property \\'"+$missingProperty+"\\'"}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}$errSchemaPath=$currErrSchemaPath;it.errorPath=$currentErrorPath;out+=" } else { "}else{if($breakOnError){out+=" if ( "+$useData+" === undefined ";if($ownProperties){out+=" || ! Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($propertyKey)+"') "}out+=") { "+$nextValid+" = true; } else { "}else{out+=" if ("+$useData+" !== undefined ";if($ownProperties){out+=" && Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($propertyKey)+"') "}out+=" ) { "}}out+=" "+$code+" } "}}if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}}}if($pPropertyKeys.length){var arr4=$pPropertyKeys;if(arr4){var $pProperty,i4=-1,l4=arr4.length-1;while(i4<l4){$pProperty=arr4[i4+=1];var $sch=$pProperties[$pProperty];if(it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)){$it.schema=$sch;$it.schemaPath=it.schemaPath+".patternProperties"+it.util.getProperty($pProperty);$it.errSchemaPath=it.errSchemaPath+"/patternProperties/"+it.util.escapeFragment($pProperty);if($ownProperties){out+=" "+$dataProperties+" = "+$dataProperties+" || Object.keys("+$data+"); for (var "+$idx+"=0; "+$idx+"<"+$dataProperties+".length; "+$idx+"++) { var "+$key+" = "+$dataProperties+"["+$idx+"]; "}else{out+=" for (var "+$key+" in "+$data+") { "}out+=" if ("+it.usePattern($pProperty)+".test("+$key+")) { ";$it.errorPath=it.util.getPathExpr(it.errorPath,$key,it.opts.jsonPointers);var $passData=$data+"["+$key+"]";$it.dataPathArr[$dataNxt]=$key;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}if($breakOnError){out+=" if (!"+$nextValid+") break; "}out+=" } ";if($breakOnError){out+=" else "+$nextValid+" = true; "}out+=" } ";if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}}}}if($breakOnError){out+=" "+$closingBraces+" if ("+$errs+" == errors) {"}return out}},{}],372:[function(require,module,exports){"use strict";module.exports=function generate_propertyNames(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;out+="var "+$errs+" = errors;";if(it.opts.strictKeywords?typeof $schema=="object"&&Object.keys($schema).length>0||$schema===false:it.util.schemaHasRules($schema,it.RULES.all)){$it.schema=$schema;$it.schemaPath=$schemaPath;$it.errSchemaPath=$errSchemaPath
37
+ ;var $key="key"+$lvl,$idx="idx"+$lvl,$i="i"+$lvl,$invalidName="' + "+$key+" + '",$dataNxt=$it.dataLevel=it.dataLevel+1,$nextData="data"+$dataNxt,$dataProperties="dataProperties"+$lvl,$ownProperties=it.opts.ownProperties,$currentBaseId=it.baseId;if($ownProperties){out+=" var "+$dataProperties+" = undefined; "}if($ownProperties){out+=" "+$dataProperties+" = "+$dataProperties+" || Object.keys("+$data+"); for (var "+$idx+"=0; "+$idx+"<"+$dataProperties+".length; "+$idx+"++) { var "+$key+" = "+$dataProperties+"["+$idx+"]; "}else{out+=" for (var "+$key+" in "+$data+") { "}out+=" var startErrs"+$lvl+" = errors; ";var $passData=$key;var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}it.compositeRule=$it.compositeRule=$wasComposite;out+=" if (!"+$nextValid+") { for (var "+$i+"=startErrs"+$lvl+"; "+$i+"<errors; "+$i+"++) { vErrors["+$i+"].propertyName = "+$key+"; } var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"propertyNames"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { propertyName: '"+$invalidName+"' } ";if(it.opts.messages!==false){out+=" , message: 'property name \\'"+$invalidName+"\\' is invalid' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(vErrors); "}else{out+=" validate.errors = vErrors; return false; "}}if($breakOnError){out+=" break; "}out+=" } }"}if($breakOnError){out+=" "+$closingBraces+" if ("+$errs+" == errors) {"}return out}},{}],373:[function(require,module,exports){"use strict";module.exports=function generate_ref(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $async,$refCode;if($schema=="#"||$schema=="#/"){if(it.isRoot){$async=it.async;$refCode="validate"}else{$async=it.root.schema.$async===true;$refCode="root.refVal[0]"}}else{var $refVal=it.resolveRef(it.baseId,$schema,it.isRoot);if($refVal===undefined){var $message=it.MissingRefError.message(it.baseId,$schema);if(it.opts.missingRefs=="fail"){it.logger.error($message);var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"$ref"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { ref: '"+it.util.escapeQuotes($schema)+"' } ";if(it.opts.messages!==false){out+=" , message: 'can\\'t resolve reference "+it.util.escapeQuotes($schema)+"' "}if(it.opts.verbose){out+=" , schema: "+it.util.toQuotedString($schema)+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}if($breakOnError){out+=" if (false) { "}}else if(it.opts.missingRefs=="ignore"){it.logger.warn($message);if($breakOnError){out+=" if (true) { "}}else{throw new it.MissingRefError(it.baseId,$schema,$message)}}else if($refVal.inline){var $it=it.util.copy(it);$it.level++;var $nextValid="valid"+$it.level;$it.schema=$refVal.schema;$it.schemaPath="";$it.errSchemaPath=$schema;var $code=it.validate($it).replace(/validate\.schema/g,$refVal.code);out+=" "+$code+" ";if($breakOnError){out+=" if ("+$nextValid+") { "}}else{$async=$refVal.$async===true||it.async&&$refVal.$async!==false;$refCode=$refVal.code}}if($refCode){var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.opts.passContext){out+=" "+$refCode+".call(this, "}else{out+=" "+$refCode+"( "}out+=" "+$data+", (dataPath || '')";if(it.errorPath!='""'){out+=" + "+it.errorPath}var $parentData=$dataLvl?"data"+($dataLvl-1||""):"parentData",$parentDataProperty=$dataLvl?it.dataPathArr[$dataLvl]:"parentDataProperty";out+=" , "+$parentData+" , "+$parentDataProperty+", rootData) ";var __callValidate=out;out=$$outStack.pop();if($async){if(!it.async)throw new Error("async schema referenced by sync schema");if($breakOnError){out+=" var "+$valid+"; "}out+=" try { await "+__callValidate+"; ";if($breakOnError){out+=" "+$valid+" = true; "}out+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ";if($breakOnError){out+=" "+$valid+" = false; "}out+=" } ";if($breakOnError){out+=" if ("+$valid+") { "}}else{out+=" if (!"+__callValidate+") { if (vErrors === null) vErrors = "+$refCode+".errors; else vErrors = vErrors.concat("+$refCode+".errors); errors = vErrors.length; } ";if($breakOnError){out+=" else { "}}}return out}},{}],374:[function(require,module,exports){"use strict";module.exports=function generate_required(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $vSchema="schema"+$lvl;if(!$isData){if($schema.length<it.opts.loopRequired&&it.schema.properties&&Object.keys(it.schema.properties).length){var $required=[];var arr1=$schema;if(arr1){var $property,i1=-1,l1=arr1.length-1;while(i1<l1){$property=arr1[i1+=1];var $propertySch=it.schema.properties[$property];if(!($propertySch&&(it.opts.strictKeywords?typeof $propertySch=="object"&&Object.keys($propertySch).length>0||$propertySch===false:it.util.schemaHasRules($propertySch,it.RULES.all)))){$required[$required.length]=$property}}}}else{var $required=$schema}}if($isData||$required.length){var $currentErrorPath=it.errorPath,$loopRequired=$isData||$required.length>=it.opts.loopRequired,$ownProperties=it.opts.ownProperties;if($breakOnError){out+=" var missing"+$lvl+"; ";if($loopRequired){if(!$isData){out+=" var "+$vSchema+" = validate.schema"+$schemaPath+"; "}var $i="i"+$lvl,$propertyPath="schema"+$lvl+"["+$i+"]",$missingProperty="' + "+$propertyPath+" + '";if(it.opts._errorDataPathProperty){it.errorPath=it.util.getPathExpr($currentErrorPath,$propertyPath,it.opts.jsonPointers)}out+=" var "+$valid+" = true; ";if($isData){out+=" if (schema"+$lvl+" === undefined) "+$valid+" = true; else if (!Array.isArray(schema"+$lvl+")) "+$valid+" = false; else {"}out+=" for (var "+$i+" = 0; "+$i+" < "+$vSchema+".length; "+$i+"++) { "+$valid+" = "+$data+"["+$vSchema+"["+$i+"]] !== undefined ";if($ownProperties){out+=" && Object.prototype.hasOwnProperty.call("+$data+", "+$vSchema+"["+$i+"]) "}out+="; if (!"+$valid+") break; } ";if($isData){out+=" } "}out+=" if (!"+$valid+") { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { missingProperty: '"+$missingProperty+"' } ";if(it.opts.messages!==false){out+=" , message: '";if(it.opts._errorDataPathProperty){out+="is a required property"}else{out+="should have required property \\'"+$missingProperty+"\\'"}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } else { "}else{out+=" if ( ";var arr2=$required;if(arr2){var $propertyKey,$i=-1,l2=arr2.length-1;while($i<l2){$propertyKey=arr2[$i+=1];if($i){out+=" || "}var $prop=it.util.getProperty($propertyKey),$useData=$data+$prop;out+=" ( ( "+$useData+" === undefined ";if($ownProperties){out+=" || ! Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($propertyKey)+"') "}out+=") && (missing"+$lvl+" = "+it.util.toQuotedString(it.opts.jsonPointers?$propertyKey:$prop)+") ) "}}out+=") { ";var $propertyPath="missing"+$lvl,$missingProperty="' + "+$propertyPath+" + '";if(it.opts._errorDataPathProperty){it.errorPath=it.opts.jsonPointers?it.util.getPathExpr($currentErrorPath,$propertyPath,true):$currentErrorPath+" + "+$propertyPath}var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { missingProperty: '"+$missingProperty+"' } ";if(it.opts.messages!==false){out+=" , message: '";if(it.opts._errorDataPathProperty){out+="is a required property"}else{out+="should have required property \\'"+$missingProperty+"\\'"}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } else { "}}else{if($loopRequired){if(!$isData){out+=" var "+$vSchema+" = validate.schema"+$schemaPath+"; "}var $i="i"+$lvl,$propertyPath="schema"+$lvl+"["+$i+"]",$missingProperty="' + "+$propertyPath+" + '";if(it.opts._errorDataPathProperty){it.errorPath=it.util.getPathExpr($currentErrorPath,$propertyPath,it.opts.jsonPointers)}if($isData){out+=" if ("+$vSchema+" && !Array.isArray("+$vSchema+")) { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { missingProperty: '"+$missingProperty+"' } ";if(it.opts.messages!==false){out+=" , message: '";if(it.opts._errorDataPathProperty){out+="is a required property"}else{out+="should have required property \\'"+$missingProperty+"\\'"}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+$vSchema+" !== undefined) { "}out+=" for (var "+$i+" = 0; "+$i+" < "+$vSchema+".length; "+$i+"++) { if ("+$data+"["+$vSchema+"["+$i+"]] === undefined ";if($ownProperties){out+=" || ! Object.prototype.hasOwnProperty.call("+$data+", "+$vSchema+"["+$i+"]) "}out+=") { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { missingProperty: '"+$missingProperty+"' } ";if(it.opts.messages!==false){out+=" , message: '";if(it.opts._errorDataPathProperty){out+="is a required property"}else{out+="should have required property \\'"+$missingProperty+"\\'"}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ";if($isData){out+=" } "}}else{var arr3=$required;if(arr3){var $propertyKey,i3=-1,l3=arr3.length-1;while(i3<l3){$propertyKey=arr3[i3+=1];var $prop=it.util.getProperty($propertyKey),$missingProperty=it.util.escapeQuotes($propertyKey),$useData=$data+$prop;if(it.opts._errorDataPathProperty){it.errorPath=it.util.getPath($currentErrorPath,$propertyKey,it.opts.jsonPointers)}out+=" if ( "+$useData+" === undefined ";if($ownProperties){out+=" || ! Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($propertyKey)+"') "}out+=") { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"required"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { missingProperty: '"+$missingProperty+"' } ";if(it.opts.messages!==false){out+=" , message: '";if(it.opts._errorDataPathProperty){out+="is a required property"}else{out+="should have required property \\'"+$missingProperty+"\\'"}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}}}it.errorPath=$currentErrorPath}else if($breakOnError){out+=" if (true) {"}return out}},{}],375:[function(require,module,exports){"use strict";module.exports=function generate_uniqueItems(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(($schema||$isData)&&it.opts.uniqueItems!==false){if($isData){out+=" var "+$valid+"; if ("+$schemaValue+" === false || "+$schemaValue+" === undefined) "+$valid+" = true; else if (typeof "+$schemaValue+" != 'boolean') "+$valid+" = false; else { "}out+=" var i = "+$data+".length , "+$valid+" = true , j; if (i > 1) { ";var $itemType=it.schema.items&&it.schema.items.type,$typeIsArray=Array.isArray($itemType);if(!$itemType||$itemType=="object"||$itemType=="array"||$typeIsArray&&($itemType.indexOf("object")>=0||$itemType.indexOf("array")>=0)){out+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+$data+"[i], "+$data+"[j])) { "+$valid+" = false; break outer; } } } "}else{out+=" var itemIndices = {}, item; for (;i--;) { var item = "+$data+"[i]; ";var $method="checkDataType"+($typeIsArray?"s":"");out+=" if ("+it.util[$method]($itemType,"item",it.opts.strictNumbers,true)+") continue; ";if($typeIsArray){out+=" if (typeof item == 'string') item = '\"' + item; "}out+=" if (typeof itemIndices[item] == 'number') { "+$valid+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}out+=" } ";if($isData){out+=" } "}out+=" if (!"+$valid+") { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"uniqueItems"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { i: i, j: j } ";if(it.opts.messages!==false){out+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } ";if($breakOnError){out+=" else { "}}else{if($breakOnError){out+=" if (true) { "}}return out}},{}],376:[function(require,module,exports){"use strict";module.exports=function generate_validate(it,$keyword,$ruleType){var out="";var $async=it.schema.$async===true,$refKeywords=it.util.schemaHasRulesExcept(it.schema,it.RULES.all,"$ref"),$id=it.self._getId(it.schema);if(it.opts.strictKeywords){var $unknownKwd=it.util.schemaUnknownRules(it.schema,it.RULES.keywords);if($unknownKwd){var $keywordsMsg="unknown keyword: "+$unknownKwd;if(it.opts.strictKeywords==="log")it.logger.warn($keywordsMsg);else throw new Error($keywordsMsg)}}if(it.isTop){out+=" var validate = ";if($async){it.async=true;out+="async "}out+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ";if($id&&(it.opts.sourceCode||it.opts.processCode)){out+=" "+("/*# sourceURL="+$id+" */")+" "}}if(typeof it.schema=="boolean"||!($refKeywords||it.schema.$ref)){var $keyword="false schema";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;if(it.schema===false){if(it.isTop){$breakOnError=true}else{out+=" var "+$valid+" = false; "}var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"false schema")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: 'boolean schema is false' "}if(it.opts.verbose){out+=" , schema: false , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}}else{if(it.isTop){if($async){out+=" return data; "}else{out+=" validate.errors = null; return true; "}}else{out+=" var "+$valid+" = true; "}}if(it.isTop){out+=" }; return validate; "}return out}if(it.isTop){var $top=it.isTop,$lvl=it.level=0,$dataLvl=it.dataLevel=0,$data="data";it.rootId=it.resolve.fullPath(it.self._getId(it.root.schema));it.baseId=it.baseId||it.rootId;delete it.isTop;it.dataPathArr=[""];if(it.schema.default!==undefined&&it.opts.useDefaults&&it.opts.strictDefaults){var $defaultMsg="default is ignored in the schema root";if(it.opts.strictDefaults==="log")it.logger.warn($defaultMsg);else throw new Error($defaultMsg)}out+=" var vErrors = null; ";out+=" var errors = 0; ";out+=" if (rootData === undefined) rootData = data; "}else{var $lvl=it.level,$dataLvl=it.dataLevel,$data="data"+($dataLvl||"");if($id)it.baseId=it.resolve.url(it.baseId,$id);if($async&&!it.async)throw new Error("async schema in sync schema");out+=" var errs_"+$lvl+" = errors;"}var $valid="valid"+$lvl,$breakOnError=!it.opts.allErrors,$closingBraces1="",$closingBraces2="";var $errorKeyword;var $typeSchema=it.schema.type,$typeIsArray=Array.isArray($typeSchema);if($typeSchema&&it.opts.nullable&&it.schema.nullable===true){if($typeIsArray){if($typeSchema.indexOf("null")==-1)$typeSchema=$typeSchema.concat("null")}else if($typeSchema!="null"){$typeSchema=[$typeSchema,"null"];$typeIsArray=true}}if($typeIsArray&&$typeSchema.length==1){$typeSchema=$typeSchema[0];$typeIsArray=false}if(it.schema.$ref&&$refKeywords){if(it.opts.extendRefs=="fail"){throw new Error('$ref: validation keywords used in schema at path "'+it.errSchemaPath+'" (see option extendRefs)')}else if(it.opts.extendRefs!==true){$refKeywords=false;it.logger.warn('$ref: keywords ignored in schema at path "'+it.errSchemaPath+'"')}}if(it.schema.$comment&&it.opts.$comment){out+=" "+it.RULES.all.$comment.code(it,"$comment")}if($typeSchema){if(it.opts.coerceTypes){var $coerceToTypes=it.util.coerceToTypes(it.opts.coerceTypes,$typeSchema)}var $rulesGroup=it.RULES.types[$typeSchema];if($coerceToTypes||$typeIsArray||$rulesGroup===true||$rulesGroup&&!$shouldUseGroup($rulesGroup)){var $schemaPath=it.schemaPath+".type",$errSchemaPath=it.errSchemaPath+"/type";var $schemaPath=it.schemaPath+".type",$errSchemaPath=it.errSchemaPath+"/type",$method=$typeIsArray?"checkDataTypes":"checkDataType";out+=" if ("+it.util[$method]($typeSchema,$data,it.opts.strictNumbers,true)+") { ";if($coerceToTypes){var $dataType="dataType"+$lvl,$coerced="coerced"+$lvl;out+=" var "+$dataType+" = typeof "+$data+"; var "+$coerced+" = undefined; ";if(it.opts.coerceTypes=="array"){out+=" if ("+$dataType+" == 'object' && Array.isArray("+$data+") && "+$data+".length == 1) { "+$data+" = "+$data+"[0]; "+$dataType+" = typeof "+$data+"; if ("+it.util.checkDataType(it.schema.type,$data,it.opts.strictNumbers)+") "+$coerced+" = "+$data+"; } "}out+=" if ("+$coerced+" !== undefined) ; ";var arr1=$coerceToTypes;if(arr1){var $type,$i=-1,l1=arr1.length-1;while($i<l1){$type=arr1[$i+=1];if($type=="string"){out+=" else if ("+$dataType+" == 'number' || "+$dataType+" == 'boolean') "+$coerced+" = '' + "+$data+"; else if ("+$data+" === null) "+$coerced+" = ''; "}else if($type=="number"||$type=="integer"){out+=" else if ("+$dataType+" == 'boolean' || "+$data+" === null || ("+$dataType+" == 'string' && "+$data+" && "+$data+" == +"+$data+" ";if($type=="integer"){out+=" && !("+$data+" % 1)"}out+=")) "+$coerced+" = +"+$data+"; "}else if($type=="boolean"){out+=" else if ("+$data+" === 'false' || "+$data+" === 0 || "+$data+" === null) "+$coerced+" = false; else if ("+$data+" === 'true' || "+$data+" === 1) "+$coerced+" = true; "}else if($type=="null"){out+=" else if ("+$data+" === '' || "+$data+" === 0 || "+$data+" === false) "+$coerced+" = null; "}else if(it.opts.coerceTypes=="array"&&$type=="array"){out+=" else if ("+$dataType+" == 'string' || "+$dataType+" == 'number' || "+$dataType+" == 'boolean' || "+$data+" == null) "+$coerced+" = ["+$data+"]; "}}}out+=" else { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"type")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { type: '";if($typeIsArray){out+=""+$typeSchema.join(",")}else{out+=""+$typeSchema}out+="' } ";if(it.opts.messages!==false){out+=" , message: 'should be ";if($typeIsArray){out+=""+$typeSchema.join(",")}else{out+=""+$typeSchema}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } if ("+$coerced+" !== undefined) { ";var $parentData=$dataLvl?"data"+($dataLvl-1||""):"parentData",$parentDataProperty=$dataLvl?it.dataPathArr[$dataLvl]:"parentDataProperty";out+=" "+$data+" = "+$coerced+"; ";if(!$dataLvl){out+="if ("+$parentData+" !== undefined)"}out+=" "+$parentData+"["+$parentDataProperty+"] = "+$coerced+"; } "}else{var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"type")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { type: '";if($typeIsArray){out+=""+$typeSchema.join(",")}else{out+=""+$typeSchema}out+="' } ";if(it.opts.messages!==false){out+=" , message: 'should be ";if($typeIsArray){out+=""+$typeSchema.join(",")}else{out+=""+$typeSchema}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}}out+=" } "}}if(it.schema.$ref&&!$refKeywords){out+=" "+it.RULES.all.$ref.code(it,"$ref")+" ";if($breakOnError){out+=" } if (errors === ";if($top){out+="0"}else{out+="errs_"+$lvl}out+=") { ";$closingBraces2+="}"}}else{var arr2=it.RULES;if(arr2){var $rulesGroup,i2=-1,l2=arr2.length-1;while(i2<l2){$rulesGroup=arr2[i2+=1];if($shouldUseGroup($rulesGroup)){if($rulesGroup.type){out+=" if ("+it.util.checkDataType($rulesGroup.type,$data,it.opts.strictNumbers)+") { "}if(it.opts.useDefaults){if($rulesGroup.type=="object"&&it.schema.properties){var $schema=it.schema.properties,$schemaKeys=Object.keys($schema);var arr3=$schemaKeys;if(arr3){var $propertyKey,i3=-1,l3=arr3.length-1;while(i3<l3){$propertyKey=arr3[i3+=1];var $sch=$schema[$propertyKey];if($sch.default!==undefined){var $passData=$data+it.util.getProperty($propertyKey);if(it.compositeRule){if(it.opts.strictDefaults){var $defaultMsg="default is ignored for: "+$passData;if(it.opts.strictDefaults==="log")it.logger.warn($defaultMsg);else throw new Error($defaultMsg)}}else{out+=" if ("+$passData+" === undefined ";if(it.opts.useDefaults=="empty"){out+=" || "+$passData+" === null || "+$passData+" === '' "}out+=" ) "+$passData+" = ";if(it.opts.useDefaults=="shared"){out+=" "+it.useDefault($sch.default)+" "}else{out+=" "+JSON.stringify($sch.default)+" "}out+="; "}}}}}else if($rulesGroup.type=="array"&&Array.isArray(it.schema.items)){var arr4=it.schema.items;if(arr4){var $sch,$i=-1,l4=arr4.length-1;while($i<l4){$sch=arr4[$i+=1];if($sch.default!==undefined){var $passData=$data+"["+$i+"]";if(it.compositeRule){if(it.opts.strictDefaults){var $defaultMsg="default is ignored for: "+$passData;if(it.opts.strictDefaults==="log")it.logger.warn($defaultMsg);else throw new Error($defaultMsg)}}else{out+=" if ("+$passData+" === undefined ";if(it.opts.useDefaults=="empty"){out+=" || "+$passData+" === null || "+$passData+" === '' "}out+=" ) "+$passData+" = ";if(it.opts.useDefaults=="shared"){out+=" "+it.useDefault($sch.default)+" "}else{out+=" "+JSON.stringify($sch.default)+" "}out+="; "}}}}}}var arr5=$rulesGroup.rules;if(arr5){var $rule,i5=-1,l5=arr5.length-1;while(i5<l5){$rule=arr5[i5+=1];if($shouldUseRule($rule)){var $code=$rule.code(it,$rule.keyword,$rulesGroup.type);if($code){out+=" "+$code+" ";if($breakOnError){$closingBraces1+="}"}}}}}if($breakOnError){out+=" "+$closingBraces1+" ";$closingBraces1=""}if($rulesGroup.type){out+=" } ";if($typeSchema&&$typeSchema===$rulesGroup.type&&!$coerceToTypes){out+=" else { ";var $schemaPath=it.schemaPath+".type",$errSchemaPath=it.errSchemaPath+"/type";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"type")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { type: '";if($typeIsArray){out+=""+$typeSchema.join(",")}else{out+=""+$typeSchema}out+="' } ";if(it.opts.messages!==false){out+=" , message: 'should be ";if($typeIsArray){out+=""+$typeSchema.join(",")}else{out+=""+$typeSchema}out+="' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } "}}if($breakOnError){out+=" if (errors === ";if($top){out+="0"}else{out+="errs_"+$lvl}out+=") { ";$closingBraces2+="}"}}}}}if($breakOnError){out+=" "+$closingBraces2+" "}if($top){if($async){out+=" if (errors === 0) return data; ";out+=" else throw new ValidationError(vErrors); "}else{out+=" validate.errors = vErrors; ";out+=" return errors === 0; "}out+=" }; return validate;"}else{out+=" var "+$valid+" = errors === errs_"+$lvl+";"}function $shouldUseGroup($rulesGroup){var rules=$rulesGroup.rules;for(var i=0;i<rules.length;i++)if($shouldUseRule(rules[i]))return true}function $shouldUseRule($rule){return it.schema[$rule.keyword]!==undefined||$rule.implements&&$ruleImplementsSomeKeyword($rule)}function $ruleImplementsSomeKeyword($rule){var impl=$rule.implements;for(var i=0;i<impl.length;i++)if(it.schema[impl[i]]!==undefined)return true}return out}},{}],377:[function(require,module,exports){"use strict";var IDENTIFIER=/^[a-z_$][a-z0-9_$-]*$/i;var customRuleCode=require("./dotjs/custom");var definitionSchema=require("./definition_schema");module.exports={add:addKeyword,get:getKeyword,remove:removeKeyword,validate:validateKeyword};function addKeyword(keyword,definition){var RULES=this.RULES;if(RULES.keywords[keyword])throw new Error("Keyword "+keyword+" is already defined");if(!IDENTIFIER.test(keyword))throw new Error("Keyword "+keyword+" is not a valid identifier");if(definition){this.validateKeyword(definition,true);var dataType=definition.type;if(Array.isArray(dataType)){for(var i=0;i<dataType.length;i++)_addRule(keyword,dataType[i],definition)}else{_addRule(keyword,dataType,definition)}var metaSchema=definition.metaSchema;if(metaSchema){if(definition.$data&&this._opts.$data){metaSchema={anyOf:[metaSchema,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}}definition.validateSchema=this.compile(metaSchema,true)}}RULES.keywords[keyword]=RULES.all[keyword]=true;function _addRule(keyword,dataType,definition){var ruleGroup;for(var i=0;i<RULES.length;i++){var rg=RULES[i];if(rg.type==dataType){ruleGroup=rg;break}}if(!ruleGroup){ruleGroup={type:dataType,rules:[]};RULES.push(ruleGroup)}var rule={keyword:keyword,definition:definition,custom:true,code:customRuleCode,implements:definition.implements};ruleGroup.rules.push(rule);RULES.custom[keyword]=rule}return this}function getKeyword(keyword){var rule=this.RULES.custom[keyword];return rule?rule.definition:this.RULES.keywords[keyword]||false}function removeKeyword(keyword){var RULES=this.RULES;delete RULES.keywords[keyword];delete RULES.all[keyword];delete RULES.custom[keyword];for(var i=0;i<RULES.length;i++){var rules=RULES[i].rules;for(var j=0;j<rules.length;j++){if(rules[j].keyword==keyword){rules.splice(j,1);break}}}return this}function validateKeyword(definition,throwError){validateKeyword.errors=null;var v=this._validateKeyword=this._validateKeyword||this.compile(definitionSchema,true);if(v(definition))return true;validateKeyword.errors=v.errors;if(throwError)throw new Error("custom keyword definition is invalid: "+this.errorsText(v.errors));else return false}},{"./definition_schema":350,"./dotjs/custom":360}],378:[function(require,module,exports){module.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:false}},{}],379:[function(require,module,exports){module.exports={$schema:"http://json-schema.org/draft-06/schema#",$id:"http://json-schema.org/draft-06/schema#",
38
+ title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},title:{type:"string"},description:{type:"string"},default:{},examples:{type:"array",items:{}},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:{}},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:{},enum:{type:"array",minItems:1,uniqueItems:true},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:true}]},format:{type:"string"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:{}}},{}],380:[function(require,module,exports){module.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:true,readOnly:{type:"boolean",default:false},examples:{type:"array",items:true},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:true},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:true,enum:{type:"array",items:true,minItems:1,uniqueItems:true},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:true}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:true}},{}],381:[function(require,module,exports){module.exports={newInvalidAsn1Error:function(msg){var e=new Error;e.name="InvalidAsn1Error";e.message=msg||"";return e}}},{}],382:[function(require,module,exports){var errors=require("./errors");var types=require("./types");var Reader=require("./reader");var Writer=require("./writer");module.exports={Reader:Reader,Writer:Writer};for(var t in types){if(types.hasOwnProperty(t))module.exports[t]=types[t]}for(var e in errors){if(errors.hasOwnProperty(e))module.exports[e]=errors[e]}},{"./errors":381,"./reader":383,"./types":384,"./writer":385}],383:[function(require,module,exports){var assert=require("assert");var Buffer=require("safer-buffer").Buffer;var ASN1=require("./types");var errors=require("./errors");var newInvalidAsn1Error=errors.newInvalidAsn1Error;function Reader(data){if(!data||!Buffer.isBuffer(data))throw new TypeError("data must be a node Buffer");this._buf=data;this._size=data.length;this._len=0;this._offset=0}Object.defineProperty(Reader.prototype,"length",{enumerable:true,get:function(){return this._len}});Object.defineProperty(Reader.prototype,"offset",{enumerable:true,get:function(){return this._offset}});Object.defineProperty(Reader.prototype,"remain",{get:function(){return this._size-this._offset}});Object.defineProperty(Reader.prototype,"buffer",{get:function(){return this._buf.slice(this._offset)}});Reader.prototype.readByte=function(peek){if(this._size-this._offset<1)return null;var b=this._buf[this._offset]&255;if(!peek)this._offset+=1;return b};Reader.prototype.peek=function(){return this.readByte(true)};Reader.prototype.readLength=function(offset){if(offset===undefined)offset=this._offset;if(offset>=this._size)return null;var lenB=this._buf[offset++]&255;if(lenB===null)return null;if((lenB&128)===128){lenB&=127;if(lenB===0)throw newInvalidAsn1Error("Indefinite length not supported");if(lenB>4)throw newInvalidAsn1Error("encoding too long");if(this._size-offset<lenB)return null;this._len=0;for(var i=0;i<lenB;i++)this._len=(this._len<<8)+(this._buf[offset++]&255)}else{this._len=lenB}return offset};Reader.prototype.readSequence=function(tag){var seq=this.peek();if(seq===null)return null;if(tag!==undefined&&tag!==seq)throw newInvalidAsn1Error("Expected 0x"+tag.toString(16)+": got 0x"+seq.toString(16));var o=this.readLength(this._offset+1);if(o===null)return null;this._offset=o;return seq};Reader.prototype.readInt=function(){return this._readTag(ASN1.Integer)};Reader.prototype.readBoolean=function(){return this._readTag(ASN1.Boolean)===0?false:true};Reader.prototype.readEnumeration=function(){return this._readTag(ASN1.Enumeration)};Reader.prototype.readString=function(tag,retbuf){if(!tag)tag=ASN1.OctetString;var b=this.peek();if(b===null)return null;if(b!==tag)throw newInvalidAsn1Error("Expected 0x"+tag.toString(16)+": got 0x"+b.toString(16));var o=this.readLength(this._offset+1);if(o===null)return null;if(this.length>this._size-o)return null;this._offset=o;if(this.length===0)return retbuf?Buffer.alloc(0):"";var str=this._buf.slice(this._offset,this._offset+this.length);this._offset+=this.length;return retbuf?str:str.toString("utf8")};Reader.prototype.readOID=function(tag){if(!tag)tag=ASN1.OID;var b=this.readString(tag,true);if(b===null)return null;var values=[];var value=0;for(var i=0;i<b.length;i++){var byte=b[i]&255;value<<=7;value+=byte&127;if((byte&128)===0){values.push(value);value=0}}value=values.shift();values.unshift(value%40);values.unshift(value/40>>0);return values.join(".")};Reader.prototype._readTag=function(tag){assert.ok(tag!==undefined);var b=this.peek();if(b===null)return null;if(b!==tag)throw newInvalidAsn1Error("Expected 0x"+tag.toString(16)+": got 0x"+b.toString(16));var o=this.readLength(this._offset+1);if(o===null)return null;if(this.length>4)throw newInvalidAsn1Error("Integer too long: "+this.length);if(this.length>this._size-o)return null;this._offset=o;var fb=this._buf[this._offset];var value=0;for(var i=0;i<this.length;i++){value<<=8;value|=this._buf[this._offset++]&255}if((fb&128)===128&&i!==4)value-=1<<i*8;return value>>0};module.exports=Reader},{"./errors":381,"./types":384,assert:16,"safer-buffer":470}],384:[function(require,module,exports){module.exports={EOC:0,Boolean:1,Integer:2,BitString:3,OctetString:4,Null:5,OID:6,ObjectDescriptor:7,External:8,Real:9,Enumeration:10,PDV:11,Utf8String:12,RelativeOID:13,Sequence:16,Set:17,NumericString:18,PrintableString:19,T61String:20,VideotexString:21,IA5String:22,UTCTime:23,GeneralizedTime:24,GraphicString:25,VisibleString:26,GeneralString:28,UniversalString:29,CharacterString:30,BMPString:31,Constructor:32,Context:128}},{}],385:[function(require,module,exports){var assert=require("assert");var Buffer=require("safer-buffer").Buffer;var ASN1=require("./types");var errors=require("./errors");var newInvalidAsn1Error=errors.newInvalidAsn1Error;var DEFAULT_OPTS={size:1024,growthFactor:8};function merge(from,to){assert.ok(from);assert.equal(typeof from,"object");assert.ok(to);assert.equal(typeof to,"object");var keys=Object.getOwnPropertyNames(from);keys.forEach(function(key){if(to[key])return;var value=Object.getOwnPropertyDescriptor(from,key);Object.defineProperty(to,key,value)});return to}function Writer(options){options=merge(DEFAULT_OPTS,options||{});this._buf=Buffer.alloc(options.size||1024);this._size=this._buf.length;this._offset=0;this._options=options;this._seq=[]}Object.defineProperty(Writer.prototype,"buffer",{get:function(){if(this._seq.length)throw newInvalidAsn1Error(this._seq.length+" unended sequence(s)");return this._buf.slice(0,this._offset)}});Writer.prototype.writeByte=function(b){if(typeof b!=="number")throw new TypeError("argument must be a Number");this._ensure(1);this._buf[this._offset++]=b};Writer.prototype.writeInt=function(i,tag){if(typeof i!=="number")throw new TypeError("argument must be a Number");if(typeof tag!=="number")tag=ASN1.Integer;var sz=4;while(((i&4286578688)===0||(i&4286578688)===4286578688>>0)&&sz>1){sz--;i<<=8}if(sz>4)throw newInvalidAsn1Error("BER ints cannot be > 0xffffffff");this._ensure(2+sz);this._buf[this._offset++]=tag;this._buf[this._offset++]=sz;while(sz-- >0){this._buf[this._offset++]=(i&4278190080)>>>24;i<<=8}};Writer.prototype.writeNull=function(){this.writeByte(ASN1.Null);this.writeByte(0)};Writer.prototype.writeEnumeration=function(i,tag){if(typeof i!=="number")throw new TypeError("argument must be a Number");if(typeof tag!=="number")tag=ASN1.Enumeration;return this.writeInt(i,tag)};Writer.prototype.writeBoolean=function(b,tag){if(typeof b!=="boolean")throw new TypeError("argument must be a Boolean");if(typeof tag!=="number")tag=ASN1.Boolean;this._ensure(3);this._buf[this._offset++]=tag;this._buf[this._offset++]=1;this._buf[this._offset++]=b?255:0};Writer.prototype.writeString=function(s,tag){if(typeof s!=="string")throw new TypeError("argument must be a string (was: "+typeof s+")");if(typeof tag!=="number")tag=ASN1.OctetString;var len=Buffer.byteLength(s);this.writeByte(tag);this.writeLength(len);if(len){this._ensure(len);this._buf.write(s,this._offset);this._offset+=len}};Writer.prototype.writeBuffer=function(buf,tag){if(typeof tag!=="number")throw new TypeError("tag must be a number");if(!Buffer.isBuffer(buf))throw new TypeError("argument must be a buffer");this.writeByte(tag);this.writeLength(buf.length);this._ensure(buf.length);buf.copy(this._buf,this._offset,0,buf.length);this._offset+=buf.length};Writer.prototype.writeStringArray=function(strings){if(!strings instanceof Array)throw new TypeError("argument must be an Array[String]");var self=this;strings.forEach(function(s){self.writeString(s)})};Writer.prototype.writeOID=function(s,tag){if(typeof s!=="string")throw new TypeError("argument must be a string");if(typeof tag!=="number")tag=ASN1.OID;if(!/^([0-9]+\.){3,}[0-9]+$/.test(s))throw new Error("argument is not a valid OID string");function encodeOctet(bytes,octet){if(octet<128){bytes.push(octet)}else if(octet<16384){bytes.push(octet>>>7|128);bytes.push(octet&127)}else if(octet<2097152){bytes.push(octet>>>14|128);bytes.push((octet>>>7|128)&255);bytes.push(octet&127)}else if(octet<268435456){bytes.push(octet>>>21|128);bytes.push((octet>>>14|128)&255);bytes.push((octet>>>7|128)&255);bytes.push(octet&127)}else{bytes.push((octet>>>28|128)&255);bytes.push((octet>>>21|128)&255);bytes.push((octet>>>14|128)&255);bytes.push((octet>>>7|128)&255);bytes.push(octet&127)}}var tmp=s.split(".");var bytes=[];bytes.push(parseInt(tmp[0],10)*40+parseInt(tmp[1],10));tmp.slice(2).forEach(function(b){encodeOctet(bytes,parseInt(b,10))});var self=this;this._ensure(2+bytes.length);this.writeByte(tag);this.writeLength(bytes.length);bytes.forEach(function(b){self.writeByte(b)})};Writer.prototype.writeLength=function(len){if(typeof len!=="number")throw new TypeError("argument must be a Number");this._ensure(4);if(len<=127){this._buf[this._offset++]=len}else if(len<=255){this._buf[this._offset++]=129;this._buf[this._offset++]=len}else if(len<=65535){this._buf[this._offset++]=130;this._buf[this._offset++]=len>>8;this._buf[this._offset++]=len}else if(len<=16777215){this._buf[this._offset++]=131;this._buf[this._offset++]=len>>16;this._buf[this._offset++]=len>>8;this._buf[this._offset++]=len}else{throw newInvalidAsn1Error("Length too long (> 4 bytes)")}};Writer.prototype.startSequence=function(tag){if(typeof tag!=="number")tag=ASN1.Sequence|ASN1.Constructor;this.writeByte(tag);this._seq.push(this._offset);this._ensure(3);this._offset+=3};Writer.prototype.endSequence=function(){var seq=this._seq.pop();var start=seq+3;var len=this._offset-start;if(len<=127){this._shift(start,len,-2);this._buf[seq]=len}else if(len<=255){this._shift(start,len,-1);this._buf[seq]=129;this._buf[seq+1]=len}else if(len<=65535){this._buf[seq]=130;this._buf[seq+1]=len>>8;this._buf[seq+2]=len}else if(len<=16777215){this._shift(start,len,1);this._buf[seq]=131;this._buf[seq+1]=len>>16;this._buf[seq+2]=len>>8;this._buf[seq+3]=len}else{throw newInvalidAsn1Error("Sequence too long")}};Writer.prototype._shift=function(start,len,shift){assert.ok(start!==undefined);assert.ok(len!==undefined);assert.ok(shift);this._buf.copy(this._buf,start+shift,start,start+len);this._offset+=shift};Writer.prototype._ensure=function(len){assert.ok(len);if(this._size-this._offset<len){var sz=this._size*this._options.growthFactor;if(sz-this._offset<len)sz+=len;var buf=Buffer.alloc(sz);this._buf.copy(buf,0,0,this._offset);this._buf=buf;this._size=sz}};module.exports=Writer},{"./errors":381,"./types":384,assert:16,"safer-buffer":470}],386:[function(require,module,exports){var Ber=require("./ber/index");module.exports={Ber:Ber,BerReader:Ber.Reader,BerWriter:Ber.Writer}},{"./ber/index":382}],387:[function(require,module,exports){(function(Buffer,process){(function(){var assert=require("assert");var Stream=require("stream").Stream;var util=require("util");var UUID_REGEXP=/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;function _capitalize(str){return str.charAt(0).toUpperCase()+str.slice(1)}function _toss(name,expected,oper,arg,actual){throw new assert.AssertionError({message:util.format("%s (%s) is required",name,expected),actual:actual===undefined?typeof arg:actual(arg),expected:expected,operator:oper||"===",stackStartFunction:_toss.caller})}function _getClass(arg){return Object.prototype.toString.call(arg).slice(8,-1)}function noop(){}var types={bool:{check:function(arg){return typeof arg==="boolean"}},func:{check:function(arg){return typeof arg==="function"}},string:{check:function(arg){return typeof arg==="string"}},object:{check:function(arg){return typeof arg==="object"&&arg!==null}},number:{check:function(arg){return typeof arg==="number"&&!isNaN(arg)}},finite:{check:function(arg){return typeof arg==="number"&&!isNaN(arg)&&isFinite(arg)}},buffer:{check:function(arg){return Buffer.isBuffer(arg)},operator:"Buffer.isBuffer"},array:{check:function(arg){return Array.isArray(arg)},operator:"Array.isArray"},stream:{check:function(arg){return arg instanceof Stream},operator:"instanceof",actual:_getClass},date:{check:function(arg){return arg instanceof Date},operator:"instanceof",actual:_getClass},regexp:{check:function(arg){return arg instanceof RegExp},operator:"instanceof",actual:_getClass},uuid:{check:function(arg){return typeof arg==="string"&&UUID_REGEXP.test(arg)},operator:"isUUID"}};function _setExports(ndebug){var keys=Object.keys(types);var out;if(process.env.NODE_NDEBUG){out=noop}else{out=function(arg,msg){if(!arg){_toss(msg,"true",arg)}}}keys.forEach(function(k){if(ndebug){out[k]=noop;return}var type=types[k];out[k]=function(arg,msg){if(!type.check(arg)){_toss(msg,k,type.operator,arg,type.actual)}}});keys.forEach(function(k){var name="optional"+_capitalize(k);if(ndebug){out[name]=noop;return}var type=types[k];out[name]=function(arg,msg){if(arg===undefined||arg===null){return}if(!type.check(arg)){_toss(msg,k,type.operator,arg,type.actual)}}});keys.forEach(function(k){var name="arrayOf"+_capitalize(k);if(ndebug){out[name]=noop;return}var type=types[k];var expected="["+k+"]";out[name]=function(arg,msg){if(!Array.isArray(arg)){_toss(msg,expected,type.operator,arg,type.actual)}var i;for(i=0;i<arg.length;i++){if(!type.check(arg[i])){_toss(msg,expected,type.operator,arg,type.actual)}}}});keys.forEach(function(k){var name="optionalArrayOf"+_capitalize(k);if(ndebug){out[name]=noop;return}var type=types[k];var expected="["+k+"]";out[name]=function(arg,msg){if(arg===undefined||arg===null){return}if(!Array.isArray(arg)){_toss(msg,expected,type.operator,arg,type.actual)}var i;for(i=0;i<arg.length;i++){if(!type.check(arg[i])){_toss(msg,expected,type.operator,arg,type.actual)}}}});Object.keys(assert).forEach(function(k){if(k==="AssertionError"){out[k]=assert[k];return}if(ndebug){out[k]=noop;return}out[k]=assert[k]});out._setExports=_setExports;return out}module.exports=_setExports(process.env.NODE_NDEBUG)}).call(this)}).call(this,{isBuffer:require("../../browser-agent/node_modules/is-buffer/index.js")},require("_process"))},{"../../browser-agent/node_modules/is-buffer/index.js":146,_process:179,assert:16,stream:229,util:243}],388:[function(require,module,exports){var crypto=require("crypto"),parse=require("url").parse;var keys=["acl","location","logging","notification","partNumber","policy","requestPayment","torrent","uploadId","uploads","versionId","versioning","versions","website"];function authorization(options){return"AWS "+options.key+":"+sign(options)}module.exports=authorization;module.exports.authorization=authorization;function hmacSha1(options){return crypto.createHmac("sha1",options.secret).update(options.message).digest("base64")}module.exports.hmacSha1=hmacSha1;function sign(options){options.message=stringToSign(options);return hmacSha1(options)}module.exports.sign=sign;function signQuery(options){options.message=queryStringToSign(options);return hmacSha1(options)}module.exports.signQuery=signQuery;function stringToSign(options){var headers=options.amazonHeaders||"";if(headers)headers+="\n";var r=[options.verb,options.md5,options.contentType,options.date?options.date.toUTCString():"",headers+options.resource];return r.join("\n")}module.exports.stringToSign=stringToSign;function queryStringToSign(options){return"GET\n\n\n"+options.date+"\n"+options.resource}module.exports.queryStringToSign=queryStringToSign;function canonicalizeHeaders(headers){var buf=[],fields=Object.keys(headers);for(var i=0,len=fields.length;i<len;++i){var field=fields[i],val=headers[field],field=field.toLowerCase();if(0!==field.indexOf("x-amz"))continue;buf.push(field+":"+val)}return buf.sort().join("\n")}module.exports.canonicalizeHeaders=canonicalizeHeaders;function canonicalizeResource(resource){var url=parse(resource,true),path=url.pathname,buf=[];Object.keys(url.query).forEach(function(key){if(!~keys.indexOf(key))return;var val=""==url.query[key]?"":"="+encodeURIComponent(url.query[key]);buf.push(key+val)});return path+(buf.length?"?"+buf.sort().join("&"):"")}module.exports.canonicalizeResource=canonicalizeResource},{crypto:81,url:238}],389:[function(require,module,exports){(function(process,Buffer){(function(){var aws4=exports,url=require("url"),querystring=require("querystring"),crypto=require("crypto"),lru=require("./lru"),credentialsCache=lru(1e3);function hmac(key,string,encoding){return crypto.createHmac("sha256",key).update(string,"utf8").digest(encoding)}function hash(string,encoding){return crypto.createHash("sha256").update(string,"utf8").digest(encoding)}function encodeRfc3986(urlEncodedString){return urlEncodedString.replace(/[!'()*]/g,function(c){return"%"+c.charCodeAt(0).toString(16).toUpperCase()})}function encodeRfc3986Full(str){return encodeRfc3986(encodeURIComponent(str))}var HEADERS_TO_IGNORE={authorization:true,connection:true,"x-amzn-trace-id":true,"user-agent":true,expect:true,"presigned-expires":true,range:true};function RequestSigner(request,credentials){if(typeof request==="string")request=url.parse(request);var headers=request.headers=request.headers||{},hostParts=(!this.service||!this.region)&&this.matchHost(request.hostname||request.host||headers.Host||headers.host);this.request=request;this.credentials=credentials||this.defaultCredentials();this.service=request.service||hostParts[0]||"";this.region=request.region||hostParts[1]||"us-east-1";if(this.service==="email")this.service="ses";if(!request.method&&request.body)request.method="POST";if(!headers.Host&&!headers.host){headers.Host=request.hostname||request.host||this.createHost();if(request.port)headers.Host+=":"+request.port}if(!request.hostname&&!request.host)request.hostname=headers.Host||headers.host;this.isCodeCommitGit=this.service==="codecommit"&&request.method==="GIT"}RequestSigner.prototype.matchHost=function(host){var match=(host||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/);var hostParts=(match||[]).slice(1,3);if(hostParts[1]==="es")hostParts=hostParts.reverse();if(hostParts[1]=="s3"){hostParts[0]="s3";hostParts[1]="us-east-1"}else{for(var i=0;i<2;i++){if(/^s3-/.test(hostParts[i])){hostParts[1]=hostParts[i].slice(3);hostParts[0]="s3";break}}}return hostParts};RequestSigner.prototype.isSingleRegion=function(){if(["s3","sdb"].indexOf(this.service)>=0&&this.region==="us-east-1")return true;return["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)>=0};RequestSigner.prototype.createHost=function(){var region=this.isSingleRegion()?"":"."+this.region,subdomain=this.service==="ses"?"email":this.service;return subdomain+region+".amazonaws.com"};RequestSigner.prototype.prepareRequest=function(){this.parsePath();var request=this.request,headers=request.headers,query;if(request.signQuery){this.parsedPath.query=query=this.parsedPath.query||{};if(this.credentials.sessionToken)query["X-Amz-Security-Token"]=this.credentials.sessionToken;if(this.service==="s3"&&!query["X-Amz-Expires"])query["X-Amz-Expires"]=86400;if(query["X-Amz-Date"])this.datetime=query["X-Amz-Date"];else query["X-Amz-Date"]=this.getDateTime();query["X-Amz-Algorithm"]="AWS4-HMAC-SHA256";query["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString();query["X-Amz-SignedHeaders"]=this.signedHeaders()}else{if(!request.doNotModifyHeaders&&!this.isCodeCommitGit){if(request.body&&!headers["Content-Type"]&&!headers["content-type"])headers["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8";if(request.body&&!headers["Content-Length"]&&!headers["content-length"])headers["Content-Length"]=Buffer.byteLength(request.body);if(this.credentials.sessionToken&&!headers["X-Amz-Security-Token"]&&!headers["x-amz-security-token"])headers["X-Amz-Security-Token"]=this.credentials.sessionToken;if(this.service==="s3"&&!headers["X-Amz-Content-Sha256"]&&!headers["x-amz-content-sha256"])headers["X-Amz-Content-Sha256"]=hash(this.request.body||"","hex");if(headers["X-Amz-Date"]||headers["x-amz-date"])this.datetime=headers["X-Amz-Date"]||headers["x-amz-date"];else headers["X-Amz-Date"]=this.getDateTime()}delete headers.Authorization;delete headers.authorization}};RequestSigner.prototype.sign=function(){if(!this.parsedPath)this.prepareRequest();if(this.request.signQuery){this.parsedPath.query["X-Amz-Signature"]=this.signature()}else{this.request.headers.Authorization=this.authHeader()}this.request.path=this.formatPath();return this.request};RequestSigner.prototype.getDateTime=function(){if(!this.datetime){var headers=this.request.headers,date=new Date(headers.Date||headers.date||new Date);this.datetime=date.toISOString().replace(/[:\-]|\.\d{3}/g,"");if(this.isCodeCommitGit)this.datetime=this.datetime.slice(0,-1)}return this.datetime};RequestSigner.prototype.getDate=function(){return this.getDateTime().substr(0,8)};RequestSigner.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")};RequestSigner.prototype.signature=function(){var date=this.getDate(),cacheKey=[this.credentials.secretAccessKey,date,this.region,this.service].join(),kDate,kRegion,kService,kCredentials=credentialsCache.get(cacheKey);if(!kCredentials){kDate=hmac("AWS4"+this.credentials.secretAccessKey,date);kRegion=hmac(kDate,this.region);kService=hmac(kRegion,this.service);kCredentials=hmac(kService,"aws4_request");credentialsCache.set(cacheKey,kCredentials)}return hmac(kCredentials,this.stringToSign(),"hex")};RequestSigner.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),hash(this.canonicalString(),"hex")].join("\n")};RequestSigner.prototype.canonicalString=function(){if(!this.parsedPath)this.prepareRequest();var pathStr=this.parsedPath.path,query=this.parsedPath.query,headers=this.request.headers,queryStr="",normalizePath=this.service!=="s3",decodePath=this.service==="s3"||this.request.doNotEncodePath,decodeSlashesInPath=this.service==="s3",firstValOnly=this.service==="s3",bodyHash;if(this.service==="s3"&&this.request.signQuery){bodyHash="UNSIGNED-PAYLOAD"}else if(this.isCodeCommitGit){bodyHash=""}else{bodyHash=headers["X-Amz-Content-Sha256"]||headers["x-amz-content-sha256"]||hash(this.request.body||"","hex")}if(query){var reducedQuery=Object.keys(query).reduce(function(obj,key){if(!key)return obj;obj[encodeRfc3986Full(key)]=!Array.isArray(query[key])?query[key]:firstValOnly?query[key][0]:query[key];return obj},{});var encodedQueryPieces=[];Object.keys(reducedQuery).sort().forEach(function(key){if(!Array.isArray(reducedQuery[key])){encodedQueryPieces.push(key+"="+encodeRfc3986Full(reducedQuery[key]))}else{reducedQuery[key].map(encodeRfc3986Full).sort().forEach(function(val){encodedQueryPieces.push(key+"="+val)})}});queryStr=encodedQueryPieces.join("&")}if(pathStr!=="/"){if(normalizePath)pathStr=pathStr.replace(/\/{2,}/g,"/");pathStr=pathStr.split("/").reduce(function(path,piece){if(normalizePath&&piece===".."){path.pop()}else if(!normalizePath||piece!=="."){if(decodePath)piece=decodeURIComponent(piece.replace(/\+/g," "));path.push(encodeRfc3986Full(piece))}return path},[]).join("/");if(pathStr[0]!=="/")pathStr="/"+pathStr;if(decodeSlashesInPath)pathStr=pathStr.replace(/%2F/g,"/")}return[this.request.method||"GET",pathStr,queryStr,this.canonicalHeaders()+"\n",this.signedHeaders(),bodyHash].join("\n")};RequestSigner.prototype.canonicalHeaders=function(){var headers=this.request.headers;function trimAll(header){return header.toString().trim().replace(/\s+/g," ")}return Object.keys(headers).filter(function(key){return HEADERS_TO_IGNORE[key.toLowerCase()]==null}).sort(function(a,b){return a.toLowerCase()<b.toLowerCase()?-1:1}).map(function(key){return key.toLowerCase()+":"+trimAll(headers[key])}).join("\n")};RequestSigner.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map(function(key){return key.toLowerCase()}).filter(function(key){return HEADERS_TO_IGNORE[key]==null}).sort().join(";")};RequestSigner.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")};RequestSigner.prototype.defaultCredentials=function(){var env=process.env;return{accessKeyId:env.AWS_ACCESS_KEY_ID||env.AWS_ACCESS_KEY,secretAccessKey:env.AWS_SECRET_ACCESS_KEY||env.AWS_SECRET_KEY,sessionToken:env.AWS_SESSION_TOKEN}};RequestSigner.prototype.parsePath=function(){var path=this.request.path||"/";if(/[^0-9A-Za-z;,\/?:@&=+$\-_.!~*'()#%]/.test(path)){path=encodeURI(decodeURI(path))}var queryIx=path.indexOf("?"),query=null;if(queryIx>=0){query=querystring.parse(path.slice(queryIx+1));path=path.slice(0,queryIx)}this.parsedPath={path:path,query:query}};RequestSigner.prototype.formatPath=function(){var path=this.parsedPath.path,query=this.parsedPath.query;if(!query)return path;if(query[""]!=null)delete query[""];return path+"?"+encodeRfc3986(querystring.stringify(query))};aws4.RequestSigner=RequestSigner;aws4.sign=function(request,credentials){return new RequestSigner(request,credentials).sign()}}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{"./lru":390,_process:179,buffer:71,crypto:81,querystring:190,url:238}],390:[function(require,module,exports){module.exports=function(size){return new LruCache(size)};function LruCache(size){this.capacity=size|0;this.map=Object.create(null);this.list=new DoublyLinkedList}LruCache.prototype.get=function(key){var node=this.map[key];if(node==null)return undefined;this.used(node);return node.val};LruCache.prototype.set=function(key,val){var node=this.map[key];if(node!=null){node.val=val}else{if(!this.capacity)this.prune();if(!this.capacity)return false;node=new DoublyLinkedNode(key,val);this.map[key]=node;this.capacity--}this.used(node);return true};LruCache.prototype.used=function(node){this.list.moveToFront(node)};LruCache.prototype.prune=function(){var node=this.list.pop();if(node!=null){delete this.map[node.key];this.capacity++}};function DoublyLinkedList(){this.firstNode=null;this.lastNode=null}DoublyLinkedList.prototype.moveToFront=function(node){if(this.firstNode==node)return;this.remove(node);if(this.firstNode==null){this.firstNode=node;this.lastNode=node;node.prev=null;node.next=null}else{node.prev=null;node.next=this.firstNode;node.next.prev=node;this.firstNode=node}};DoublyLinkedList.prototype.pop=function(){var lastNode=this.lastNode;if(lastNode!=null){this.remove(lastNode)}return lastNode};DoublyLinkedList.prototype.remove=function(node){if(this.firstNode==node){this.firstNode=node.next}else if(node.prev!=null){node.prev.next=node.next}if(this.lastNode==node){this.lastNode=node.prev}else if(node.next!=null){node.next.prev=node.prev}};function DoublyLinkedNode(key,val){this.key=key;this.val=val;this.prev=null;this.next=null}},{}],391:[function(require,module,exports){"use strict";var crypto_hash_sha512=require("tweetnacl").lowlevel.crypto_hash;var BLF_J=0;var Blowfish=function(){
39
39
  this.S=[new Uint32Array([3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946]),new Uint32Array([1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055]),new Uint32Array([3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504]),new Uint32Array([976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462])];this.P=new Uint32Array([608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731])};function F(S,x8,i){return(S[0][x8[i+3]]+S[1][x8[i+2]]^S[2][x8[i+1]])+S[3][x8[i]]}Blowfish.prototype.encipher=function(x,x8){if(x8===undefined){x8=new Uint8Array(x.buffer);if(x.byteOffset!==0)x8=x8.subarray(x.byteOffset)}x[0]^=this.P[0];for(var i=1;i<16;i+=2){x[1]^=F(this.S,x8,0)^this.P[i];x[0]^=F(this.S,x8,4)^this.P[i+1]}var t=x[0];x[0]=x[1]^this.P[17];x[1]=t};Blowfish.prototype.decipher=function(x){var x8=new Uint8Array(x.buffer);if(x.byteOffset!==0)x8=x8.subarray(x.byteOffset);x[0]^=this.P[17];for(var i=16;i>0;i-=2){x[1]^=F(this.S,x8,0)^this.P[i];x[0]^=F(this.S,x8,4)^this.P[i-1]}var t=x[0];x[0]=x[1]^this.P[0];x[1]=t};function stream2word(data,databytes){var i,temp=0;for(i=0;i<4;i++,BLF_J++){if(BLF_J>=databytes)BLF_J=0;temp=temp<<8|data[BLF_J]}return temp}Blowfish.prototype.expand0state=function(key,keybytes){var d=new Uint32Array(2),i,k;var d8=new Uint8Array(d.buffer);for(i=0,BLF_J=0;i<18;i++){this.P[i]^=stream2word(key,keybytes)}BLF_J=0;for(i=0;i<18;i+=2){this.encipher(d,d8);this.P[i]=d[0];this.P[i+1]=d[1]}for(i=0;i<4;i++){for(k=0;k<256;k+=2){this.encipher(d,d8);this.S[i][k]=d[0];this.S[i][k+1]=d[1]}}};Blowfish.prototype.expandstate=function(data,databytes,key,keybytes){var d=new Uint32Array(2),i,k;for(i=0,BLF_J=0;i<18;i++){this.P[i]^=stream2word(key,keybytes)}for(i=0,BLF_J=0;i<18;i+=2){d[0]^=stream2word(data,databytes);d[1]^=stream2word(data,databytes);this.encipher(d);this.P[i]=d[0];this.P[i+1]=d[1]}for(i=0;i<4;i++){for(k=0;k<256;k+=2){d[0]^=stream2word(data,databytes);d[1]^=stream2word(data,databytes);this.encipher(d);this.S[i][k]=d[0];this.S[i][k+1]=d[1]}}BLF_J=0};Blowfish.prototype.enc=function(data,blocks){for(var i=0;i<blocks;i++){this.encipher(data.subarray(i*2))}};Blowfish.prototype.dec=function(data,blocks){for(var i=0;i<blocks;i++){this.decipher(data.subarray(i*2))}};var BCRYPT_BLOCKS=8,BCRYPT_HASHSIZE=32;function bcrypt_hash(sha2pass,sha2salt,out){var state=new Blowfish,cdata=new Uint32Array(BCRYPT_BLOCKS),i,ciphertext=new Uint8Array([79,120,121,99,104,114,111,109,97,116,105,99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109,105,116,101]);state.expandstate(sha2salt,64,sha2pass,64);for(i=0;i<64;i++){state.expand0state(sha2salt,64);state.expand0state(sha2pass,64)}for(i=0;i<BCRYPT_BLOCKS;i++)cdata[i]=stream2word(ciphertext,ciphertext.byteLength);for(i=0;i<64;i++)state.enc(cdata,cdata.byteLength/8);for(i=0;i<BCRYPT_BLOCKS;i++){out[4*i+3]=cdata[i]>>>24;out[4*i+2]=cdata[i]>>>16;out[4*i+1]=cdata[i]>>>8;out[4*i+0]=cdata[i]}}function bcrypt_pbkdf(pass,passlen,salt,saltlen,key,keylen,rounds){var sha2pass=new Uint8Array(64),sha2salt=new Uint8Array(64),out=new Uint8Array(BCRYPT_HASHSIZE),tmpout=new Uint8Array(BCRYPT_HASHSIZE),countsalt=new Uint8Array(saltlen+4),i,j,amt,stride,dest,count,origkeylen=keylen;if(rounds<1)return-1;if(passlen===0||saltlen===0||keylen===0||keylen>out.byteLength*out.byteLength||saltlen>1<<20)return-1;stride=Math.floor((keylen+out.byteLength-1)/out.byteLength);amt=Math.floor((keylen+stride-1)/stride);for(i=0;i<saltlen;i++)countsalt[i]=salt[i];crypto_hash_sha512(sha2pass,pass,passlen);for(count=1;keylen>0;count++){countsalt[saltlen+0]=count>>>24;countsalt[saltlen+1]=count>>>16;countsalt[saltlen+2]=count>>>8;countsalt[saltlen+3]=count;crypto_hash_sha512(sha2salt,countsalt,saltlen+4);bcrypt_hash(sha2pass,sha2salt,tmpout);for(i=out.byteLength;i--;)out[i]=tmpout[i];for(i=1;i<rounds;i++){crypto_hash_sha512(sha2salt,tmpout,tmpout.byteLength);bcrypt_hash(sha2pass,sha2salt,tmpout);for(j=0;j<out.byteLength;j++)out[j]^=tmpout[j]}amt=Math.min(amt,keylen);for(i=0;i<amt;i++){dest=i*stride+(count-1);if(dest>=origkeylen)break;key[dest]=out[i]}keylen-=i}return 0}module.exports={BLOCKS:BCRYPT_BLOCKS,HASHSIZE:BCRYPT_HASHSIZE,hash:bcrypt_hash,pbkdf:bcrypt_pbkdf}},{tweetnacl:504}],392:[function(require,module,exports){function Caseless(dict){this.dict=dict||{}}Caseless.prototype.set=function(name,value,clobber){if(typeof name==="object"){for(var i in name){this.set(i,name[i],value)}}else{if(typeof clobber==="undefined")clobber=true;var has=this.has(name);if(!clobber&&has)this.dict[has]=this.dict[has]+","+value;else this.dict[has||name]=value;return has}};Caseless.prototype.has=function(name){var keys=Object.keys(this.dict),name=name.toLowerCase();for(var i=0;i<keys.length;i++){if(keys[i].toLowerCase()===name)return keys[i]}return false};Caseless.prototype.get=function(name){name=name.toLowerCase();var result,_key;var headers=this.dict;Object.keys(headers).forEach(function(key){_key=key.toLowerCase();if(name===_key)result=headers[key]});return result};Caseless.prototype.swap=function(name){var has=this.has(name);if(has===name)return;if(!has)throw new Error('There is no header than matches "'+name+'"');this.dict[name]=this.dict[has];delete this.dict[has]};Caseless.prototype.del=function(name){var has=this.has(name);return delete this.dict[has||name]};module.exports=function(dict){return new Caseless(dict)};module.exports.httpify=function(resp,headers){var c=new Caseless(headers);resp.setHeader=function(key,value,clobber){if(typeof value==="undefined")return;return c.set(key,value,clobber)};resp.hasHeader=function(key){return c.has(key)};resp.getHeader=function(key){return c.get(key)};resp.removeHeader=function(key){return c.del(key)};resp.headers=c.dict;return c}},{}],393:[function(require,module,exports){(function(Buffer){(function(){var util=require("util");var Stream=require("stream").Stream;var DelayedStream=require("delayed-stream");module.exports=CombinedStream;function CombinedStream(){this.writable=false;this.readable=true;this.dataSize=0;this.maxDataSize=2*1024*1024;this.pauseStreams=true;this._released=false;this._streams=[];this._currentStream=null;this._insideLoop=false;this._pendingNext=false}util.inherits(CombinedStream,Stream);CombinedStream.create=function(options){var combinedStream=new this;options=options||{};for(var option in options){combinedStream[option]=options[option]}return combinedStream};CombinedStream.isStreamLike=function(stream){return typeof stream!=="function"&&typeof stream!=="string"&&typeof stream!=="boolean"&&typeof stream!=="number"&&!Buffer.isBuffer(stream)};CombinedStream.prototype.append=function(stream){var isStreamLike=CombinedStream.isStreamLike(stream);if(isStreamLike){if(!(stream instanceof DelayedStream)){var newStream=DelayedStream.create(stream,{maxDataSize:Infinity,pauseStream:this.pauseStreams});stream.on("data",this._checkDataSize.bind(this));stream=newStream}this._handleErrors(stream);if(this.pauseStreams){stream.pause()}}this._streams.push(stream);return this};CombinedStream.prototype.pipe=function(dest,options){Stream.prototype.pipe.call(this,dest,options);this.resume();return dest};CombinedStream.prototype._getNext=function(){this._currentStream=null;if(this._insideLoop){this._pendingNext=true;return}this._insideLoop=true;try{do{this._pendingNext=false;this._realGetNext()}while(this._pendingNext)}finally{this._insideLoop=false}};CombinedStream.prototype._realGetNext=function(){var stream=this._streams.shift();if(typeof stream=="undefined"){this.end();return}if(typeof stream!=="function"){this._pipeNext(stream);return}var getStream=stream;getStream(function(stream){var isStreamLike=CombinedStream.isStreamLike(stream);if(isStreamLike){stream.on("data",this._checkDataSize.bind(this));this._handleErrors(stream)}this._pipeNext(stream)}.bind(this))};CombinedStream.prototype._pipeNext=function(stream){this._currentStream=stream;var isStreamLike=CombinedStream.isStreamLike(stream);if(isStreamLike){stream.on("end",this._getNext.bind(this));stream.pipe(this,{end:false});return}var value=stream;this.write(value);this._getNext()};CombinedStream.prototype._handleErrors=function(stream){var self=this;stream.on("error",function(err){self._emitError(err)})};CombinedStream.prototype.write=function(data){this.emit("data",data)};CombinedStream.prototype.pause=function(){if(!this.pauseStreams){return}if(this.pauseStreams&&this._currentStream&&typeof this._currentStream.pause=="function")this._currentStream.pause();this.emit("pause")};CombinedStream.prototype.resume=function(){if(!this._released){this._released=true;this.writable=true;this._getNext()}if(this.pauseStreams&&this._currentStream&&typeof this._currentStream.resume=="function")this._currentStream.resume();this.emit("resume")};CombinedStream.prototype.end=function(){this._reset();this.emit("end")};CombinedStream.prototype.destroy=function(){this._reset();this.emit("close")};CombinedStream.prototype._reset=function(){this.writable=false;this._streams=[];this._currentStream=null};CombinedStream.prototype._checkDataSize=function(){this._updateDataSize();if(this.dataSize<=this.maxDataSize){return}var message="DelayedStream#maxDataSize of "+this.maxDataSize+" bytes exceeded.";this._emitError(new Error(message))};CombinedStream.prototype._updateDataSize=function(){this.dataSize=0;var self=this;this._streams.forEach(function(stream){if(!stream.dataSize){return}self.dataSize+=stream.dataSize});if(this._currentStream&&this._currentStream.dataSize){this.dataSize+=this._currentStream.dataSize}};CombinedStream.prototype._emitError=function(err){this._reset();this.emit("error",err)}}).call(this)}).call(this,{isBuffer:require("../../../browser-agent/node_modules/is-buffer/index.js")})},{"../../../browser-agent/node_modules/is-buffer/index.js":146,"delayed-stream":395,stream:229,util:243}],394:[function(require,module,exports){(function(Buffer){(function(){function isArray(arg){if(Array.isArray){return Array.isArray(arg)}return objectToString(arg)==="[object Array]"}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=Buffer.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this)}).call(this,{isBuffer:require("../../../browser-agent/node_modules/is-buffer/index.js")})},{"../../../browser-agent/node_modules/is-buffer/index.js":146}],395:[function(require,module,exports){var Stream=require("stream").Stream;var util=require("util");module.exports=DelayedStream;function DelayedStream(){this.source=null;this.dataSize=0;this.maxDataSize=1024*1024;this.pauseStream=true;this._maxDataSizeExceeded=false;this._released=false;this._bufferedEvents=[]}util.inherits(DelayedStream,Stream);DelayedStream.create=function(source,options){var delayedStream=new this;options=options||{};for(var option in options){delayedStream[option]=options[option]}delayedStream.source=source;var realEmit=source.emit;source.emit=function(){delayedStream._handleEmit(arguments);return realEmit.apply(source,arguments)};source.on("error",function(){});if(delayedStream.pauseStream){source.pause()}return delayedStream};Object.defineProperty(DelayedStream.prototype,"readable",{configurable:true,enumerable:true,get:function(){return this.source.readable}});DelayedStream.prototype.setEncoding=function(){return this.source.setEncoding.apply(this.source,arguments)};DelayedStream.prototype.resume=function(){if(!this._released){this.release()}this.source.resume()};DelayedStream.prototype.pause=function(){this.source.pause()};DelayedStream.prototype.release=function(){this._released=true;this._bufferedEvents.forEach(function(args){this.emit.apply(this,args)}.bind(this));this._bufferedEvents=[]};DelayedStream.prototype.pipe=function(){var r=Stream.prototype.pipe.apply(this,arguments);this.resume();return r};DelayedStream.prototype._handleEmit=function(args){if(this._released){this.emit.apply(this,args);return}if(args[0]==="data"){this.dataSize+=args[1].length;this._checkIfMaxDataSizeExceeded()}this._bufferedEvents.push(args)};DelayedStream.prototype._checkIfMaxDataSizeExceeded=function(){if(this._maxDataSizeExceeded){return}if(this.dataSize<=this.maxDataSize){return}this._maxDataSizeExceeded=true;var message="DelayedStream#maxDataSize of "+this.maxDataSize+" bytes exceeded.";this.emit("error",new Error(message))}},{stream:229,util:243}],396:[function(require,module,exports){var crypto=require("crypto");var BigInteger=require("jsbn").BigInteger;var ECPointFp=require("./lib/ec.js").ECPointFp;var Buffer=require("safer-buffer").Buffer;exports.ECCurves=require("./lib/sec.js");function unstupid(hex,len){return hex.length>=len?hex:unstupid("0"+hex,len)}exports.ECKey=function(curve,key,isPublic){var priv;var c=curve();var n=c.getN();var bytes=Math.floor(n.bitLength()/8);if(key){if(isPublic){var curve=c.getCurve();this.P=curve.decodePointHex(key.toString("hex"))}else{if(key.length!=bytes)return false;priv=new BigInteger(key.toString("hex"),16)}}else{var n1=n.subtract(BigInteger.ONE);var r=new BigInteger(crypto.randomBytes(n.bitLength()));priv=r.mod(n1).add(BigInteger.ONE);this.P=c.getG().multiply(priv)}if(this.P){this.PublicKey=Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex")}if(priv){this.PrivateKey=Buffer.from(unstupid(priv.toString(16),bytes*2),"hex");this.deriveSharedSecret=function(key){if(!key||!key.P)return false;var S=key.P.multiply(priv);return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex")}}}},{"./lib/ec.js":397,"./lib/sec.js":398,crypto:81,jsbn:433,"safer-buffer":470}],397:[function(require,module,exports){var BigInteger=require("jsbn").BigInteger;var Barrett=BigInteger.prototype.Barrett;function ECFieldElementFp(q,x){this.x=x;this.q=q}function feFpEquals(other){if(other==this)return true;return this.q.equals(other.q)&&this.x.equals(other.x)}function feFpToBigInteger(){return this.x}function feFpNegate(){return new ECFieldElementFp(this.q,this.x.negate().mod(this.q))}function feFpAdd(b){return new ECFieldElementFp(this.q,this.x.add(b.toBigInteger()).mod(this.q))}function feFpSubtract(b){return new ECFieldElementFp(this.q,this.x.subtract(b.toBigInteger()).mod(this.q))}function feFpMultiply(b){return new ECFieldElementFp(this.q,this.x.multiply(b.toBigInteger()).mod(this.q))}function feFpSquare(){return new ECFieldElementFp(this.q,this.x.square().mod(this.q))}function feFpDivide(b){return new ECFieldElementFp(this.q,this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q))}ECFieldElementFp.prototype.equals=feFpEquals;ECFieldElementFp.prototype.toBigInteger=feFpToBigInteger;ECFieldElementFp.prototype.negate=feFpNegate;ECFieldElementFp.prototype.add=feFpAdd;ECFieldElementFp.prototype.subtract=feFpSubtract;ECFieldElementFp.prototype.multiply=feFpMultiply;ECFieldElementFp.prototype.square=feFpSquare;ECFieldElementFp.prototype.divide=feFpDivide;function ECPointFp(curve,x,y,z){this.curve=curve;this.x=x;this.y=y;if(z==null){this.z=BigInteger.ONE}else{this.z=z}this.zinv=null}function pointFpGetX(){if(this.zinv==null){this.zinv=this.z.modInverse(this.curve.q)}var r=this.x.toBigInteger().multiply(this.zinv);this.curve.reduce(r);return this.curve.fromBigInteger(r)}function pointFpGetY(){if(this.zinv==null){this.zinv=this.z.modInverse(this.curve.q)}var r=this.y.toBigInteger().multiply(this.zinv);this.curve.reduce(r);return this.curve.fromBigInteger(r)}function pointFpEquals(other){if(other==this)return true;if(this.isInfinity())return other.isInfinity();if(other.isInfinity())return this.isInfinity();var u,v;u=other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q);if(!u.equals(BigInteger.ZERO))return false;v=other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q);return v.equals(BigInteger.ZERO)}function pointFpIsInfinity(){if(this.x==null&&this.y==null)return true;return this.z.equals(BigInteger.ZERO)&&!this.y.toBigInteger().equals(BigInteger.ZERO)}function pointFpNegate(){return new ECPointFp(this.curve,this.x,this.y.negate(),this.z)}function pointFpAdd(b){if(this.isInfinity())return b;if(b.isInfinity())return this;var u=b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q);var v=b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q);if(BigInteger.ZERO.equals(v)){if(BigInteger.ZERO.equals(u)){return this.twice()}return this.curve.getInfinity()}var THREE=new BigInteger("3");var x1=this.x.toBigInteger();var y1=this.y.toBigInteger();var x2=b.x.toBigInteger();var y2=b.y.toBigInteger();var v2=v.square();var v3=v2.multiply(v);var x1v2=x1.multiply(v2);var zu2=u.square().multiply(this.z);var x3=zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q);var y3=x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q);var z3=v3.multiply(this.z).multiply(b.z).mod(this.curve.q);return new ECPointFp(this.curve,this.curve.fromBigInteger(x3),this.curve.fromBigInteger(y3),z3)}function pointFpTwice(){if(this.isInfinity())return this;if(this.y.toBigInteger().signum()==0)return this.curve.getInfinity();var THREE=new BigInteger("3");var x1=this.x.toBigInteger();var y1=this.y.toBigInteger();var y1z1=y1.multiply(this.z);var y1sqz1=y1z1.multiply(y1).mod(this.curve.q);var a=this.curve.a.toBigInteger();var w=x1.square().multiply(THREE);if(!BigInteger.ZERO.equals(a)){w=w.add(this.z.square().multiply(a))}w=w.mod(this.curve.q);var x3=w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q);var y3=w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q);var z3=y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q);return new ECPointFp(this.curve,this.curve.fromBigInteger(x3),this.curve.fromBigInteger(y3),z3)}function pointFpMultiply(k){if(this.isInfinity())return this;if(k.signum()==0)return this.curve.getInfinity();var e=k;var h=e.multiply(new BigInteger("3"));var neg=this.negate();var R=this;var i;for(i=h.bitLength()-2;i>0;--i){R=R.twice();var hBit=h.testBit(i);var eBit=e.testBit(i);if(hBit!=eBit){R=R.add(hBit?this:neg)}}return R}function pointFpMultiplyTwo(j,x,k){var i;if(j.bitLength()>k.bitLength())i=j.bitLength()-1;else i=k.bitLength()-1;var R=this.curve.getInfinity();var both=this.add(x);while(i>=0){R=R.twice();if(j.testBit(i)){if(k.testBit(i)){R=R.add(both)}else{R=R.add(this)}}else{if(k.testBit(i)){R=R.add(x)}}--i}return R}ECPointFp.prototype.getX=pointFpGetX;ECPointFp.prototype.getY=pointFpGetY;ECPointFp.prototype.equals=pointFpEquals;ECPointFp.prototype.isInfinity=pointFpIsInfinity;ECPointFp.prototype.negate=pointFpNegate;ECPointFp.prototype.add=pointFpAdd;ECPointFp.prototype.twice=pointFpTwice;ECPointFp.prototype.multiply=pointFpMultiply;ECPointFp.prototype.multiplyTwo=pointFpMultiplyTwo;function ECCurveFp(q,a,b){this.q=q;this.a=this.fromBigInteger(a);this.b=this.fromBigInteger(b);this.infinity=new ECPointFp(this,null,null);this.reducer=new Barrett(this.q)}function curveFpGetQ(){return this.q}function curveFpGetA(){return this.a}function curveFpGetB(){return this.b}function curveFpEquals(other){if(other==this)return true;return this.q.equals(other.q)&&this.a.equals(other.a)&&this.b.equals(other.b)}function curveFpGetInfinity(){return this.infinity}function curveFpFromBigInteger(x){return new ECFieldElementFp(this.q,x)}function curveReduce(x){this.reducer.reduce(x)}function curveFpDecodePointHex(s){switch(parseInt(s.substr(0,2),16)){case 0:return this.infinity;case 2:case 3:return null;case 4:case 6:case 7:var len=(s.length-2)/2;var xHex=s.substr(2,len);var yHex=s.substr(len+2,len);return new ECPointFp(this,this.fromBigInteger(new BigInteger(xHex,16)),this.fromBigInteger(new BigInteger(yHex,16)));default:return null}}function curveFpEncodePointHex(p){
40
40
  if(p.isInfinity())return"00";var xHex=p.getX().toBigInteger().toString(16);var yHex=p.getY().toBigInteger().toString(16);var oLen=this.getQ().toString(16).length;if(oLen%2!=0)oLen++;while(xHex.length<oLen){xHex="0"+xHex}while(yHex.length<oLen){yHex="0"+yHex}return"04"+xHex+yHex}ECCurveFp.prototype.getQ=curveFpGetQ;ECCurveFp.prototype.getA=curveFpGetA;ECCurveFp.prototype.getB=curveFpGetB;ECCurveFp.prototype.equals=curveFpEquals;ECCurveFp.prototype.getInfinity=curveFpGetInfinity;ECCurveFp.prototype.fromBigInteger=curveFpFromBigInteger;ECCurveFp.prototype.reduce=curveReduce;ECCurveFp.prototype.encodePointHex=curveFpEncodePointHex;ECCurveFp.prototype.decodePointHex=function(s){var yIsEven;switch(parseInt(s.substr(0,2),16)){case 0:return this.infinity;case 2:yIsEven=false;case 3:if(yIsEven==undefined)yIsEven=true;var len=s.length-2;var xHex=s.substr(2,len);var x=this.fromBigInteger(new BigInteger(xHex,16));var alpha=x.multiply(x.square().add(this.getA())).add(this.getB());var beta=alpha.sqrt();if(beta==null)throw"Invalid point compression";var betaValue=beta.toBigInteger();if(betaValue.testBit(0)!=yIsEven){beta=this.fromBigInteger(this.getQ().subtract(betaValue))}return new ECPointFp(this,x,beta);case 4:case 6:case 7:var len=(s.length-2)/2;var xHex=s.substr(2,len);var yHex=s.substr(len+2,len);return new ECPointFp(this,this.fromBigInteger(new BigInteger(xHex,16)),this.fromBigInteger(new BigInteger(yHex,16)));default:return null}};ECCurveFp.prototype.encodeCompressedPointHex=function(p){if(p.isInfinity())return"00";var xHex=p.getX().toBigInteger().toString(16);var oLen=this.getQ().toString(16).length;if(oLen%2!=0)oLen++;while(xHex.length<oLen)xHex="0"+xHex;var yPrefix;if(p.getY().toBigInteger().isEven())yPrefix="02";else yPrefix="03";return yPrefix+xHex};ECFieldElementFp.prototype.getR=function(){if(this.r!=undefined)return this.r;this.r=null;var bitLength=this.q.bitLength();if(bitLength>128){var firstWord=this.q.shiftRight(bitLength-64);if(firstWord.intValue()==-1){this.r=BigInteger.ONE.shiftLeft(bitLength).subtract(this.q)}}return this.r};ECFieldElementFp.prototype.modMult=function(x1,x2){return this.modReduce(x1.multiply(x2))};ECFieldElementFp.prototype.modReduce=function(x){if(this.getR()!=null){var qLen=q.bitLength();while(x.bitLength()>qLen+1){var u=x.shiftRight(qLen);var v=x.subtract(u.shiftLeft(qLen));if(!this.getR().equals(BigInteger.ONE)){u=u.multiply(this.getR())}x=u.add(v)}while(x.compareTo(q)>=0){x=x.subtract(q)}}else{x=x.mod(q)}return x};ECFieldElementFp.prototype.sqrt=function(){if(!this.q.testBit(0))throw"unsupported";if(this.q.testBit(1)){var z=new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q));return z.square().equals(this)?z:null}var qMinusOne=this.q.subtract(BigInteger.ONE);var legendreExponent=qMinusOne.shiftRight(1);if(!this.x.modPow(legendreExponent,this.q).equals(BigInteger.ONE)){return null}var u=qMinusOne.shiftRight(2);var k=u.shiftLeft(1).add(BigInteger.ONE);var Q=this.x;var fourQ=modDouble(modDouble(Q));var U,V;do{var P;do{P=new BigInteger(this.q.bitLength(),new SecureRandom)}while(P.compareTo(this.q)>=0||!P.multiply(P).subtract(fourQ).modPow(legendreExponent,this.q).equals(qMinusOne));var result=this.lucasSequence(P,Q,k);U=result[0];V=result[1];if(this.modMult(V,V).equals(fourQ)){if(V.testBit(0)){V=V.add(q)}V=V.shiftRight(1);return new ECFieldElementFp(q,V)}}while(U.equals(BigInteger.ONE)||U.equals(qMinusOne));return null};ECFieldElementFp.prototype.lucasSequence=function(P,Q,k){var n=k.bitLength();var s=k.getLowestSetBit();var Uh=BigInteger.ONE;var Vl=BigInteger.TWO;var Vh=P;var Ql=BigInteger.ONE;var Qh=BigInteger.ONE;for(var j=n-1;j>=s+1;--j){Ql=this.modMult(Ql,Qh);if(k.testBit(j)){Qh=this.modMult(Ql,Q);Uh=this.modMult(Uh,Vh);Vl=this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));Vh=this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1)))}else{Qh=Ql;Uh=this.modReduce(Uh.multiply(Vl).subtract(Ql));Vh=this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));Vl=this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)))}}Ql=this.modMult(Ql,Qh);Qh=this.modMult(Ql,Q);Uh=this.modReduce(Uh.multiply(Vl).subtract(Ql));Vl=this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));Ql=this.modMult(Ql,Qh);for(var j=1;j<=s;++j){Uh=this.modMult(Uh,Vl);Vl=this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));Ql=this.modMult(Ql,Ql)}return[Uh,Vl]};var exports={ECCurveFp:ECCurveFp,ECPointFp:ECPointFp,ECFieldElementFp:ECFieldElementFp};module.exports=exports},{jsbn:433}],398:[function(require,module,exports){var BigInteger=require("jsbn").BigInteger;var ECCurveFp=require("./ec.js").ECCurveFp;function X9ECParameters(curve,g,n,h){this.curve=curve;this.g=g;this.n=n;this.h=h}function x9getCurve(){return this.curve}function x9getG(){return this.g}function x9getN(){return this.n}function x9getH(){return this.h}X9ECParameters.prototype.getCurve=x9getCurve;X9ECParameters.prototype.getG=x9getG;X9ECParameters.prototype.getN=x9getN;X9ECParameters.prototype.getH=x9getH;function fromHex(s){return new BigInteger(s,16)}function secp128r1(){var p=fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");var a=fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC");var b=fromHex("E87579C11079F43DD824993C2CEE5ED3");var n=fromHex("FFFFFFFE0000000075A30D1B9038A115");var h=BigInteger.ONE;var curve=new ECCurveFp(p,a,b);var G=curve.decodePointHex("04"+"161FF7528B899B2D0C28607CA52C5B86"+"CF5AC8395BAFEB13C02DA292DDED7A83");return new X9ECParameters(curve,G,n,h)}function secp160k1(){var p=fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");var a=BigInteger.ZERO;var b=fromHex("7");var n=fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3");var h=BigInteger.ONE;var curve=new ECCurveFp(p,a,b);var G=curve.decodePointHex("04"+"3B4C382CE37AA192A4019E763036F4F5DD4D7EBB"+"938CF935318FDCED6BC28286531733C3F03C4FEE");return new X9ECParameters(curve,G,n,h)}function secp160r1(){var p=fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF");var a=fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC");var b=fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45");var n=fromHex("0100000000000000000001F4C8F927AED3CA752257");var h=BigInteger.ONE;var curve=new ECCurveFp(p,a,b);var G=curve.decodePointHex("04"+"4A96B5688EF573284664698968C38BB913CBFC82"+"23A628553168947D59DCC912042351377AC5FB32");return new X9ECParameters(curve,G,n,h)}function secp192k1(){var p=fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37");var a=BigInteger.ZERO;var b=fromHex("3");var n=fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D");var h=BigInteger.ONE;var curve=new ECCurveFp(p,a,b);var G=curve.decodePointHex("04"+"DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D"+"9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D");return new X9ECParameters(curve,G,n,h)}function secp192r1(){var p=fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF");var a=fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC");var b=fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1");var n=fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831");var h=BigInteger.ONE;var curve=new ECCurveFp(p,a,b);var G=curve.decodePointHex("04"+"188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"+"07192B95FFC8DA78631011ED6B24CDD573F977A11E794811");return new X9ECParameters(curve,G,n,h)}function secp224r1(){var p=fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001");var a=fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE");var b=fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4");var n=fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D");var h=BigInteger.ONE;var curve=new ECCurveFp(p,a,b);var G=curve.decodePointHex("04"+"B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21"+"BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34");return new X9ECParameters(curve,G,n,h)}function secp256r1(){var p=fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");var a=fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");var b=fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B");var n=fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");var h=BigInteger.ONE;var curve=new ECCurveFp(p,a,b);var G=curve.decodePointHex("04"+"6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"+"4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5");return new X9ECParameters(curve,G,n,h)}function getSECCurveByName(name){if(name=="secp128r1")return secp128r1();if(name=="secp160k1")return secp160k1();if(name=="secp160r1")return secp160r1();if(name=="secp192k1")return secp192k1();if(name=="secp192r1")return secp192r1();if(name=="secp224r1")return secp224r1();if(name=="secp256r1")return secp256r1();return null}module.exports={secp128r1:secp128r1,secp160k1:secp160k1,secp160r1:secp160r1,secp192k1:secp192k1,secp192r1:secp192r1,secp224r1:secp224r1,secp256r1:secp256r1}},{"./ec.js":397,jsbn:433}],399:[function(require,module,exports){"use strict";var hasOwn=Object.prototype.hasOwnProperty;var toStr=Object.prototype.toString;var defineProperty=Object.defineProperty;var gOPD=Object.getOwnPropertyDescriptor;var isArray=function isArray(arr){if(typeof Array.isArray==="function"){return Array.isArray(arr)}return toStr.call(arr)==="[object Array]"};var isPlainObject=function isPlainObject(obj){if(!obj||toStr.call(obj)!=="[object Object]"){return false}var hasOwnConstructor=hasOwn.call(obj,"constructor");var hasIsPrototypeOf=obj.constructor&&obj.constructor.prototype&&hasOwn.call(obj.constructor.prototype,"isPrototypeOf");if(obj.constructor&&!hasOwnConstructor&&!hasIsPrototypeOf){return false}var key;for(key in obj){}return typeof key==="undefined"||hasOwn.call(obj,key)};var setProperty=function setProperty(target,options){if(defineProperty&&options.name==="__proto__"){defineProperty(target,options.name,{enumerable:true,configurable:true,value:options.newValue,writable:true})}else{target[options.name]=options.newValue}};var getProperty=function getProperty(obj,name){if(name==="__proto__"){if(!hasOwn.call(obj,name)){return void 0}else if(gOPD){return gOPD(obj,name).value}}return obj[name]};module.exports=function extend(){var options,name,src,copy,copyIsArray,clone;var target=arguments[0];var i=1;var length=arguments.length;var deep=false;if(typeof target==="boolean"){deep=target;target=arguments[1]||{};i=2}if(target==null||typeof target!=="object"&&typeof target!=="function"){target={}}for(;i<length;++i){options=arguments[i];if(options!=null){for(name in options){src=getProperty(target,name);copy=getProperty(options,name);if(target!==copy){if(deep&&copy&&(isPlainObject(copy)||(copyIsArray=isArray(copy)))){if(copyIsArray){copyIsArray=false;clone=src&&isArray(src)?src:[]}else{clone=src&&isPlainObject(src)?src:{}}setProperty(target,{name:name,newValue:extend(deep,clone,copy)})}else if(typeof copy!=="undefined"){setProperty(target,{name:name,newValue:copy})}}}}}return target}},{}],400:[function(require,module,exports){(function(process){(function(){var mod_assert=require("assert");var mod_util=require("util");exports.sprintf=jsSprintf;exports.printf=jsPrintf;exports.fprintf=jsFprintf;function jsSprintf(fmt){var regex=["([^%]*)","%","(['\\-+ #0]*?)","([1-9]\\d*)?","(\\.([1-9]\\d*))?","[lhjztL]*?","([diouxXfFeEgGaAcCsSp%jr])"].join("");var re=new RegExp(regex);var args=Array.prototype.slice.call(arguments,1);var flags,width,precision,conversion;var left,pad,sign,arg,match;var ret="";var argn=1;mod_assert.equal("string",typeof fmt);while((match=re.exec(fmt))!==null){ret+=match[1];fmt=fmt.substring(match[0].length);flags=match[2]||"";width=match[3]||0;precision=match[4]||"";conversion=match[6];left=false;sign=false;pad=" ";if(conversion=="%"){ret+="%";continue}if(args.length===0)throw new Error("too few args to sprintf");arg=args.shift();argn++;if(flags.match(/[\' #]/))throw new Error("unsupported flags: "+flags);if(precision.length>0)throw new Error("non-zero precision not supported");if(flags.match(/-/))left=true;if(flags.match(/0/))pad="0";if(flags.match(/\+/))sign=true;switch(conversion){case"s":if(arg===undefined||arg===null)throw new Error("argument "+argn+": attempted to print undefined or null "+"as a string");ret+=doPad(pad,width,left,arg.toString());break;case"d":arg=Math.floor(arg);case"f":sign=sign&&arg>0?"+":"";ret+=sign+doPad(pad,width,left,arg.toString());break;case"x":ret+=doPad(pad,width,left,arg.toString(16));break;case"j":if(width===0)width=10;ret+=mod_util.inspect(arg,false,width);break;case"r":ret+=dumpException(arg);break;default:throw new Error("unsupported conversion: "+conversion)}}ret+=fmt;return ret}function jsPrintf(){var args=Array.prototype.slice.call(arguments);args.unshift(process.stdout);jsFprintf.apply(null,args)}function jsFprintf(stream){var args=Array.prototype.slice.call(arguments,1);return stream.write(jsSprintf.apply(this,args))}function doPad(chr,width,left,str){var ret=str;while(ret.length<width){if(left)ret+=chr;else ret=chr+ret}return ret}function dumpException(ex){var ret;if(!(ex instanceof Error))throw new Error(jsSprintf("invalid type for %%r: %j",ex));ret="EXCEPTION: "+ex.constructor.name+": "+ex.stack;if(ex.cause&&typeof ex.cause==="function"){var cex=ex.cause();if(cex){ret+="\nCaused by: "+dumpException(cex)}}return ret}}).call(this)}).call(this,require("_process"))},{_process:179,assert:16,util:243}],401:[function(require,module,exports){"use strict";module.exports=function equal(a,b){if(a===b)return true;if(a&&b&&typeof a=="object"&&typeof b=="object"){if(a.constructor!==b.constructor)return false;var length,i,keys;if(Array.isArray(a)){length=a.length;if(length!=b.length)return false;for(i=length;i--!==0;)if(!equal(a[i],b[i]))return false;return true}if(a.constructor===RegExp)return a.source===b.source&&a.flags===b.flags;if(a.valueOf!==Object.prototype.valueOf)return a.valueOf()===b.valueOf();if(a.toString!==Object.prototype.toString)return a.toString()===b.toString();keys=Object.keys(a);length=keys.length;if(length!==Object.keys(b).length)return false;for(i=length;i--!==0;)if(!Object.prototype.hasOwnProperty.call(b,keys[i]))return false;for(i=length;i--!==0;){var key=keys[i];if(!equal(a[key],b[key]))return false}return true}return a!==a&&b!==b}},{}],402:[function(require,module,exports){"use strict";module.exports=function(data,opts){if(!opts)opts={};if(typeof opts==="function")opts={cmp:opts};var cycles=typeof opts.cycles==="boolean"?opts.cycles:false;var cmp=opts.cmp&&function(f){return function(node){return function(a,b){var aobj={key:a,value:node[a]};var bobj={key:b,value:node[b]};return f(aobj,bobj)}}}(opts.cmp);var seen=[];return function stringify(node){if(node&&node.toJSON&&typeof node.toJSON==="function"){node=node.toJSON()}if(node===undefined)return;if(typeof node=="number")return isFinite(node)?""+node:"null";if(typeof node!=="object")return JSON.stringify(node);var i,out;if(Array.isArray(node)){out="[";for(i=0;i<node.length;i++){if(i)out+=",";out+=stringify(node[i])||"null"}return out+"]"}if(node===null)return"null";if(seen.indexOf(node)!==-1){if(cycles)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var seenIndex=seen.push(node)-1;var keys=Object.keys(node).sort(cmp&&cmp(node));out="";for(i=0;i<keys.length;i++){var key=keys[i];var value=stringify(node[key]);if(!value)continue;if(out)out+=",";out+=JSON.stringify(key)+":"+value}seen.splice(seenIndex,1);return"{"+out+"}"}(data)}},{}],403:[function(require,module,exports){module.exports=ForeverAgent;ForeverAgent.SSL=ForeverAgentSSL;var util=require("util"),Agent=require("http").Agent,net=require("net"),tls=require("tls"),AgentSSL=require("https").Agent;function getConnectionName(host,port){var name="";if(typeof host==="string"){name=host+":"+port}else{name=host.host+":"+host.port+":"+(host.localAddress?host.localAddress+":":":")}return name}function ForeverAgent(options){var self=this;self.options=options||{};self.requests={};self.sockets={};self.freeSockets={};self.maxSockets=self.options.maxSockets||Agent.defaultMaxSockets;self.minSockets=self.options.minSockets||ForeverAgent.defaultMinSockets;self.on("free",function(socket,host,port){var name=getConnectionName(host,port);if(self.requests[name]&&self.requests[name].length){self.requests[name].shift().onSocket(socket)}else if(self.sockets[name].length<self.minSockets){if(!self.freeSockets[name])self.freeSockets[name]=[];self.freeSockets[name].push(socket);var onIdleError=function(){socket.destroy()};socket._onIdleError=onIdleError;socket.on("error",onIdleError)}else{socket.destroy()}})}util.inherits(ForeverAgent,Agent);ForeverAgent.defaultMinSockets=5;ForeverAgent.prototype.createConnection=net.createConnection;ForeverAgent.prototype.addRequestNoreuse=Agent.prototype.addRequest;ForeverAgent.prototype.addRequest=function(req,host,port){var name=getConnectionName(host,port);if(typeof host!=="string"){var options=host;port=options.port;host=options.host}if(this.freeSockets[name]&&this.freeSockets[name].length>0&&!req.useChunkedEncodingByDefault){var idleSocket=this.freeSockets[name].pop();idleSocket.removeListener("error",idleSocket._onIdleError);delete idleSocket._onIdleError;req._reusedSocket=true;req.onSocket(idleSocket)}else{this.addRequestNoreuse(req,host,port)}};ForeverAgent.prototype.removeSocket=function(s,name,host,port){if(this.sockets[name]){var index=this.sockets[name].indexOf(s);if(index!==-1){this.sockets[name].splice(index,1)}}else if(this.sockets[name]&&this.sockets[name].length===0){delete this.sockets[name];delete this.requests[name]}if(this.freeSockets[name]){var index=this.freeSockets[name].indexOf(s);if(index!==-1){this.freeSockets[name].splice(index,1);if(this.freeSockets[name].length===0){delete this.freeSockets[name]}}}if(this.requests[name]&&this.requests[name].length){this.createSocket(name,host,port).emit("free")}};function ForeverAgentSSL(options){ForeverAgent.call(this,options)}util.inherits(ForeverAgentSSL,ForeverAgent);ForeverAgentSSL.prototype.createConnection=createConnectionSSL;ForeverAgentSSL.prototype.addRequestNoreuse=AgentSSL.prototype.addRequest;function createConnectionSSL(port,host,options){if(typeof port==="object"){options=port}else if(typeof host==="object"){options=host}else if(typeof options==="object"){options=options}else{options={}}if(typeof port==="number"){options.port=port}if(typeof host==="string"){options.host=host}return tls.connect(options)}},{http:230,https:142,net:69,tls:69,util:243}],404:[function(require,module,exports){module.exports=typeof self=="object"?self.FormData:window.FormData},{}],405:[function(require,module,exports){module.exports={$id:"afterRequest.json#",$schema:"http://json-schema.org/draft-06/schema#",type:"object",optional:true,required:["lastAccess","eTag","hitCount"],properties:{expires:{type:"string",pattern:"^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"},lastAccess:{type:"string",pattern:"^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"},eTag:{type:"string"},hitCount:{type:"integer"},comment:{type:"string"}}}},{}],406:[function(require,module,exports){module.exports={$id:"beforeRequest.json#",$schema:"http://json-schema.org/draft-06/schema#",type:"object",optional:true,required:["lastAccess","eTag","hitCount"],properties:{expires:{type:"string",pattern:"^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"},lastAccess:{type:"string",pattern:"^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"},eTag:{type:"string"},hitCount:{type:"integer"},comment:{type:"string"}}}},{}],407:[function(require,module,exports){module.exports={$id:"browser.json#",$schema:"http://json-schema.org/draft-06/schema#",type:"object",required:["name","version"],properties:{name:{type:"string"},version:{type:"string"},comment:{type:"string"}}}},{}],408:[function(require,module,exports){module.exports={$id:"cache.json#",$schema:"http://json-schema.org/draft-06/schema#",properties:{beforeRequest:{oneOf:[{type:"null"},{$ref:"beforeRequest.json#"}]},afterRequest:{oneOf:[{type:"null"},{$ref:"afterRequest.json#"}]},comment:{type:"string"}}}},{}],409:[function(require,module,exports){module.exports={$id:"content.json#",$schema:"http://json-schema.org/draft-06/schema#",type:"object",required:["size","mimeType"],properties:{size:{type:"integer"},compression:{type:"integer"},mimeType:{type:"string"},text:{type:"string"},encoding:{type:"string"},comment:{type:"string"}}}},{}],410:[function(require,module,exports){module.exports={$id:"cookie.json#",$schema:"http://json-schema.org/draft-06/schema#",type:"object",required:["name","value"],properties:{name:{type:"string"},value:{type:"string"},path:{type:"string"},domain:{type:"string"},expires:{type:["string","null"],format:"date-time"},httpOnly:{type:"boolean"},secure:{type:"boolean"},comment:{type:"string"}}}},{}],411:[function(require,module,exports){module.exports={$id:"creator.json#",$schema:"http://json-schema.org/draft-06/schema#",type:"object",required:["name","version"],properties:{name:{type:"string"},version:{type:"string"},comment:{type:"string"}}}},{}],412:[function(require,module,exports){module.exports={$id:"entry.json#",$schema:"http://json-schema.org/draft-06/schema#",type:"object",optional:true,required:["startedDateTime","time","request","response","cache","timings"],properties:{pageref:{type:"string"},startedDateTime:{type:"string",format:"date-time",pattern:"^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))"},time:{type:"number",min:0},request:{$ref:"request.json#"},response:{$ref:"response.json#"},cache:{$ref:"cache.json#"},timings:{$ref:"timings.json#"},serverIPAddress:{type:"string",oneOf:[{format:"ipv4"},{format:"ipv6"}]},connection:{type:"string"},comment:{type:"string"}}}},{}],413:[function(require,module,exports){module.exports={$id:"har.json#",$schema:"http://json-schema.org/draft-06/schema#",type:"object",required:["log"],properties:{log:{$ref:"log.json#"}}}},{}],414:[function(require,module,exports){module.exports={$id:"header.json#",$schema:"http://json-schema.org/draft-06/schema#",type:"object",required:["name","value"],properties:{name:{type:"string"},value:{type:"string"},comment:{type:"string"}}}},{}],415:[function(require,module,exports){"use strict";module.exports={afterRequest:require("./afterRequest.json"),beforeRequest:require("./beforeRequest.json"),browser:require("./browser.json"),cache:require("./cache.json"),content:require("./content.json"),cookie:require("./cookie.json"),creator:require("./creator.json"),entry:require("./entry.json"),har:require("./har.json"),header:require("./header.json"),log:require("./log.json"),page:require("./page.json"),pageTimings:require("./pageTimings.json"),postData:require("./postData.json"),query:require("./query.json"),request:require("./request.json"),response:require("./response.json"),timings:require("./timings.json")}},{"./afterRequest.json":405,"./beforeRequest.json":406,"./browser.json":407,"./cache.json":408,"./content.json":409,"./cookie.json":410,"./creator.json":411,"./entry.json":412,"./har.json":413,"./header.json":414,"./log.json":416,"./page.json":417,"./pageTimings.json":418,"./postData.json":419,"./query.json":420,"./request.json":421,"./response.json":422,"./timings.json":423}],416:[function(require,module,exports){module.exports={$id:"log.json#",$schema:"http://json-schema.org/draft-06/schema#",type:"object",required:["version","creator","entries"],properties:{version:{type:"string"},creator:{$ref:"creator.json#"},browser:{$ref:"browser.json#"},pages:{type:"array",items:{$ref:"page.json#"}},entries:{type:"array",items:{$ref:"entry.json#"}},comment:{type:"string"}}}},{}],417:[function(require,module,exports){module.exports={$id:"page.json#",$schema:"http://json-schema.org/draft-06/schema#",type:"object",optional:true,required:["startedDateTime","id","title","pageTimings"],properties:{startedDateTime:{type:"string",format:"date-time",pattern:"^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))"},id:{type:"string",unique:true},title:{type:"string"},pageTimings:{$ref:"pageTimings.json#"},comment:{type:"string"}}}},{}],418:[function(require,module,exports){module.exports={$id:"pageTimings.json#",$schema:"http://json-schema.org/draft-06/schema#",type:"object",properties:{onContentLoad:{type:"number",min:-1},onLoad:{type:"number",min:-1},comment:{type:"string"}}}},{}],419:[function(require,module,exports){module.exports={$id:"postData.json#",$schema:"http://json-schema.org/draft-06/schema#",type:"object",optional:true,required:["mimeType"],properties:{mimeType:{type:"string"},text:{type:"string"},params:{type:"array",required:["name"],properties:{name:{type:"string"},value:{type:"string"},fileName:{type:"string"},contentType:{type:"string"},comment:{type:"string"}}},comment:{type:"string"}}}},{}],420:[function(require,module,exports){module.exports={$id:"query.json#",$schema:"http://json-schema.org/draft-06/schema#",type:"object",required:["name","value"],properties:{name:{type:"string"},value:{type:"string"},comment:{type:"string"}}}},{}],421:[function(require,module,exports){module.exports={$id:"request.json#",$schema:"http://json-schema.org/draft-06/schema#",type:"object",required:["method","url","httpVersion","cookies","headers","queryString","headersSize","bodySize"],properties:{method:{type:"string"},url:{type:"string",format:"uri"},httpVersion:{type:"string"},cookies:{type:"array",items:{$ref:"cookie.json#"}},headers:{type:"array",items:{$ref:"header.json#"}},queryString:{type:"array",items:{$ref:"query.json#"}},postData:{$ref:"postData.json#"},headersSize:{type:"integer"},bodySize:{type:"integer"},comment:{type:"string"}}}},{}],422:[function(require,module,exports){module.exports={$id:"response.json#",$schema:"http://json-schema.org/draft-06/schema#",type:"object",required:["status","statusText","httpVersion","cookies","headers","content","redirectURL","headersSize","bodySize"],properties:{status:{type:"integer"},statusText:{type:"string"},httpVersion:{type:"string"},cookies:{type:"array",items:{$ref:"cookie.json#"}},headers:{type:"array",items:{$ref:"header.json#"}},content:{$ref:"content.json#"},redirectURL:{type:"string"},headersSize:{type:"integer"},bodySize:{type:"integer"},comment:{type:"string"}}}},{}],423:[function(require,module,exports){module.exports={$id:"timings.json#",$schema:"http://json-schema.org/draft-06/schema#",required:["send","wait","receive"],properties:{dns:{type:"number",min:-1},connect:{type:"number",min:-1},blocked:{type:"number",min:-1},send:{type:"number",min:-1},wait:{type:"number",min:-1},receive:{type:"number",min:-1},ssl:{type:"number",min:-1},comment:{type:"string"}}}},{}],424:[function(require,module,exports){function HARError(errors){var message="validation failed";this.name="HARError";this.message=message;this.errors=errors;if(typeof Error.captureStackTrace==="function"){Error.captureStackTrace(this,this.constructor)}else{this.stack=new Error(message).stack}}HARError.prototype=Error.prototype;module.exports=HARError},{}],425:[function(require,module,exports){var Ajv=require("ajv");var HARError=require("./error");var schemas=require("har-schema");var ajv;function createAjvInstance(){var ajv=new Ajv({allErrors:true});ajv.addMetaSchema(require("ajv/lib/refs/json-schema-draft-06.json"));ajv.addSchema(schemas);return ajv}function validate(name,data){data=data||{};ajv=ajv||createAjvInstance();var validate=ajv.getSchema(name+".json");return new Promise(function(resolve,reject){var valid=validate(data);!valid?reject(new HARError(validate.errors)):resolve(data)})}exports.afterRequest=function(data){return validate("afterRequest",data)};exports.beforeRequest=function(data){return validate("beforeRequest",data)};exports.browser=function(data){return validate("browser",data)};exports.cache=function(data){return validate("cache",data)};exports.content=function(data){return validate("content",data)};exports.cookie=function(data){return validate("cookie",data)};exports.creator=function(data){return validate("creator",data)};exports.entry=function(data){return validate("entry",data)};exports.har=function(data){return validate("har",data)};exports.header=function(data){return validate("header",data)};exports.log=function(data){return validate("log",data)};exports.page=function(data){return validate("page",data)};exports.pageTimings=function(data){return validate("pageTimings",data)};exports.postData=function(data){return validate("postData",data)};exports.query=function(data){return validate("query",data)};exports.request=function(data){return validate("request",data)};exports.response=function(data){return validate("response",data)};exports.timings=function(data){return validate("timings",data)}},{"./error":424,ajv:338,"ajv/lib/refs/json-schema-draft-06.json":379,"har-schema":415}],426:[function(require,module,exports){var parser=require("./parser");var signer=require("./signer");var verify=require("./verify");var utils=require("./utils");module.exports={parse:parser.parseRequest,parseRequest:parser.parseRequest,sign:signer.signRequest,signRequest:signer.signRequest,createSigner:signer.createSigner,isSigner:signer.isSigner,sshKeyToPEM:utils.sshKeyToPEM,sshKeyFingerprint:utils.fingerprint,pemToRsaSSHKey:utils.pemToRsaSSHKey,verify:verify.verifySignature,verifySignature:verify.verifySignature,verifyHMAC:verify.verifyHMAC}},{"./parser":427,"./signer":428,"./utils":429,"./verify":430}],427:[function(require,module,exports){var assert=require("assert-plus");var util=require("util");var utils=require("./utils");var HASH_ALGOS=utils.HASH_ALGOS;var PK_ALGOS=utils.PK_ALGOS;var HttpSignatureError=utils.HttpSignatureError;var InvalidAlgorithmError=utils.InvalidAlgorithmError;var validateAlgorithm=utils.validateAlgorithm;var State={New:0,Params:1};var ParamsState={Name:0,Quote:1,Value:2,Comma:3};function ExpiredRequestError(message){HttpSignatureError.call(this,message,ExpiredRequestError)}util.inherits(ExpiredRequestError,HttpSignatureError);function InvalidHeaderError(message){HttpSignatureError.call(this,message,InvalidHeaderError)}util.inherits(InvalidHeaderError,HttpSignatureError);function InvalidParamsError(message){HttpSignatureError.call(this,message,InvalidParamsError)}util.inherits(InvalidParamsError,HttpSignatureError);function MissingHeaderError(message){HttpSignatureError.call(this,message,MissingHeaderError)}util.inherits(MissingHeaderError,HttpSignatureError);function StrictParsingError(message){HttpSignatureError.call(this,message,StrictParsingError)}util.inherits(StrictParsingError,HttpSignatureError);module.exports={parseRequest:function parseRequest(request,options){assert.object(request,"request");assert.object(request.headers,"request.headers");if(options===undefined){options={}}if(options.headers===undefined){options.headers=[request.headers["x-date"]?"x-date":"date"]}assert.object(options,"options");assert.arrayOfString(options.headers,"options.headers");assert.optionalFinite(options.clockSkew,"options.clockSkew");var authzHeaderName=options.authorizationHeaderName||"authorization";if(!request.headers[authzHeaderName]){throw new MissingHeaderError("no "+authzHeaderName+" header "+"present in the request")}options.clockSkew=options.clockSkew||300;var i=0;var state=State.New;var substate=ParamsState.Name;var tmpName="";var tmpValue="";var parsed={scheme:"",params:{},signingString:""};var authz=request.headers[authzHeaderName];for(i=0;i<authz.length;i++){var c=authz.charAt(i);switch(Number(state)){case State.New:if(c!==" ")parsed.scheme+=c;else state=State.Params;break;case State.Params:switch(Number(substate)){case ParamsState.Name:var code=c.charCodeAt(0);if(code>=65&&code<=90||code>=97&&code<=122){tmpName+=c}else if(c==="="){
41
41
  if(tmpName.length===0)throw new InvalidHeaderError("bad param format");substate=ParamsState.Quote}else{throw new InvalidHeaderError("bad param format")}break;case ParamsState.Quote:if(c==='"'){tmpValue="";substate=ParamsState.Value}else{throw new InvalidHeaderError("bad param format")}break;case ParamsState.Value:if(c==='"'){parsed.params[tmpName]=tmpValue;substate=ParamsState.Comma}else{tmpValue+=c}break;case ParamsState.Comma:if(c===","){tmpName="";substate=ParamsState.Name}else{throw new InvalidHeaderError("bad param format")}break;default:throw new Error("Invalid substate")}break;default:throw new Error("Invalid substate")}}if(!parsed.params.headers||parsed.params.headers===""){if(request.headers["x-date"]){parsed.params.headers=["x-date"]}else{parsed.params.headers=["date"]}}else{parsed.params.headers=parsed.params.headers.split(" ")}if(!parsed.scheme||parsed.scheme!=="Signature")throw new InvalidHeaderError('scheme was not "Signature"');if(!parsed.params.keyId)throw new InvalidHeaderError("keyId was not specified");if(!parsed.params.algorithm)throw new InvalidHeaderError("algorithm was not specified");if(!parsed.params.signature)throw new InvalidHeaderError("signature was not specified");parsed.params.algorithm=parsed.params.algorithm.toLowerCase();try{validateAlgorithm(parsed.params.algorithm)}catch(e){if(e instanceof InvalidAlgorithmError)throw new InvalidParamsError(parsed.params.algorithm+" is not "+"supported");else throw e}for(i=0;i<parsed.params.headers.length;i++){var h=parsed.params.headers[i].toLowerCase();parsed.params.headers[i]=h;if(h==="request-line"){if(!options.strict){parsed.signingString+=request.method+" "+request.url+" HTTP/"+request.httpVersion}else{throw new StrictParsingError("request-line is not a valid header "+"with strict parsing enabled.")}}else if(h==="(request-target)"){parsed.signingString+="(request-target): "+request.method.toLowerCase()+" "+request.url}else{var value=request.headers[h];if(value===undefined)throw new MissingHeaderError(h+" was not in the request");parsed.signingString+=h+": "+value}if(i+1<parsed.params.headers.length)parsed.signingString+="\n"}var date;if(request.headers.date||request.headers["x-date"]){if(request.headers["x-date"]){date=new Date(request.headers["x-date"])}else{date=new Date(request.headers.date)}var now=new Date;var skew=Math.abs(now.getTime()-date.getTime());if(skew>options.clockSkew*1e3){throw new ExpiredRequestError("clock skew of "+skew/1e3+"s was greater than "+options.clockSkew+"s")}}options.headers.forEach(function(hdr){if(parsed.params.headers.indexOf(hdr.toLowerCase())<0)throw new MissingHeaderError(hdr+" was not a signed header")});if(options.algorithms){if(options.algorithms.indexOf(parsed.params.algorithm)===-1)throw new InvalidParamsError(parsed.params.algorithm+" is not a supported algorithm")}parsed.algorithm=parsed.params.algorithm.toUpperCase();parsed.keyId=parsed.params.keyId;return parsed}}},{"./utils":429,"assert-plus":387,util:243}],428:[function(require,module,exports){(function(Buffer){(function(){var assert=require("assert-plus");var crypto=require("crypto");var http=require("http");var util=require("util");var sshpk=require("sshpk");var jsprim=require("jsprim");var utils=require("./utils");var sprintf=require("util").format;var HASH_ALGOS=utils.HASH_ALGOS;var PK_ALGOS=utils.PK_ALGOS;var InvalidAlgorithmError=utils.InvalidAlgorithmError;var HttpSignatureError=utils.HttpSignatureError;var validateAlgorithm=utils.validateAlgorithm;var AUTHZ_FMT='Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"';function MissingHeaderError(message){HttpSignatureError.call(this,message,MissingHeaderError)}util.inherits(MissingHeaderError,HttpSignatureError);function StrictParsingError(message){HttpSignatureError.call(this,message,StrictParsingError)}util.inherits(StrictParsingError,HttpSignatureError);function RequestSigner(options){assert.object(options,"options");var alg=[];if(options.algorithm!==undefined){assert.string(options.algorithm,"options.algorithm");alg=validateAlgorithm(options.algorithm)}this.rs_alg=alg;if(options.sign!==undefined){assert.func(options.sign,"options.sign");this.rs_signFunc=options.sign}else if(alg[0]==="hmac"&&options.key!==undefined){assert.string(options.keyId,"options.keyId");this.rs_keyId=options.keyId;if(typeof options.key!=="string"&&!Buffer.isBuffer(options.key))throw new TypeError("options.key for HMAC must be a string or Buffer");this.rs_signer=crypto.createHmac(alg[1].toUpperCase(),options.key);this.rs_signer.sign=function(){var digest=this.digest("base64");return{hashAlgorithm:alg[1],toString:function(){return digest}}}}else if(options.key!==undefined){var key=options.key;if(typeof key==="string"||Buffer.isBuffer(key))key=sshpk.parsePrivateKey(key);assert.ok(sshpk.PrivateKey.isPrivateKey(key,[1,2]),"options.key must be a sshpk.PrivateKey");this.rs_key=key;assert.string(options.keyId,"options.keyId");this.rs_keyId=options.keyId;if(!PK_ALGOS[key.type]){throw new InvalidAlgorithmError(key.type.toUpperCase()+" type "+"keys are not supported")}if(alg[0]!==undefined&&key.type!==alg[0]){throw new InvalidAlgorithmError("options.key must be a "+alg[0].toUpperCase()+" key, was given a "+key.type.toUpperCase()+" key instead")}this.rs_signer=key.createSign(alg[1])}else{throw new TypeError("options.sign (func) or options.key is required")}this.rs_headers=[];this.rs_lines=[]}RequestSigner.prototype.writeHeader=function(header,value){assert.string(header,"header");header=header.toLowerCase();assert.string(value,"value");this.rs_headers.push(header);if(this.rs_signFunc){this.rs_lines.push(header+": "+value)}else{var line=header+": "+value;if(this.rs_headers.length>0)line="\n"+line;this.rs_signer.update(line)}return value};RequestSigner.prototype.writeDateHeader=function(){return this.writeHeader("date",jsprim.rfc1123(new Date))};RequestSigner.prototype.writeTarget=function(method,path){assert.string(method,"method");assert.string(path,"path");method=method.toLowerCase();this.writeHeader("(request-target)",method+" "+path)};RequestSigner.prototype.sign=function(cb){assert.func(cb,"callback");if(this.rs_headers.length<1)throw new Error("At least one header must be signed");var alg,authz;if(this.rs_signFunc){var data=this.rs_lines.join("\n");var self=this;this.rs_signFunc(data,function(err,sig){if(err){cb(err);return}try{assert.object(sig,"signature");assert.string(sig.keyId,"signature.keyId");assert.string(sig.algorithm,"signature.algorithm");assert.string(sig.signature,"signature.signature");alg=validateAlgorithm(sig.algorithm);authz=sprintf(AUTHZ_FMT,sig.keyId,sig.algorithm,self.rs_headers.join(" "),sig.signature)}catch(e){cb(e);return}cb(null,authz)})}else{try{var sigObj=this.rs_signer.sign()}catch(e){cb(e);return}alg=(this.rs_alg[0]||this.rs_key.type)+"-"+sigObj.hashAlgorithm;var signature=sigObj.toString();authz=sprintf(AUTHZ_FMT,this.rs_keyId,alg,this.rs_headers.join(" "),signature);cb(null,authz)}};module.exports={isSigner:function(obj){if(typeof obj==="object"&&obj instanceof RequestSigner)return true;return false},createSigner:function createSigner(options){return new RequestSigner(options)},signRequest:function signRequest(request,options){assert.object(request,"request");assert.object(options,"options");assert.optionalString(options.algorithm,"options.algorithm");assert.string(options.keyId,"options.keyId");assert.optionalArrayOfString(options.headers,"options.headers");assert.optionalString(options.httpVersion,"options.httpVersion");if(!request.getHeader("Date"))request.setHeader("Date",jsprim.rfc1123(new Date));if(!options.headers)options.headers=["date"];if(!options.httpVersion)options.httpVersion="1.1";var alg=[];if(options.algorithm){options.algorithm=options.algorithm.toLowerCase();alg=validateAlgorithm(options.algorithm)}var i;var stringToSign="";for(i=0;i<options.headers.length;i++){if(typeof options.headers[i]!=="string")throw new TypeError("options.headers must be an array of Strings");var h=options.headers[i].toLowerCase();if(h==="request-line"){if(!options.strict){stringToSign+=request.method+" "+request.path+" HTTP/"+options.httpVersion}else{throw new StrictParsingError("request-line is not a valid header "+"with strict parsing enabled.")}}else if(h==="(request-target)"){stringToSign+="(request-target): "+request.method.toLowerCase()+" "+request.path}else{var value=request.getHeader(h);if(value===undefined||value===""){throw new MissingHeaderError(h+" was not in the request")}stringToSign+=h+": "+value}if(i+1<options.headers.length)stringToSign+="\n"}if(request.hasOwnProperty("_stringToSign")){request._stringToSign=stringToSign}var signature;if(alg[0]==="hmac"){if(typeof options.key!=="string"&&!Buffer.isBuffer(options.key))throw new TypeError("options.key must be a string or Buffer");var hmac=crypto.createHmac(alg[1].toUpperCase(),options.key);hmac.update(stringToSign);signature=hmac.digest("base64")}else{var key=options.key;if(typeof key==="string"||Buffer.isBuffer(key))key=sshpk.parsePrivateKey(options.key);assert.ok(sshpk.PrivateKey.isPrivateKey(key,[1,2]),"options.key must be a sshpk.PrivateKey");if(!PK_ALGOS[key.type]){throw new InvalidAlgorithmError(key.type.toUpperCase()+" type "+"keys are not supported")}if(alg[0]!==undefined&&key.type!==alg[0]){throw new InvalidAlgorithmError("options.key must be a "+alg[0].toUpperCase()+" key, was given a "+key.type.toUpperCase()+" key instead")}var signer=key.createSign(alg[1]);signer.update(stringToSign);var sigObj=signer.sign();if(!HASH_ALGOS[sigObj.hashAlgorithm]){throw new InvalidAlgorithmError(sigObj.hashAlgorithm.toUpperCase()+" is not a supported hash algorithm")}options.algorithm=key.type+"-"+sigObj.hashAlgorithm;signature=sigObj.toString();assert.notStrictEqual(signature,"","empty signature produced")}var authzHeaderName=options.authorizationHeaderName||"Authorization";request.setHeader(authzHeaderName,sprintf(AUTHZ_FMT,options.keyId,options.algorithm,options.headers.join(" "),signature));return true}}}).call(this)}).call(this,{isBuffer:require("../../../browser-agent/node_modules/is-buffer/index.js")})},{"../../../browser-agent/node_modules/is-buffer/index.js":146,"./utils":429,"assert-plus":387,crypto:81,http:230,jsprim:437,sshpk:490,util:243}],429:[function(require,module,exports){var assert=require("assert-plus");var sshpk=require("sshpk");var util=require("util");var HASH_ALGOS={sha1:true,sha256:true,sha512:true};var PK_ALGOS={rsa:true,dsa:true,ecdsa:true};function HttpSignatureError(message,caller){if(Error.captureStackTrace)Error.captureStackTrace(this,caller||HttpSignatureError);this.message=message;this.name=caller.name}util.inherits(HttpSignatureError,Error);function InvalidAlgorithmError(message){HttpSignatureError.call(this,message,InvalidAlgorithmError)}util.inherits(InvalidAlgorithmError,HttpSignatureError);function validateAlgorithm(algorithm){var alg=algorithm.toLowerCase().split("-");if(alg.length!==2){throw new InvalidAlgorithmError(alg[0].toUpperCase()+" is not a "+"valid algorithm")}if(alg[0]!=="hmac"&&!PK_ALGOS[alg[0]]){throw new InvalidAlgorithmError(alg[0].toUpperCase()+" type keys "+"are not supported")}if(!HASH_ALGOS[alg[1]]){throw new InvalidAlgorithmError(alg[1].toUpperCase()+" is not a "+"supported hash algorithm")}return alg}module.exports={HASH_ALGOS:HASH_ALGOS,PK_ALGOS:PK_ALGOS,HttpSignatureError:HttpSignatureError,InvalidAlgorithmError:InvalidAlgorithmError,validateAlgorithm:validateAlgorithm,sshKeyToPEM:function sshKeyToPEM(key){assert.string(key,"ssh_key");var k=sshpk.parseKey(key,"ssh");return k.toString("pem")},fingerprint:function fingerprint(key){assert.string(key,"ssh_key");var k=sshpk.parseKey(key,"ssh");return k.fingerprint("md5").toString("hex")},pemToRsaSSHKey:function pemToRsaSSHKey(pem,comment){assert.equal("string",typeof pem,"typeof pem");var k=sshpk.parseKey(pem,"pem");k.comment=comment;return k.toString("ssh")}}},{"assert-plus":387,sshpk:490,util:243}],430:[function(require,module,exports){(function(Buffer){(function(){var assert=require("assert-plus");var crypto=require("crypto");var sshpk=require("sshpk");var utils=require("./utils");var HASH_ALGOS=utils.HASH_ALGOS;var PK_ALGOS=utils.PK_ALGOS;var InvalidAlgorithmError=utils.InvalidAlgorithmError;var HttpSignatureError=utils.HttpSignatureError;var validateAlgorithm=utils.validateAlgorithm;module.exports={verifySignature:function verifySignature(parsedSignature,pubkey){assert.object(parsedSignature,"parsedSignature");if(typeof pubkey==="string"||Buffer.isBuffer(pubkey))pubkey=sshpk.parseKey(pubkey);assert.ok(sshpk.Key.isKey(pubkey,[1,1]),"pubkey must be a sshpk.Key");var alg=validateAlgorithm(parsedSignature.algorithm);if(alg[0]==="hmac"||alg[0]!==pubkey.type)return false;var v=pubkey.createVerify(alg[1]);v.update(parsedSignature.signingString);return v.verify(parsedSignature.params.signature,"base64")},verifyHMAC:function verifyHMAC(parsedSignature,secret){assert.object(parsedSignature,"parsedHMAC");assert.string(secret,"secret");var alg=validateAlgorithm(parsedSignature.algorithm);if(alg[0]!=="hmac")return false;var hashAlg=alg[1].toUpperCase();var hmac=crypto.createHmac(hashAlg,secret);hmac.update(parsedSignature.signingString);var h1=crypto.createHmac(hashAlg,secret);h1.update(hmac.digest());h1=h1.digest();var h2=crypto.createHmac(hashAlg,secret);h2.update(new Buffer(parsedSignature.params.signature,"base64"));h2=h2.digest();if(typeof h1==="string")return h1===h2;if(Buffer.isBuffer(h1)&&!h1.equals)return h1.toString("binary")===h2.toString("binary");return h1.equals(h2)}}}).call(this)}).call(this,require("buffer").Buffer)},{"./utils":429,"assert-plus":387,buffer:71,crypto:81,sshpk:490}],431:[function(require,module,exports){module.exports=isTypedArray;isTypedArray.strict=isStrictTypedArray;isTypedArray.loose=isLooseTypedArray;var toString=Object.prototype.toString;var names={"[object Int8Array]":true,"[object Int16Array]":true,"[object Int32Array]":true,"[object Uint8Array]":true,"[object Uint8ClampedArray]":true,"[object Uint16Array]":true,"[object Uint32Array]":true,"[object Float32Array]":true,"[object Float64Array]":true};function isTypedArray(arr){return isStrictTypedArray(arr)||isLooseTypedArray(arr)}function isStrictTypedArray(arr){return arr instanceof Int8Array||arr instanceof Int16Array||arr instanceof Int32Array||arr instanceof Uint8Array||arr instanceof Uint8ClampedArray||arr instanceof Uint16Array||arr instanceof Uint32Array||arr instanceof Float32Array||arr instanceof Float64Array}function isLooseTypedArray(arr){return names[toString.call(arr)]}},{}],432:[function(require,module,exports){var stream=require("stream");function isStream(obj){return obj instanceof stream.Stream}function isReadable(obj){return isStream(obj)&&typeof obj._read=="function"&&typeof obj._readableState=="object"}function isWritable(obj){return isStream(obj)&&typeof obj._write=="function"&&typeof obj._writableState=="object"}function isDuplex(obj){return isReadable(obj)&&isWritable(obj)}module.exports=isStream;module.exports.isReadable=isReadable;module.exports.isWritable=isWritable;module.exports.isDuplex=isDuplex},{stream:229}],433:[function(require,module,exports){(function(){var dbits;var canary=0xdeadbeefcafe;var j_lm=(canary&16777215)==15715070;function BigInteger(a,b,c){if(a!=null)if("number"==typeof a)this.fromNumber(a,b,c);else if(b==null&&"string"!=typeof a)this.fromString(a,256);else this.fromString(a,b)}function nbi(){return new BigInteger(null)}function am1(i,x,w,j,c,n){while(--n>=0){var v=x*this[i++]+w[j]+c;c=Math.floor(v/67108864);w[j++]=v&67108863}return c}function am2(i,x,w,j,c,n){var xl=x&32767,xh=x>>15;while(--n>=0){var l=this[i]&32767;var h=this[i++]>>15;var m=xh*l+h*xl;l=xl*l+((m&32767)<<15)+w[j]+(c&1073741823);c=(l>>>30)+(m>>>15)+xh*h+(c>>>30);w[j++]=l&1073741823}return c}function am3(i,x,w,j,c,n){var xl=x&16383,xh=x>>14;while(--n>=0){var l=this[i]&16383;var h=this[i++]>>14;var m=xh*l+h*xl;l=xl*l+((m&16383)<<14)+w[j]+c;c=(l>>28)+(m>>14)+xh*h;w[j++]=l&268435455}return c}var inBrowser=typeof navigator!=="undefined";if(inBrowser&&j_lm&&navigator.appName=="Microsoft Internet Explorer"){BigInteger.prototype.am=am2;dbits=30}else if(inBrowser&&j_lm&&navigator.appName!="Netscape"){BigInteger.prototype.am=am1;dbits=26}else{BigInteger.prototype.am=am3;dbits=28}BigInteger.prototype.DB=dbits;BigInteger.prototype.DM=(1<<dbits)-1;BigInteger.prototype.DV=1<<dbits;var BI_FP=52;BigInteger.prototype.FV=Math.pow(2,BI_FP);BigInteger.prototype.F1=BI_FP-dbits;BigInteger.prototype.F2=2*dbits-BI_FP;var BI_RM="0123456789abcdefghijklmnopqrstuvwxyz";var BI_RC=new Array;var rr,vv;rr="0".charCodeAt(0);for(vv=0;vv<=9;++vv)BI_RC[rr++]=vv;rr="a".charCodeAt(0);for(vv=10;vv<36;++vv)BI_RC[rr++]=vv;rr="A".charCodeAt(0);for(vv=10;vv<36;++vv)BI_RC[rr++]=vv;function int2char(n){return BI_RM.charAt(n)}function intAt(s,i){var c=BI_RC[s.charCodeAt(i)];return c==null?-1:c}function bnpCopyTo(r){for(var i=this.t-1;i>=0;--i)r[i]=this[i];r.t=this.t;r.s=this.s}function bnpFromInt(x){this.t=1;this.s=x<0?-1:0;if(x>0)this[0]=x;else if(x<-1)this[0]=x+this.DV;else this.t=0}function nbv(i){var r=nbi();r.fromInt(i);return r}function bnpFromString(s,b){var k;if(b==16)k=4;else if(b==8)k=3;else if(b==256)k=8;else if(b==2)k=1;else if(b==32)k=5;else if(b==4)k=2;else{this.fromRadix(s,b);return}this.t=0;this.s=0;var i=s.length,mi=false,sh=0;while(--i>=0){var x=k==8?s[i]&255:intAt(s,i);if(x<0){if(s.charAt(i)=="-")mi=true;continue}mi=false;if(sh==0)this[this.t++]=x;else if(sh+k>this.DB){this[this.t-1]|=(x&(1<<this.DB-sh)-1)<<sh;this[this.t++]=x>>this.DB-sh}else this[this.t-1]|=x<<sh;sh+=k;if(sh>=this.DB)sh-=this.DB}if(k==8&&(s[0]&128)!=0){this.s=-1;if(sh>0)this[this.t-1]|=(1<<this.DB-sh)-1<<sh}this.clamp();if(mi)BigInteger.ZERO.subTo(this,this)}function bnpClamp(){var c=this.s&this.DM;while(this.t>0&&this[this.t-1]==c)--this.t}function bnToString(b){if(this.s<0)return"-"+this.negate().toString(b);var k;if(b==16)k=4;else if(b==8)k=3;else if(b==2)k=1;else if(b==32)k=5;else if(b==4)k=2;else return this.toRadix(b);var km=(1<<k)-1,d,m=false,r="",i=this.t;var p=this.DB-i*this.DB%k;if(i-- >0){if(p<this.DB&&(d=this[i]>>p)>0){m=true;r=int2char(d)}while(i>=0){if(p<k){d=(this[i]&(1<<p)-1)<<k-p;d|=this[--i]>>(p+=this.DB-k)}else{d=this[i]>>(p-=k)&km;if(p<=0){p+=this.DB;--i}}if(d>0)m=true;if(m)r+=int2char(d)}}return m?r:"0"}function bnNegate(){var r=nbi();BigInteger.ZERO.subTo(this,r);return r}function bnAbs(){return this.s<0?this.negate():this}function bnCompareTo(a){var r=this.s-a.s;if(r!=0)return r;var i=this.t;r=i-a.t;if(r!=0)return this.s<0?-r:r;while(--i>=0)if((r=this[i]-a[i])!=0)return r;return 0}function nbits(x){var r=1,t;if((t=x>>>16)!=0){x=t;r+=16}if((t=x>>8)!=0){x=t;r+=8}if((t=x>>4)!=0){x=t;r+=4}if((t=x>>2)!=0){x=t;r+=2}if((t=x>>1)!=0){x=t;r+=1}return r}function bnBitLength(){if(this.t<=0)return 0;return this.DB*(this.t-1)+nbits(this[this.t-1]^this.s&this.DM)}function bnpDLShiftTo(n,r){var i;for(i=this.t-1;i>=0;--i)r[i+n]=this[i];for(i=n-1;i>=0;--i)r[i]=0;r.t=this.t+n;r.s=this.s}function bnpDRShiftTo(n,r){for(var i=n;i<this.t;++i)r[i-n]=this[i];r.t=Math.max(this.t-n,0);r.s=this.s}function bnpLShiftTo(n,r){var bs=n%this.DB;var cbs=this.DB-bs;var bm=(1<<cbs)-1;var ds=Math.floor(n/this.DB),c=this.s<<bs&this.DM,i;for(i=this.t-1;i>=0;--i){r[i+ds+1]=this[i]>>cbs|c;c=(this[i]&bm)<<bs}for(i=ds-1;i>=0;--i)r[i]=0;r[ds]=c;r.t=this.t+ds+1;r.s=this.s;r.clamp()}function bnpRShiftTo(n,r){r.s=this.s;var ds=Math.floor(n/this.DB);if(ds>=this.t){r.t=0;return}var bs=n%this.DB;var cbs=this.DB-bs;var bm=(1<<bs)-1;r[0]=this[ds]>>bs;for(var i=ds+1;i<this.t;++i){r[i-ds-1]|=(this[i]&bm)<<cbs;r[i-ds]=this[i]>>bs}if(bs>0)r[this.t-ds-1]|=(this.s&bm)<<cbs;r.t=this.t-ds;r.clamp()}function bnpSubTo(a,r){var i=0,c=0,m=Math.min(a.t,this.t);while(i<m){c+=this[i]-a[i];r[i++]=c&this.DM;c>>=this.DB}if(a.t<this.t){c-=a.s;while(i<this.t){c+=this[i];r[i++]=c&this.DM;c>>=this.DB}c+=this.s}else{c+=this.s;while(i<a.t){c-=a[i];r[i++]=c&this.DM;c>>=this.DB}c-=a.s}r.s=c<0?-1:0;if(c<-1)r[i++]=this.DV+c;else if(c>0)r[i++]=c;r.t=i;r.clamp()}function bnpMultiplyTo(a,r){var x=this.abs(),y=a.abs();var i=x.t;r.t=i+y.t;while(--i>=0)r[i]=0;for(i=0;i<y.t;++i)r[i+x.t]=x.am(0,y[i],r,i,0,x.t);r.s=0;r.clamp();if(this.s!=a.s)BigInteger.ZERO.subTo(r,r)}function bnpSquareTo(r){var x=this.abs();var i=r.t=2*x.t;while(--i>=0)r[i]=0;for(i=0;i<x.t-1;++i){var c=x.am(i,x[i],r,2*i,0,1);if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1))>=x.DV){r[i+x.t]-=x.DV;r[i+x.t+1]=1}}if(r.t>0)r[r.t-1]+=x.am(i,x[i],r,2*i,0,1);r.s=0;r.clamp()}function bnpDivRemTo(m,q,r){var pm=m.abs();if(pm.t<=0)return;var pt=this.abs();if(pt.t<pm.t){if(q!=null)q.fromInt(0);if(r!=null)this.copyTo(r);return}if(r==null)r=nbi();var y=nbi(),ts=this.s,ms=m.s;var nsh=this.DB-nbits(pm[pm.t-1]);if(nsh>0){pm.lShiftTo(nsh,y);pt.lShiftTo(nsh,r)}else{pm.copyTo(y);pt.copyTo(r)}var ys=y.t;var y0=y[ys-1];if(y0==0)return;var yt=y0*(1<<this.F1)+(ys>1?y[ys-2]>>this.F2:0);var d1=this.FV/yt,d2=(1<<this.F1)/yt,e=1<<this.F2;var i=r.t,j=i-ys,t=q==null?nbi():q;y.dlShiftTo(j,t);if(r.compareTo(t)>=0){r[r.t++]=1;r.subTo(t,r)}BigInteger.ONE.dlShiftTo(ys,t);t.subTo(y,y);while(y.t<ys)y[y.t++]=0;while(--j>=0){var qd=r[--i]==y0?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);if((r[i]+=y.am(0,qd,r,j,0,ys))<qd){y.dlShiftTo(j,t);r.subTo(t,r);while(r[i]<--qd)r.subTo(t,r)}}if(q!=null){r.drShiftTo(ys,q);if(ts!=ms)BigInteger.ZERO.subTo(q,q)}r.t=ys;r.clamp();if(nsh>0)r.rShiftTo(nsh,r);if(ts<0)BigInteger.ZERO.subTo(r,r)}function bnMod(a){var r=nbi();this.abs().divRemTo(a,null,r);if(this.s<0&&r.compareTo(BigInteger.ZERO)>0)a.subTo(r,r);return r}function Classic(m){this.m=m}function cConvert(x){if(x.s<0||x.compareTo(this.m)>=0)return x.mod(this.m);else return x}function cRevert(x){return x}function cReduce(x){x.divRemTo(this.m,null,x)}function cMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r)}function cSqrTo(x,r){x.squareTo(r);this.reduce(r)}Classic.prototype.convert=cConvert;Classic.prototype.revert=cRevert;Classic.prototype.reduce=cReduce;Classic.prototype.mulTo=cMulTo;Classic.prototype.sqrTo=cSqrTo;function bnpInvDigit(){if(this.t<1)return 0;var x=this[0];if((x&1)==0)return 0;var y=x&3;y=y*(2-(x&15)*y)&15;y=y*(2-(x&255)*y)&255;y=y*(2-((x&65535)*y&65535))&65535;y=y*(2-x*y%this.DV)%this.DV;return y>0?this.DV-y:-y}function Montgomery(m){this.m=m;this.mp=m.invDigit();this.mpl=this.mp&32767;this.mph=this.mp>>15;this.um=(1<<m.DB-15)-1;this.mt2=2*m.t}function montConvert(x){var r=nbi();x.abs().dlShiftTo(this.m.t,r);r.divRemTo(this.m,null,r);if(x.s<0&&r.compareTo(BigInteger.ZERO)>0)this.m.subTo(r,r);return r}function montRevert(x){var r=nbi();x.copyTo(r);this.reduce(r);return r}function montReduce(x){while(x.t<=this.mt2)x[x.t++]=0;for(var i=0;i<this.m.t;++i){var j=x[i]&32767;var u0=j*this.mpl+((j*this.mph+(x[i]>>15)*this.mpl&this.um)<<15)&x.DM;j=i+this.m.t;x[j]+=this.m.am(0,u0,x,i,0,this.m.t);while(x[j]>=x.DV){x[j]-=x.DV;x[++j]++}}x.clamp();x.drShiftTo(this.m.t,x);if(x.compareTo(this.m)>=0)x.subTo(this.m,x)}function montSqrTo(x,r){x.squareTo(r);this.reduce(r)}function montMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r)}Montgomery.prototype.convert=montConvert;Montgomery.prototype.revert=montRevert;Montgomery.prototype.reduce=montReduce;Montgomery.prototype.mulTo=montMulTo;Montgomery.prototype.sqrTo=montSqrTo;function bnpIsEven(){return(this.t>0?this[0]&1:this.s)==0}function bnpExp(e,z){if(e>4294967295||e<1)return BigInteger.ONE;var r=nbi(),r2=nbi(),g=z.convert(this),i=nbits(e)-1;g.copyTo(r);while(--i>=0){z.sqrTo(r,r2);if((e&1<<i)>0)z.mulTo(r2,g,r);else{var t=r;r=r2;r2=t}}return z.revert(r)}function bnModPowInt(e,m){var z;if(e<256||m.isEven())z=new Classic(m);else z=new Montgomery(m);return this.exp(e,z)}BigInteger.prototype.copyTo=bnpCopyTo;BigInteger.prototype.fromInt=bnpFromInt;BigInteger.prototype.fromString=bnpFromString;BigInteger.prototype.clamp=bnpClamp;BigInteger.prototype.dlShiftTo=bnpDLShiftTo;BigInteger.prototype.drShiftTo=bnpDRShiftTo;BigInteger.prototype.lShiftTo=bnpLShiftTo;BigInteger.prototype.rShiftTo=bnpRShiftTo;BigInteger.prototype.subTo=bnpSubTo;BigInteger.prototype.multiplyTo=bnpMultiplyTo;BigInteger.prototype.squareTo=bnpSquareTo;BigInteger.prototype.divRemTo=bnpDivRemTo;BigInteger.prototype.invDigit=bnpInvDigit;BigInteger.prototype.isEven=bnpIsEven;BigInteger.prototype.exp=bnpExp;BigInteger.prototype.toString=bnToString;BigInteger.prototype.negate=bnNegate;BigInteger.prototype.abs=bnAbs;BigInteger.prototype.compareTo=bnCompareTo;BigInteger.prototype.bitLength=bnBitLength;BigInteger.prototype.mod=bnMod;BigInteger.prototype.modPowInt=bnModPowInt;BigInteger.ZERO=nbv(0);BigInteger.ONE=nbv(1);function bnClone(){var r=nbi();this.copyTo(r);return r}function bnIntValue(){if(this.s<0){if(this.t==1)return this[0]-this.DV;else if(this.t==0)return-1}else if(this.t==1)return this[0];else if(this.t==0)return 0;return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]}function bnByteValue(){return this.t==0?this.s:this[0]<<24>>24}function bnShortValue(){return this.t==0?this.s:this[0]<<16>>16}function bnpChunkSize(r){return Math.floor(Math.LN2*this.DB/Math.log(r))}function bnSigNum(){if(this.s<0)return-1;else if(this.t<=0||this.t==1&&this[0]<=0)return 0;else return 1}function bnpToRadix(b){if(b==null)b=10;if(this.signum()==0||b<2||b>36)return"0";var cs=this.chunkSize(b);var a=Math.pow(b,cs);var d=nbv(a),y=nbi(),z=nbi(),r="";this.divRemTo(d,y,z);while(y.signum()>0){r=(a+z.intValue()).toString(b).substr(1)+r;y.divRemTo(d,y,z)}return z.intValue().toString(b)+r}function bnpFromRadix(s,b){this.fromInt(0);if(b==null)b=10;var cs=this.chunkSize(b);var d=Math.pow(b,cs),mi=false,j=0,w=0;for(var i=0;i<s.length;++i){var x=intAt(s,i);if(x<0){if(s.charAt(i)=="-"&&this.signum()==0)mi=true;continue}w=b*w+x;if(++j>=cs){this.dMultiply(d);this.dAddOffset(w,0);j=0;w=0}}if(j>0){this.dMultiply(Math.pow(b,j));this.dAddOffset(w,0)}if(mi)BigInteger.ZERO.subTo(this,this)}function bnpFromNumber(a,b,c){if("number"==typeof b){if(a<2)this.fromInt(1);else{this.fromNumber(a,c);if(!this.testBit(a-1))this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);if(this.isEven())this.dAddOffset(1,0);while(!this.isProbablePrime(b)){this.dAddOffset(2,0);if(this.bitLength()>a)this.subTo(BigInteger.ONE.shiftLeft(a-1),this)}}}else{var x=new Array,t=a&7;x.length=(a>>3)+1;b.nextBytes(x);if(t>0)x[0]&=(1<<t)-1;else x[0]=0;this.fromString(x,256)}}function bnToByteArray(){var i=this.t,r=new Array;r[0]=this.s;var p=this.DB-i*this.DB%8,d,k=0;if(i-- >0){if(p<this.DB&&(d=this[i]>>p)!=(this.s&this.DM)>>p)r[k++]=d|this.s<<this.DB-p;while(i>=0){if(p<8){d=(this[i]&(1<<p)-1)<<8-p;d|=this[--i]>>(p+=this.DB-8)}else{d=this[i]>>(p-=8)&255;if(p<=0){p+=this.DB;--i}}if((d&128)!=0)d|=-256;if(k==0&&(this.s&128)!=(d&128))++k;if(k>0||d!=this.s)r[k++]=d}}return r}function bnEquals(a){return this.compareTo(a)==0}function bnMin(a){return this.compareTo(a)<0?this:a}function bnMax(a){return this.compareTo(a)>0?this:a}function bnpBitwiseTo(a,op,r){var i,f,m=Math.min(a.t,this.t);for(i=0;i<m;++i)r[i]=op(this[i],a[i]);if(a.t<this.t){f=a.s&this.DM;for(i=m;i<this.t;++i)r[i]=op(this[i],f);r.t=this.t}else{f=this.s&this.DM;for(i=m;i<a.t;++i)r[i]=op(f,a[i]);r.t=a.t}r.s=op(this.s,a.s);r.clamp()}function op_and(x,y){return x&y}function bnAnd(a){var r=nbi();this.bitwiseTo(a,op_and,r);return r}function op_or(x,y){return x|y}function bnOr(a){var r=nbi();this.bitwiseTo(a,op_or,r);return r}function op_xor(x,y){return x^y}function bnXor(a){var r=nbi();this.bitwiseTo(a,op_xor,r);return r}function op_andnot(x,y){return x&~y}function bnAndNot(a){var r=nbi();this.bitwiseTo(a,op_andnot,r);return r}function bnNot(){var r=nbi();for(var i=0;i<this.t;++i)r[i]=this.DM&~this[i];r.t=this.t;r.s=~this.s;return r}function bnShiftLeft(n){var r=nbi();if(n<0)this.rShiftTo(-n,r);else this.lShiftTo(n,r);return r}function bnShiftRight(n){var r=nbi();if(n<0)this.lShiftTo(-n,r);else this.rShiftTo(n,r);return r}function lbit(x){if(x==0)return-1;var r=0;if((x&65535)==0){x>>=16;r+=16}if((x&255)==0){x>>=8;r+=8}if((x&15)==0){x>>=4;r+=4}if((x&3)==0){x>>=2;r+=2}if((x&1)==0)++r;return r}function bnGetLowestSetBit(){for(var i=0;i<this.t;++i)if(this[i]!=0)return i*this.DB+lbit(this[i]);if(this.s<0)return this.t*this.DB;return-1}function cbit(x){var r=0;while(x!=0){x&=x-1;++r}return r}function bnBitCount(){var r=0,x=this.s&this.DM;for(var i=0;i<this.t;++i)r+=cbit(this[i]^x);return r}function bnTestBit(n){var j=Math.floor(n/this.DB);if(j>=this.t)return this.s!=0;return(this[j]&1<<n%this.DB)!=0}function bnpChangeBit(n,op){var r=BigInteger.ONE.shiftLeft(n);this.bitwiseTo(r,op,r);return r}function bnSetBit(n){return this.changeBit(n,op_or)}function bnClearBit(n){return this.changeBit(n,op_andnot)}function bnFlipBit(n){return this.changeBit(n,op_xor)}function bnpAddTo(a,r){var i=0,c=0,m=Math.min(a.t,this.t);while(i<m){c+=this[i]+a[i];r[i++]=c&this.DM;c>>=this.DB}if(a.t<this.t){c+=a.s;while(i<this.t){c+=this[i];r[i++]=c&this.DM;c>>=this.DB}c+=this.s}else{c+=this.s;while(i<a.t){c+=a[i];r[i++]=c&this.DM;c>>=this.DB}c+=a.s}r.s=c<0?-1:0;if(c>0)r[i++]=c;else if(c<-1)r[i++]=this.DV+c;r.t=i;r.clamp()}function bnAdd(a){var r=nbi();this.addTo(a,r);return r}function bnSubtract(a){var r=nbi();this.subTo(a,r);return r}function bnMultiply(a){var r=nbi();this.multiplyTo(a,r);return r}function bnSquare(){var r=nbi();this.squareTo(r);return r}function bnDivide(a){var r=nbi();this.divRemTo(a,r,null);return r}function bnRemainder(a){var r=nbi();this.divRemTo(a,null,r);return r}function bnDivideAndRemainder(a){var q=nbi(),r=nbi();this.divRemTo(a,q,r);return new Array(q,r)}function bnpDMultiply(n){this[this.t]=this.am(0,n-1,this,0,0,this.t);++this.t;this.clamp()}function bnpDAddOffset(n,w){if(n==0)return;while(this.t<=w)this[this.t++]=0;this[w]+=n;while(this[w]>=this.DV){this[w]-=this.DV;if(++w>=this.t)this[this.t++]=0;++this[w]}}function NullExp(){}function nNop(x){return x}function nMulTo(x,y,r){x.multiplyTo(y,r)}function nSqrTo(x,r){x.squareTo(r)}NullExp.prototype.convert=nNop;NullExp.prototype.revert=nNop;NullExp.prototype.mulTo=nMulTo;NullExp.prototype.sqrTo=nSqrTo;function bnPow(e){return this.exp(e,new NullExp)}function bnpMultiplyLowerTo(a,n,r){var i=Math.min(this.t+a.t,n);r.s=0;r.t=i;while(i>0)r[--i]=0;var j;for(j=r.t-this.t;i<j;++i)r[i+this.t]=this.am(0,a[i],r,i,0,this.t);for(j=Math.min(a.t,n);i<j;++i)this.am(0,a[i],r,i,0,n-i);r.clamp()}function bnpMultiplyUpperTo(a,n,r){--n;var i=r.t=this.t+a.t-n;r.s=0;while(--i>=0)r[i]=0;for(i=Math.max(n-this.t,0);i<a.t;++i)r[this.t+i-n]=this.am(n-i,a[i],r,0,0,this.t+i-n);r.clamp();r.drShiftTo(1,r)}function Barrett(m){this.r2=nbi();this.q3=nbi();BigInteger.ONE.dlShiftTo(2*m.t,this.r2);this.mu=this.r2.divide(m);this.m=m}function barrettConvert(x){if(x.s<0||x.t>2*this.m.t)return x.mod(this.m);else if(x.compareTo(this.m)<0)return x;else{var r=nbi();x.copyTo(r);this.reduce(r);return r}}function barrettRevert(x){return x}function barrettReduce(x){x.drShiftTo(this.m.t-1,this.r2);if(x.t>this.m.t+1){x.t=this.m.t+1;x.clamp()}this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);while(x.compareTo(this.r2)<0)x.dAddOffset(1,this.m.t+1);x.subTo(this.r2,x);while(x.compareTo(this.m)>=0)x.subTo(this.m,x)}function barrettSqrTo(x,r){x.squareTo(r);this.reduce(r)}function barrettMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r)}Barrett.prototype.convert=barrettConvert;Barrett.prototype.revert=barrettRevert;Barrett.prototype.reduce=barrettReduce;Barrett.prototype.mulTo=barrettMulTo;Barrett.prototype.sqrTo=barrettSqrTo;function bnModPow(e,m){var i=e.bitLength(),k,r=nbv(1),z;if(i<=0)return r;else if(i<18)k=1;else if(i<48)k=3;else if(i<144)k=4;else if(i<768)k=5;else k=6;if(i<8)z=new Classic(m);else if(m.isEven())z=new Barrett(m);else z=new Montgomery(m);var g=new Array,n=3,k1=k-1,km=(1<<k)-1;g[1]=z.convert(this);if(k>1){var g2=nbi();z.sqrTo(g[1],g2);while(n<=km){g[n]=nbi();z.mulTo(g2,g[n-2],g[n]);n+=2}}var j=e.t-1,w,is1=true,r2=nbi(),t;i=nbits(e[j])-1;while(j>=0){if(i>=k1)w=e[j]>>i-k1&km;else{w=(e[j]&(1<<i+1)-1)<<k1-i;if(j>0)w|=e[j-1]>>this.DB+i-k1}n=k;while((w&1)==0){w>>=1;--n}