(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Syndicate=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o=kMaxLength()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength().toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target)){throw new TypeError("Argument must be a Buffer")}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(isNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;iremaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&255;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(i=0;i>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break ;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isnan(val){return val!==val}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":3,ieee754:4,isarray:5}],3:[function(require,module,exports){"use strict";exports.byteLength=byteLength;exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i0){throw new Error("Invalid string. Length must be a multiple of 4")}return b64[len-2]==="="?2:b64[len-1]==="="?1:0}function byteLength(b64){return b64.length*3/4-placeHoldersCount(b64)}function toByteArray(b64){var i,j,l,tmp,placeHolders,arr;var len=b64.length;placeHolders=placeHoldersCount(b64);arr=new Arr(len*3/4-placeHolders);l=placeHolders>0?len-4:len;var L=0;for(i=0,j=0;i>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},{}],4:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>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<>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<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],5:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],6:[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 hashes=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(Object.keys(require("browserify-sign/algos")));exports.getHashes=function(){return hashes};var p=require("pbkdf2");exports.pbkdf2=p.pbkdf2;exports.pbkdf2Sync=p.pbkdf2Sync;var aes=require("browserify-cipher");["Cipher","createCipher","Cipheriv","createCipheriv","Decipher","createDecipher","Decipheriv","createDecipheriv","getCiphers","listCiphers"].forEach(function(key){exports[key]=aes[key]});var dh=require("diffie-hellman");["DiffieHellmanGroup","createDiffieHellmanGroup","getDiffieHellman","createDiffieHellman","DiffieHellman"].forEach(function(key){exports[key]=dh[key]});var sign=require("browserify-sign");["createSign","Sign","createVerify","Verify"].forEach(function(key){exports[key]=sign[key]});exports.createECDH=require("create-ecdh");var publicEncrypt=require("public-encrypt");["publicEncrypt","privateEncrypt","publicDecrypt","privateDecrypt"].forEach(function(key){exports[key]=publicEncrypt[key]});["createCredentials"].forEach(function(name){exports[name]=function(){throw new Error(["sorry, "+name+" is not implemented yet","we accept pull requests","https://github.com/crypto-browserify/crypto-browserify"].join("\n"))}})},{"browserify-cipher":7,"browserify-sign":37,"browserify-sign/algos":36,"create-ecdh":106,"create-hash":134,"create-hmac":147,"diffie-hellman":148,pbkdf2:155,"public-encrypt":157,randombytes:202}],7:[function(require,module,exports){var ebtk=require("evp_bytestokey");var aes=require("browserify-aes/browser");var DES=require("browserify-des");var desModes=require("browserify-des/modes");var aesModes=require("browserify-aes/modes");function createCipher(suite,password){var keyLen,ivLen;suite=suite.toLowerCase();if(aesModes[suite]){keyLen=aesModes[suite].key;ivLen=aesModes[suite].iv}else if(desModes[suite]){keyLen=desModes[suite].key*8;ivLen=desModes[suite].iv}else{throw new TypeError("invalid suite type")}var keys=ebtk(password,false,keyLen,ivLen);return createCipheriv(suite,keys.key,keys.iv)}function createDecipher(suite,password){var keyLen,ivLen;suite=suite.toLowerCase();if(aesModes[suite]){keyLen=aesModes[suite].key;ivLen=aesModes[suite].iv}else if(desModes[suite]){keyLen=desModes[suite].key*8;ivLen=desModes[suite].iv}else{throw new TypeError("invalid suite type")}var keys=ebtk(password,false,keyLen,ivLen);return createDecipheriv(suite,keys.key,keys.iv)}function createCipheriv(suite,key,iv){suite=suite.toLowerCase();if(aesModes[suite]){return aes.createCipheriv(suite,key,iv)}else if(desModes[suite]){return new DES({key:key,iv:iv,mode:suite})}else{throw new TypeError("invalid suite type")}}function createDecipheriv(suite,key,iv){suite=suite.toLowerCase();if(aesModes[suite]){return aes.createDecipheriv(suite,key,iv)}else if(desModes[suite]){return new DES({key:key,iv:iv,mode:suite,decrypt:true})}else{throw new TypeError("invalid suite type")}}exports.createCipher=exports.Cipher=createCipher;exports.createCipheriv=exports.Cipheriv=createCipheriv;exports.createDecipher=exports.Decipher=createDecipher;exports.createDecipheriv=exports.Decipheriv=createDecipheriv;function getCiphers(){return Object.keys(desModes).concat(aes.getCiphers())}exports.listCiphers=exports.getCiphers=getCiphers},{"browserify-aes/browser":10,"browserify-aes/modes":14,"browserify-des":25,"browserify-des/modes":26,evp_bytestokey:35}],8:[function(require,module,exports){(function(Buffer){var uint_max=Math.pow(2,32);function fixup_uint32(x){var ret,x_pos;ret=x>uint_max||x<0?(x_pos=Math.abs(x)%uint_max,x<0?uint_max-x_pos:x_pos):x;return ret}function scrub_vec(v){for(var i=0;i>>8^sx&255^99;this.SBOX[x]=sx;this.INV_SBOX[sx]=x;x2=d[x];x4=d[x2];x8=d[x4];t=d[sx]*257^sx*16843008;this.SUB_MIX[0][x]=t<<24|t>>>8;this.SUB_MIX[1][x]=t<<16|t>>>16;this.SUB_MIX[2][x]=t<<8|t>>>24;this.SUB_MIX[3][x]=t;t=x8*16843009^x4*65537^x2*257^x*16843008;this.INV_SUB_MIX[0][sx]=t<<24|t>>>8;this.INV_SUB_MIX[1][sx]=t<<16|t>>>16;this.INV_SUB_MIX[2][sx]=t<<8|t>>>24;this.INV_SUB_MIX[3][sx]=t;if(x===0){x=xi=1}else{x=x2^d[d[d[x8^x2]]];xi^=d[d[xi]]}}return true};var G=new Global;AES.blockSize=4*4;AES.prototype.blockSize=AES.blockSize;AES.keySize=256/8;AES.prototype.keySize=AES.keySize;function bufferToArray(buf){var len=buf.length/4;var out=new Array(len);var i=-1;while(++i>>24,t=G.SBOX[t>>>24]<<24|G.SBOX[t>>>16&255]<<16|G.SBOX[t>>>8&255]<<8|G.SBOX[t&255],t^=G.RCON[ksRow/keySize|0]<<24):keySize>6&&ksRow%keySize===4?t=G.SBOX[t>>>24]<<24|G.SBOX[t>>>16&255]<<16|G.SBOX[t>>>8&255]<<8|G.SBOX[t&255]:void 0,this._keySchedule[ksRow-keySize]^t)}this._invKeySchedule=[];for(invKsRow=0;invKsRow>>24]]^G.INV_SUB_MIX[1][G.SBOX[t>>>16&255]]^G.INV_SUB_MIX[2][G.SBOX[t>>>8&255]]^G.INV_SUB_MIX[3][G.SBOX[t&255]]}return true};AES.prototype.encryptBlock=function(M){M=bufferToArray(new Buffer(M));var out=this._doCryptBlock(M,this._keySchedule,G.SUB_MIX,G.SBOX);var buf=new Buffer(16);buf.writeUInt32BE(out[0],0);buf.writeUInt32BE(out[1],4);buf.writeUInt32BE(out[2],8);buf.writeUInt32BE(out[3],12);return buf};AES.prototype.decryptBlock=function(M){M=bufferToArray(new Buffer(M));var temp=[M[3],M[1]];M[1]=temp[0];M[3]=temp[1];var out=this._doCryptBlock(M,this._invKeySchedule,G.INV_SUB_MIX,G.INV_SBOX);var buf=new Buffer(16);buf.writeUInt32BE(out[0],0);buf.writeUInt32BE(out[3],4);buf.writeUInt32BE(out[2],8);buf.writeUInt32BE(out[1],12);return buf};AES.prototype.scrub=function(){scrub_vec(this._keySchedule);scrub_vec(this._invKeySchedule);scrub_vec(this._key)};AES.prototype._doCryptBlock=function(M,keySchedule,SUB_MIX,SBOX){var ksRow,s0,s1,s2,s3,t0,t1,t2,t3;s0=M[0]^keySchedule[0];s1=M[1]^keySchedule[1];s2=M[2]^keySchedule[2];s3=M[3]^keySchedule[3];ksRow=4;for(var round=1;round>>24]^SUB_MIX[1][s1>>>16&255]^SUB_MIX[2][s2>>>8&255]^SUB_MIX[3][s3&255]^keySchedule[ksRow++];t1=SUB_MIX[0][s1>>>24]^SUB_MIX[1][s2>>>16&255]^SUB_MIX[2][s3>>>8&255]^SUB_MIX[3][s0&255]^keySchedule[ksRow++];t2=SUB_MIX[0][s2>>>24]^SUB_MIX[1][s3>>>16&255]^SUB_MIX[2][s0>>>8&255]^SUB_MIX[3][s1&255]^keySchedule[ksRow++];t3=SUB_MIX[0][s3>>>24]^SUB_MIX[1][s0>>>16&255]^SUB_MIX[2][s1>>>8&255]^SUB_MIX[3][s2&255]^keySchedule[ksRow++];s0=t0;s1=t1;s2=t2;s3=t3}t0=(SBOX[s0>>>24]<<24|SBOX[s1>>>16&255]<<16|SBOX[s2>>>8&255]<<8|SBOX[s3&255])^keySchedule[ksRow++];t1=(SBOX[s1>>>24]<<24|SBOX[s2>>>16&255]<<16|SBOX[s3>>>8&255]<<8|SBOX[s0&255])^keySchedule[ksRow++];t2=(SBOX[s2>>>24]<<24|SBOX[s3>>>16&255]<<16|SBOX[s0>>>8&255]<<8|SBOX[s1&255])^keySchedule[ksRow++];t3=(SBOX[s3>>>24]<<24|SBOX[s0>>>16&255]<<16|SBOX[s1>>>8&255]<<8|SBOX[s2&255])^keySchedule[ksRow++];return[fixup_uint32(t0),fixup_uint32(t1),fixup_uint32(t2),fixup_uint32(t3)]};exports.AES=AES}).call(this,require("buffer").Buffer)},{buffer:2}],9:[function(require,module,exports){(function(Buffer){var aes=require("./aes");var Transform=require("cipher-base");var inherits=require("inherits");var GHASH=require("./ghash");var xor=require("buffer-xor");inherits(StreamCipher,Transform);module.exports=StreamCipher;function StreamCipher(mode,key,iv,decrypt){if(!(this instanceof StreamCipher)){return new StreamCipher(mode,key,iv)}Transform.call(this);this._finID=Buffer.concat([iv,new Buffer([0,0,0,1])]);iv=Buffer.concat([iv,new Buffer([0,0,0,2])]);this._cipher=new aes.AES(key);this._prev=new Buffer(iv.length);this._cache=new Buffer("");this._secCache=new Buffer("");this._decrypt=decrypt;this._alen=0;this._len=0;iv.copy(this._prev);this._mode=mode;var h=new Buffer(4);h.fill(0);this._ghash=new GHASH(this._cipher.encryptBlock(h));this._authTag=null;this._called=false}StreamCipher.prototype._update=function(chunk){if(!this._called&&this._alen){var rump=16-this._alen%16;if(rump<16){rump=new Buffer(rump);rump.fill(0);this._ghash.update(rump)}}this._called=true;var out=this._mode.encrypt(this,chunk);if(this._decrypt){this._ghash.update(chunk)}else{this._ghash.update(out)}this._len+=chunk.length;return out};StreamCipher.prototype._final=function(){if(this._decrypt&&!this._authTag){throw new Error("Unsupported state or unable to authenticate data")}var tag=xor(this._ghash.final(this._alen*8,this._len*8),this._cipher.encryptBlock(this._finID));if(this._decrypt){if(xorTest(tag,this._authTag)){throw new Error("Unsupported state or unable to authenticate data")}}else{this._authTag=tag}this._cipher.scrub()};StreamCipher.prototype.getAuthTag=function getAuthTag(){if(!this._decrypt&&Buffer.isBuffer(this._authTag)){return this._authTag}else{throw new Error("Attempting to get auth tag in unsupported state")}};StreamCipher.prototype.setAuthTag=function setAuthTag(tag){if(this._decrypt){this._authTag=tag}else{throw new Error("Attempting to set auth tag in unsupported state")}};StreamCipher.prototype.setAAD=function setAAD(buf){if(!this._called){this._ghash.update(buf);this._alen+=buf.length}else{throw new Error("Attempting to set AAD in unsupported state")}};function xorTest(a,b){var out=0;if(a.length!==b.length){out++}var len=Math.min(a.length,b.length);var i=-1;while(++i16){out=this.cache.slice(0,16);this.cache=this.cache.slice(16);return out}}else{if(this.cache.length>=16){out=this.cache.slice(0,16);this.cache=this.cache.slice(16);return out}}return null};Splitter.prototype.flush=function(){if(this.cache.length){return this.cache}};function unpad(last){var padded=last[15];var i=-1;while(++i15){var out=this.cache.slice(0,16);this.cache=this.cache.slice(16);return out}return null};Splitter.prototype.flush=function(){var len=16-this.cache.length;var padBuff=new Buffer(len);var i=-1;while(++i0;j--){Vi[j]=Vi[j]>>>1|(Vi[j-1]&1)<<31}Vi[0]=Vi[0]>>>1;if(lsb_Vi){Vi[0]=Vi[0]^225<<24}}this.state=fromArray(Zi)};GHASH.prototype.update=function(buf){this.cache=Buffer.concat([this.cache,buf]);var chunk;while(this.cache.length>=16){chunk=this.cache.slice(0,16);this.cache=this.cache.slice(16);this.ghash(chunk)}};GHASH.prototype.final=function(abl,bl){if(this.cache.length){this.ghash(Buffer.concat([this.cache,zeros],16))}this.ghash(fromArray([0,abl,0,bl]));return this.state};function toArray(buf){return[buf.readUInt32BE(0),buf.readUInt32BE(4),buf.readUInt32BE(8),buf.readUInt32BE(12)]}function fromArray(out){out=out.map(fixup_uint32);var buf=new Buffer(16);buf.writeUInt32BE(out[0],0);buf.writeUInt32BE(out[1],4);buf.writeUInt32BE(out[2],8);buf.writeUInt32BE(out[3],12);return buf}var uint_max=Math.pow(2,32);function fixup_uint32(x){var ret,x_pos;ret=x>uint_max||x<0?(x_pos=Math.abs(x)%uint_max,x<0?uint_max-x_pos:x_pos):x;return ret}function xor(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[3]]}}).call(this,require("buffer").Buffer)},{buffer:2}],14:[function(require,module,exports){exports["aes-128-ecb"]={cipher:"AES",key:128,iv:0,mode:"ECB",type:"block"};exports["aes-192-ecb"]={cipher:"AES",key:192,iv:0,mode:"ECB",type:"block"};exports["aes-256-ecb"]={cipher:"AES",key:256,iv:0,mode:"ECB",type:"block"};exports["aes-128-cbc"]={cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"};exports["aes-192-cbc"]={cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"};exports["aes-256-cbc"]={cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"};exports["aes128"]=exports["aes-128-cbc"];exports["aes192"]=exports["aes-192-cbc"];exports["aes256"]=exports["aes-256-cbc"];exports["aes-128-cfb"]={cipher:"AES",key:128,iv:16,mode:"CFB",type:"stream"};exports["aes-192-cfb"]={cipher:"AES",key:192,iv:16,mode:"CFB",type:"stream"};exports["aes-256-cfb"]={cipher:"AES",key:256,iv:16,mode:"CFB",type:"stream"};exports["aes-128-cfb8"]={cipher:"AES",key:128,iv:16,mode:"CFB8",type:"stream"};exports["aes-192-cfb8"]={cipher:"AES",key:192,iv:16,mode:"CFB8",type:"stream"};exports["aes-256-cfb8"]={cipher:"AES",key:256,iv:16,mode:"CFB8",type:"stream"};exports["aes-128-cfb1"]={cipher:"AES",key:128,iv:16,mode:"CFB1",type:"stream"};exports["aes-192-cfb1"]={cipher:"AES",key:192,iv:16,mode:"CFB1",type:"stream"};exports["aes-256-cfb1"]={cipher:"AES",key:256,iv:16,mode:"CFB1",type:"stream"};exports["aes-128-ofb"]={cipher:"AES",key:128,iv:16,mode:"OFB",type:"stream"};exports["aes-192-ofb"]={cipher:"AES",key:192,iv:16,mode:"OFB",type:"stream"};exports["aes-256-ofb"]={cipher:"AES",key:256,iv:16,mode:"OFB",type:"stream"};exports["aes-128-ctr"]={cipher:"AES",key:128,iv:16,mode:"CTR",type:"stream"};exports["aes-192-ctr"]={cipher:"AES",key:192,iv:16,mode:"CTR",type:"stream"};exports["aes-256-ctr"]={cipher:"AES",key:256,iv:16,mode:"CTR",type:"stream"};exports["aes-128-gcm"]={cipher:"AES",key:128,iv:12,mode:"GCM",type:"auth"};exports["aes-192-gcm"]={cipher:"AES",key:192,iv:12,mode:"GCM",type:"auth"};exports["aes-256-gcm"]={cipher:"AES",key:256,iv:12,mode:"GCM",type:"auth"}},{}],15:[function(require,module,exports){var xor=require("buffer-xor");exports.encrypt=function(self,block){var data=xor(block,self._prev);self._prev=self._cipher.encryptBlock(data);return self._prev};exports.decrypt=function(self,block){var pad=self._prev;self._prev=block;var out=self._cipher.decryptBlock(block);return xor(out,pad)}},{"buffer-xor":22}],16:[function(require,module,exports){(function(Buffer){var xor=require("buffer-xor");exports.encrypt=function(self,data,decrypt){var out=new Buffer("");var len;while(data.length){if(self._cache.length===0){self._cache=self._cipher.encryptBlock(self._prev);self._prev=new Buffer("")}if(self._cache.length<=data.length){len=self._cache.length;out=Buffer.concat([out,encryptStart(self,data.slice(0,len),decrypt)]);data=data.slice(len)}else{out=Buffer.concat([out,encryptStart(self,data,decrypt)]);break}}return out};function encryptStart(self,data,decrypt){var len=data.length;var out=xor(data,self._cache);self._cache=self._cache.slice(len);self._prev=Buffer.concat([self._prev,decrypt?data:out]);return out}}).call(this,require("buffer").Buffer)},{buffer:2,"buffer-xor":22}],17:[function(require,module,exports){(function(Buffer){function encryptByte(self,byteParam,decrypt){var pad;var i=-1;var len=8;var out=0;var bit,value;while(++i>i%8;self._prev=shiftIn(self._prev,decrypt?bit:value)}return out}exports.encrypt=function(self,chunk,decrypt){var len=chunk.length;var out=new Buffer(len);var i=-1;while(++i>7}return out}}).call(this,require("buffer").Buffer)},{buffer:2}],18:[function(require,module,exports){(function(Buffer){function encryptByte(self,byteParam,decrypt){var pad=self._cipher.encryptBlock(self._prev);var out=pad[0]^byteParam;self._prev=Buffer.concat([self._prev.slice(1),new Buffer([decrypt?byteParam:out])]);return out}exports.encrypt=function(self,chunk,decrypt){var len=chunk.length;var out=new Buffer(len);var i=-1;while(++i0;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>>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>>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)}},{"../des":28,inherits:204,"minimalistic-assert":34}],32:[function(require,module,exports){"use strict";var assert=require("minimalistic-assert");var inherits=require("inherits");var des=require("../des");var Cipher=des.Cipher;var DES=des.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},{"../des":28,inherits:204,"minimalistic-assert":34}],33:[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<>>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>>pc2table[i]&1}for(var i=len;i>>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[i]&1}return out>>>0};exports.padSplit=function padSplit(num,size,group){var str=num.toString(2);while(str.length0){bufs.push(md_buf)}bufs.push(password);if(salt){bufs.push(salt)}md_buf=md5(Buffer.concat(bufs));bufs=[];i=0;if(keyLen>0){while(true){if(keyLen===0){break}if(i===md_buf.length){break}key[ki++]=md_buf[i];keyLen--;i++}}if(ivLen>0&&i!==md_buf.length){while(true){if(ivLen===0){break}if(i===md_buf.length){break}iv[ii++]=md_buf[i];ivLen--;i++}}if(keyLen===0&&ivLen===0){break}}for(i=0;i0)return left;return right};BN.min=function min(left,right){if(left.cmp(right)<0)return left;return right};BN.prototype._init=function init(number,base,endian){if(typeof number==="number"){return this._initNumber(number,base,endian)}if(typeof number==="object"){return this._initArray(number,base,endian)}if(base==="hex"){base=16}assert(base===(base|0)&&base>=2&&base<=36);number=number.toString().replace(/\s+/g,"");var start=0;if(number[0]==="-"){start++}if(base===16){this._parseHex(number,start)}else{this._parseBase(number,base,start)}if(number[0]==="-"){this.negative=1}this.strip();if(endian!=="le")return;this._initArray(this.toArray(),base,endian)};BN.prototype._initNumber=function _initNumber(number,base,endian){if(number<0){this.negative=1;number=-number}if(number<67108864){this.words=[number&67108863];this.length=1}else if(number<4503599627370496){this.words=[number&67108863,number/67108864&67108863];this.length=2}else{assert(number<9007199254740992);this.words=[number&67108863,number/67108864&67108863,1];this.length=3}if(endian!=="le")return;this._initArray(this.toArray(),base,endian)};BN.prototype._initArray=function _initArray(number,base,endian){assert(typeof number.length==="number");if(number.length<=0){this.words=[0];this.length=1;return this}this.length=Math.ceil(number.length/3);this.words=new Array(this.length);for(var i=0;i=0;i-=3){w=number[i]|number[i-1]<<8|number[i-2]<<16;this.words[j]|=w<>>26-off&67108863;off+=24;if(off>=26){off-=26;j++}}}else if(endian==="le"){for(i=0,j=0;i>>26-off&67108863;off+=24;if(off>=26){off-=26;j++}}}return this.strip()};function parseHex(str,start,end){var r=0;var len=Math.min(str.length,end);for(var i=start;i=49&&c<=54){r|=c-49+10}else if(c>=17&&c<=22){r|=c-17+10}else{r|=c&15}}return r}BN.prototype._parseHex=function _parseHex(number,start){this.length=Math.ceil((number.length-start)/6);this.words=new Array(this.length);for(var i=0;i=start;i-=6){w=parseHex(number,i,i+6);this.words[j]|=w<>>26-off&4194303;off+=24;if(off>=26){off-=26;j++}}if(i+6!==start){w=parseHex(number,start,i+6);this.words[j]|=w<>>26-off&4194303}this.strip()};function parseBase(str,start,end,mul){var r=0;var len=Math.min(str.length,end);for(var i=start;i=49){r+=c-49+10}else if(c>=17){r+=c-17+10}else{r+=c}}return r}BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0];this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base){limbLen++}limbLen--;limbPow=limbPow/base|0;var total=number.length-start;var mod=total%limbLen;var end=Math.min(total,total-mod)+start;var word=0;for(var i=start;i1&&this.words[this.length-1]===0){this.length--}return this._normSign()};BN.prototype._normSign=function _normSign(){if(this.length===1&&this.words[0]===0){this.negative=0}return this};BN.prototype.inspect=function inspect(){return(this.red?""};var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"];var groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5];var groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function toString(base,padding){base=base||10;padding=padding|0||1;var out;if(base===16||base==="hex"){out="";var off=0;var carry=0;for(var i=0;i>>24-off&16777215;if(carry!==0||i!==this.length-1){out=zeros[6-word.length]+word+out}else{out=word+out}off+=2;if(off>=26){off-=26;i--}}if(carry!==0){out=carry.toString(16)+out}while(out.length%padding!==0){out="0"+out}if(this.negative!==0){out="-"+out}return out}if(base===(base|0)&&base>=2&&base<=36){var groupSize=groupSizes[base];var groupBase=groupBases[base];out="";var c=this.clone();c.negative=0;while(!c.isZero()){var r=c.modn(groupBase).toString(base);c=c.idivn(groupBase);if(!c.isZero()){out=zeros[groupSize-r.length]+r+out}else{out=r+out}}if(this.isZero()){out="0"+out}while(out.length%padding!==0){out="0"+out}if(this.negative!==0){out="-"+out}return out}assert(false,"Base should be between 2 and 36")};BN.prototype.toNumber=function toNumber(){var ret=this.words[0];if(this.length===2){ret+=this.words[1]*67108864}else if(this.length===3&&this.words[2]===1){ret+=4503599627370496+this.words[1]*67108864}else if(this.length>2){assert(false,"Number can only safely store up to 53 bits")}return this.negative!==0?-ret:ret};BN.prototype.toJSON=function toJSON(){return this.toString(16)};BN.prototype.toBuffer=function toBuffer(endian,length){assert(typeof Buffer!=="undefined");return this.toArrayLike(Buffer,endian,length)};BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)};BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){var byteLength=this.byteLength();var reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length");assert(reqLength>0,"Requested array length <= 0");this.strip();var littleEndian=endian==="le";var res=new ArrayType(reqLength);var b,i;var q=this.clone();if(!littleEndian){for(i=0;i=4096){r+=13;t>>>=13}if(t>=64){r+=7;t>>>=7}if(t>=8){r+=4;t>>>=4}if(t>=2){r+=2;t>>>=2}return r+t}}BN.prototype._zeroBits=function _zeroBits(w){if(w===0)return 26;var t=w;var r=0;if((t&8191)===0){r+=13;t>>>=13}if((t&127)===0){r+=7;t>>>=7}if((t&15)===0){r+=4;t>>>=4}if((t&3)===0){r+=2;t>>>=2}if((t&1)===0){r++}return r};BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1];var hi=this._countBits(w);return(this.length-1)*26+hi};function toBitArray(num){var w=new Array(num.bitLength());for(var bit=0;bit>>wbit}return w}BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;var r=0;for(var i=0;inum.length)return this.clone().ior(num);return num.clone().ior(this)};BN.prototype.uor=function uor(num){if(this.length>num.length)return this.clone().iuor(num);return num.clone().iuor(this)};BN.prototype.iuand=function iuand(num){var b;if(this.length>num.length){b=num}else{b=this}for(var i=0;inum.length)return this.clone().iand(num);return num.clone().iand(this)};BN.prototype.uand=function uand(num){if(this.length>num.length)return this.clone().iuand(num);return num.clone().iuand(this)};BN.prototype.iuxor=function iuxor(num){var a;var b;if(this.length>num.length){a=this;b=num}else{a=num;b=this}for(var i=0;inum.length)return this.clone().ixor(num);return num.clone().ixor(this)};BN.prototype.uxor=function uxor(num){if(this.length>num.length)return this.clone().iuxor(num);return num.clone().iuxor(this)};BN.prototype.inotn=function inotn(width){assert(typeof width==="number"&&width>=0);var bytesNeeded=Math.ceil(width/26)|0;var bitsLeft=width%26;this._expand(bytesNeeded);if(bitsLeft>0){bytesNeeded--}for(var i=0;i0){this.words[i]=~this.words[i]&67108863>>26-bitsLeft}return this.strip()};BN.prototype.notn=function notn(width){return this.clone().inotn(width)};BN.prototype.setn=function setn(bit,val){assert(typeof bit==="number"&&bit>=0);var off=bit/26|0;var wbit=bit%26;this._expand(off+1);if(val){this.words[off]=this.words[off]|1<num.length){a=this;b=num}else{a=num;b=this}var carry=0;for(var i=0;i>>26}for(;carry!==0&&i>>26}this.length=a.length ;if(carry!==0){this.words[this.length]=carry;this.length++}else if(a!==this){for(;inum.length)return this.clone().iadd(num);return num.clone().iadd(this)};BN.prototype.isub=function isub(num){if(num.negative!==0){num.negative=0;var r=this.iadd(num);num.negative=1;return r._normSign()}else if(this.negative!==0){this.negative=0;this.iadd(num);this.negative=1;return this._normSign()}var cmp=this.cmp(num);if(cmp===0){this.negative=0;this.length=1;this.words[0]=0;return this}var a,b;if(cmp>0){a=this;b=num}else{a=num;b=this}var carry=0;for(var i=0;i>26;this.words[i]=r&67108863}for(;carry!==0&&i>26;this.words[i]=r&67108863}if(carry===0&&i>>26;var rword=carry&67108863;var maxJ=Math.min(k,num.length-1);for(var j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;a=self.words[i]|0;b=num.words[j]|0;r=a*b+rword;ncarry+=r/67108864|0;rword=r&67108863}out.words[k]=rword|0;carry=ncarry|0}if(carry!==0){out.words[k]=carry|0}else{out.length--}return out.strip()}var comb10MulTo=function comb10MulTo(self,num,out){var a=self.words;var b=num.words;var o=out.words;var c=0;var lo;var mid;var hi;var a0=a[0]|0;var al0=a0&8191;var ah0=a0>>>13;var a1=a[1]|0;var al1=a1&8191;var ah1=a1>>>13;var a2=a[2]|0;var al2=a2&8191;var ah2=a2>>>13;var a3=a[3]|0;var al3=a3&8191;var ah3=a3>>>13;var a4=a[4]|0;var al4=a4&8191;var ah4=a4>>>13;var a5=a[5]|0;var al5=a5&8191;var ah5=a5>>>13;var a6=a[6]|0;var al6=a6&8191;var ah6=a6>>>13;var a7=a[7]|0;var al7=a7&8191;var ah7=a7>>>13;var a8=a[8]|0;var al8=a8&8191;var ah8=a8>>>13;var a9=a[9]|0;var al9=a9&8191;var ah9=a9>>>13;var b0=b[0]|0;var bl0=b0&8191;var bh0=b0>>>13;var b1=b[1]|0;var bl1=b1&8191;var bh1=b1>>>13;var b2=b[2]|0;var bl2=b2&8191;var bh2=b2>>>13;var b3=b[3]|0;var bl3=b3&8191;var bh3=b3>>>13;var b4=b[4]|0;var bl4=b4&8191;var bh4=b4>>>13;var b5=b[5]|0;var bl5=b5&8191;var bh5=b5>>>13;var b6=b[6]|0;var bl6=b6&8191;var bh6=b6>>>13;var b7=b[7]|0;var bl7=b7&8191;var bh7=b7>>>13;var b8=b[8]|0;var bl8=b8&8191;var bh8=b8>>>13;var b9=b[9]|0;var bl9=b9&8191;var bh9=b9>>>13;out.negative=self.negative^num.negative;out.length=19;lo=Math.imul(al0,bl0);mid=Math.imul(al0,bh0);mid=mid+Math.imul(ah0,bl0)|0;hi=Math.imul(ah0,bh0);var w0=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w0>>>26)|0;w0&=67108863;lo=Math.imul(al1,bl0);mid=Math.imul(al1,bh0);mid=mid+Math.imul(ah1,bl0)|0;hi=Math.imul(ah1,bh0);lo=lo+Math.imul(al0,bl1)|0;mid=mid+Math.imul(al0,bh1)|0;mid=mid+Math.imul(ah0,bl1)|0;hi=hi+Math.imul(ah0,bh1)|0;var w1=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w1>>>26)|0;w1&=67108863;lo=Math.imul(al2,bl0);mid=Math.imul(al2,bh0);mid=mid+Math.imul(ah2,bl0)|0;hi=Math.imul(ah2,bh0);lo=lo+Math.imul(al1,bl1)|0;mid=mid+Math.imul(al1,bh1)|0;mid=mid+Math.imul(ah1,bl1)|0;hi=hi+Math.imul(ah1,bh1)|0;lo=lo+Math.imul(al0,bl2)|0;mid=mid+Math.imul(al0,bh2)|0;mid=mid+Math.imul(ah0,bl2)|0;hi=hi+Math.imul(ah0,bh2)|0;var w2=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w2>>>26)|0;w2&=67108863;lo=Math.imul(al3,bl0);mid=Math.imul(al3,bh0);mid=mid+Math.imul(ah3,bl0)|0;hi=Math.imul(ah3,bh0);lo=lo+Math.imul(al2,bl1)|0;mid=mid+Math.imul(al2,bh1)|0;mid=mid+Math.imul(ah2,bl1)|0;hi=hi+Math.imul(ah2,bh1)|0;lo=lo+Math.imul(al1,bl2)|0;mid=mid+Math.imul(al1,bh2)|0;mid=mid+Math.imul(ah1,bl2)|0;hi=hi+Math.imul(ah1,bh2)|0;lo=lo+Math.imul(al0,bl3)|0;mid=mid+Math.imul(al0,bh3)|0;mid=mid+Math.imul(ah0,bl3)|0;hi=hi+Math.imul(ah0,bh3)|0;var w3=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w3>>>26)|0;w3&=67108863;lo=Math.imul(al4,bl0);mid=Math.imul(al4,bh0);mid=mid+Math.imul(ah4,bl0)|0;hi=Math.imul(ah4,bh0);lo=lo+Math.imul(al3,bl1)|0;mid=mid+Math.imul(al3,bh1)|0;mid=mid+Math.imul(ah3,bl1)|0;hi=hi+Math.imul(ah3,bh1)|0;lo=lo+Math.imul(al2,bl2)|0;mid=mid+Math.imul(al2,bh2)|0;mid=mid+Math.imul(ah2,bl2)|0;hi=hi+Math.imul(ah2,bh2)|0;lo=lo+Math.imul(al1,bl3)|0;mid=mid+Math.imul(al1,bh3)|0;mid=mid+Math.imul(ah1,bl3)|0;hi=hi+Math.imul(ah1,bh3)|0;lo=lo+Math.imul(al0,bl4)|0;mid=mid+Math.imul(al0,bh4)|0;mid=mid+Math.imul(ah0,bl4)|0;hi=hi+Math.imul(ah0,bh4)|0;var w4=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w4>>>26)|0;w4&=67108863;lo=Math.imul(al5,bl0);mid=Math.imul(al5,bh0);mid=mid+Math.imul(ah5,bl0)|0;hi=Math.imul(ah5,bh0);lo=lo+Math.imul(al4,bl1)|0;mid=mid+Math.imul(al4,bh1)|0;mid=mid+Math.imul(ah4,bl1)|0;hi=hi+Math.imul(ah4,bh1)|0;lo=lo+Math.imul(al3,bl2)|0;mid=mid+Math.imul(al3,bh2)|0;mid=mid+Math.imul(ah3,bl2)|0;hi=hi+Math.imul(ah3,bh2)|0;lo=lo+Math.imul(al2,bl3)|0;mid=mid+Math.imul(al2,bh3)|0;mid=mid+Math.imul(ah2,bl3)|0;hi=hi+Math.imul(ah2,bh3)|0;lo=lo+Math.imul(al1,bl4)|0;mid=mid+Math.imul(al1,bh4)|0;mid=mid+Math.imul(ah1,bl4)|0;hi=hi+Math.imul(ah1,bh4)|0;lo=lo+Math.imul(al0,bl5)|0;mid=mid+Math.imul(al0,bh5)|0;mid=mid+Math.imul(ah0,bl5)|0;hi=hi+Math.imul(ah0,bh5)|0;var w5=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w5>>>26)|0;w5&=67108863;lo=Math.imul(al6,bl0);mid=Math.imul(al6,bh0);mid=mid+Math.imul(ah6,bl0)|0;hi=Math.imul(ah6,bh0);lo=lo+Math.imul(al5,bl1)|0;mid=mid+Math.imul(al5,bh1)|0;mid=mid+Math.imul(ah5,bl1)|0;hi=hi+Math.imul(ah5,bh1)|0;lo=lo+Math.imul(al4,bl2)|0;mid=mid+Math.imul(al4,bh2)|0;mid=mid+Math.imul(ah4,bl2)|0;hi=hi+Math.imul(ah4,bh2)|0;lo=lo+Math.imul(al3,bl3)|0;mid=mid+Math.imul(al3,bh3)|0;mid=mid+Math.imul(ah3,bl3)|0;hi=hi+Math.imul(ah3,bh3)|0;lo=lo+Math.imul(al2,bl4)|0;mid=mid+Math.imul(al2,bh4)|0;mid=mid+Math.imul(ah2,bl4)|0;hi=hi+Math.imul(ah2,bh4)|0;lo=lo+Math.imul(al1,bl5)|0;mid=mid+Math.imul(al1,bh5)|0;mid=mid+Math.imul(ah1,bl5)|0;hi=hi+Math.imul(ah1,bh5)|0;lo=lo+Math.imul(al0,bl6)|0;mid=mid+Math.imul(al0,bh6)|0;mid=mid+Math.imul(ah0,bl6)|0;hi=hi+Math.imul(ah0,bh6)|0;var w6=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w6>>>26)|0;w6&=67108863;lo=Math.imul(al7,bl0);mid=Math.imul(al7,bh0);mid=mid+Math.imul(ah7,bl0)|0;hi=Math.imul(ah7,bh0);lo=lo+Math.imul(al6,bl1)|0;mid=mid+Math.imul(al6,bh1)|0;mid=mid+Math.imul(ah6,bl1)|0;hi=hi+Math.imul(ah6,bh1)|0;lo=lo+Math.imul(al5,bl2)|0;mid=mid+Math.imul(al5,bh2)|0;mid=mid+Math.imul(ah5,bl2)|0;hi=hi+Math.imul(ah5,bh2)|0;lo=lo+Math.imul(al4,bl3)|0;mid=mid+Math.imul(al4,bh3)|0;mid=mid+Math.imul(ah4,bl3)|0;hi=hi+Math.imul(ah4,bh3)|0;lo=lo+Math.imul(al3,bl4)|0;mid=mid+Math.imul(al3,bh4)|0;mid=mid+Math.imul(ah3,bl4)|0;hi=hi+Math.imul(ah3,bh4)|0;lo=lo+Math.imul(al2,bl5)|0;mid=mid+Math.imul(al2,bh5)|0;mid=mid+Math.imul(ah2,bl5)|0;hi=hi+Math.imul(ah2,bh5)|0;lo=lo+Math.imul(al1,bl6)|0;mid=mid+Math.imul(al1,bh6)|0;mid=mid+Math.imul(ah1,bl6)|0;hi=hi+Math.imul(ah1,bh6)|0;lo=lo+Math.imul(al0,bl7)|0;mid=mid+Math.imul(al0,bh7)|0;mid=mid+Math.imul(ah0,bl7)|0;hi=hi+Math.imul(ah0,bh7)|0;var w7=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w7>>>26)|0;w7&=67108863;lo=Math.imul(al8,bl0);mid=Math.imul(al8,bh0);mid=mid+Math.imul(ah8,bl0)|0;hi=Math.imul(ah8,bh0);lo=lo+Math.imul(al7,bl1)|0;mid=mid+Math.imul(al7,bh1)|0;mid=mid+Math.imul(ah7,bl1)|0;hi=hi+Math.imul(ah7,bh1)|0;lo=lo+Math.imul(al6,bl2)|0;mid=mid+Math.imul(al6,bh2)|0;mid=mid+Math.imul(ah6,bl2)|0;hi=hi+Math.imul(ah6,bh2)|0;lo=lo+Math.imul(al5,bl3)|0;mid=mid+Math.imul(al5,bh3)|0;mid=mid+Math.imul(ah5,bl3)|0;hi=hi+Math.imul(ah5,bh3)|0;lo=lo+Math.imul(al4,bl4)|0;mid=mid+Math.imul(al4,bh4)|0;mid=mid+Math.imul(ah4,bl4)|0;hi=hi+Math.imul(ah4,bh4)|0;lo=lo+Math.imul(al3,bl5)|0;mid=mid+Math.imul(al3,bh5)|0;mid=mid+Math.imul(ah3,bl5)|0;hi=hi+Math.imul(ah3,bh5)|0;lo=lo+Math.imul(al2,bl6)|0;mid=mid+Math.imul(al2,bh6)|0;mid=mid+Math.imul(ah2,bl6)|0;hi=hi+Math.imul(ah2,bh6)|0;lo=lo+Math.imul(al1,bl7)|0;mid=mid+Math.imul(al1,bh7)|0;mid=mid+Math.imul(ah1,bl7)|0;hi=hi+Math.imul(ah1,bh7)|0;lo=lo+Math.imul(al0,bl8)|0;mid=mid+Math.imul(al0,bh8)|0;mid=mid+Math.imul(ah0,bl8)|0;hi=hi+Math.imul(ah0,bh8)|0;var w8=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w8>>>26)|0;w8&=67108863;lo=Math.imul(al9,bl0);mid=Math.imul(al9,bh0);mid=mid+Math.imul(ah9,bl0)|0;hi=Math.imul(ah9,bh0);lo=lo+Math.imul(al8,bl1)|0;mid=mid+Math.imul(al8,bh1)|0;mid=mid+Math.imul(ah8,bl1)|0;hi=hi+Math.imul(ah8,bh1)|0;lo=lo+Math.imul(al7,bl2)|0;mid=mid+Math.imul(al7,bh2)|0;mid=mid+Math.imul(ah7,bl2)|0;hi=hi+Math.imul(ah7,bh2)|0;lo=lo+Math.imul(al6,bl3)|0;mid=mid+Math.imul(al6,bh3)|0;mid=mid+Math.imul(ah6,bl3)|0;hi=hi+Math.imul(ah6,bh3)|0;lo=lo+Math.imul(al5,bl4)|0;mid=mid+Math.imul(al5,bh4)|0;mid=mid+Math.imul(ah5,bl4)|0;hi=hi+Math.imul(ah5,bh4)|0;lo=lo+Math.imul(al4,bl5)|0;mid=mid+Math.imul(al4,bh5)|0;mid=mid+Math.imul(ah4,bl5)|0;hi=hi+Math.imul(ah4,bh5)|0;lo=lo+Math.imul(al3,bl6)|0;mid=mid+Math.imul(al3,bh6)|0;mid=mid+Math.imul(ah3,bl6)|0;hi=hi+Math.imul(ah3,bh6)|0;lo=lo+Math.imul(al2,bl7)|0;mid=mid+Math.imul(al2,bh7)|0;mid=mid+Math.imul(ah2,bl7)|0;hi=hi+Math.imul(ah2,bh7)|0;lo=lo+Math.imul(al1,bl8)|0;mid=mid+Math.imul(al1,bh8)|0;mid=mid+Math.imul(ah1,bl8)|0;hi=hi+Math.imul(ah1,bh8)|0;lo=lo+Math.imul(al0,bl9)|0;mid=mid+Math.imul(al0,bh9)|0;mid=mid+Math.imul(ah0,bl9)|0;hi=hi+Math.imul(ah0,bh9)|0;var w9=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w9>>>26)|0;w9&=67108863;lo=Math.imul(al9,bl1);mid=Math.imul(al9,bh1);mid=mid+Math.imul(ah9,bl1)|0;hi=Math.imul(ah9,bh1);lo=lo+Math.imul(al8,bl2)|0;mid=mid+Math.imul(al8,bh2)|0;mid=mid+Math.imul(ah8,bl2)|0;hi=hi+Math.imul(ah8,bh2)|0;lo=lo+Math.imul(al7,bl3)|0;mid=mid+Math.imul(al7,bh3)|0;mid=mid+Math.imul(ah7,bl3)|0;hi=hi+Math.imul(ah7,bh3)|0;lo=lo+Math.imul(al6,bl4)|0;mid=mid+Math.imul(al6,bh4)|0;mid=mid+Math.imul(ah6,bl4)|0;hi=hi+Math.imul(ah6,bh4)|0;lo=lo+Math.imul(al5,bl5)|0;mid=mid+Math.imul(al5,bh5)|0;mid=mid+Math.imul(ah5,bl5)|0;hi=hi+Math.imul(ah5,bh5)|0;lo=lo+Math.imul(al4,bl6)|0;mid=mid+Math.imul(al4,bh6)|0;mid=mid+Math.imul(ah4,bl6)|0;hi=hi+Math.imul(ah4,bh6)|0;lo=lo+Math.imul(al3,bl7)|0;mid=mid+Math.imul(al3,bh7)|0;mid=mid+Math.imul(ah3,bl7)|0;hi=hi+Math.imul(ah3,bh7)|0;lo=lo+Math.imul(al2,bl8)|0;mid=mid+Math.imul(al2,bh8)|0;mid=mid+Math.imul(ah2,bl8)|0;hi=hi+Math.imul(ah2,bh8)|0;lo=lo+Math.imul(al1,bl9)|0;mid=mid+Math.imul(al1,bh9)|0;mid=mid+Math.imul(ah1,bl9)|0;hi=hi+Math.imul(ah1,bh9)|0;var w10=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w10>>>26)|0;w10&=67108863;lo=Math.imul(al9,bl2);mid=Math.imul(al9,bh2);mid=mid+Math.imul(ah9,bl2)|0;hi=Math.imul(ah9,bh2);lo=lo+Math.imul(al8,bl3)|0;mid=mid+Math.imul(al8,bh3)|0;mid=mid+Math.imul(ah8,bl3)|0;hi=hi+Math.imul(ah8,bh3)|0;lo=lo+Math.imul(al7,bl4)|0;mid=mid+Math.imul(al7,bh4)|0;mid=mid+Math.imul(ah7,bl4)|0;hi=hi+Math.imul(ah7,bh4)|0;lo=lo+Math.imul(al6,bl5)|0;mid=mid+Math.imul(al6,bh5)|0;mid=mid+Math.imul(ah6,bl5)|0;hi=hi+Math.imul(ah6,bh5)|0;lo=lo+Math.imul(al5,bl6)|0;mid=mid+Math.imul(al5,bh6)|0;mid=mid+Math.imul(ah5,bl6)|0;hi=hi+Math.imul(ah5,bh6)|0;lo=lo+Math.imul(al4,bl7)|0;mid=mid+Math.imul(al4,bh7)|0;mid=mid+Math.imul(ah4,bl7)|0;hi=hi+Math.imul(ah4,bh7)|0;lo=lo+Math.imul(al3,bl8)|0;mid=mid+Math.imul(al3,bh8)|0;mid=mid+Math.imul(ah3,bl8)|0;hi=hi+Math.imul(ah3,bh8)|0;lo=lo+Math.imul(al2,bl9)|0;mid=mid+Math.imul(al2,bh9)|0;mid=mid+Math.imul(ah2,bl9)|0;hi=hi+Math.imul(ah2,bh9)|0;var w11=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w11>>>26)|0;w11&=67108863;lo=Math.imul(al9,bl3);mid=Math.imul(al9,bh3);mid=mid+Math.imul(ah9,bl3)|0;hi=Math.imul(ah9,bh3);lo=lo+Math.imul(al8,bl4)|0;mid=mid+Math.imul(al8,bh4)|0;mid=mid+Math.imul(ah8,bl4)|0;hi=hi+Math.imul(ah8,bh4)|0;lo=lo+Math.imul(al7,bl5)|0;mid=mid+Math.imul(al7,bh5)|0;mid=mid+Math.imul(ah7,bl5)|0;hi=hi+Math.imul(ah7,bh5)|0;lo=lo+Math.imul(al6,bl6)|0;mid=mid+Math.imul(al6,bh6)|0;mid=mid+Math.imul(ah6,bl6)|0;hi=hi+Math.imul(ah6,bh6)|0;lo=lo+Math.imul(al5,bl7)|0;mid=mid+Math.imul(al5,bh7)|0;mid=mid+Math.imul(ah5,bl7)|0;hi=hi+Math.imul(ah5,bh7)|0;lo=lo+Math.imul(al4,bl8)|0;mid=mid+Math.imul(al4,bh8)|0;mid=mid+Math.imul(ah4,bl8)|0;hi=hi+Math.imul(ah4,bh8)|0;lo=lo+Math.imul(al3,bl9)|0;mid=mid+Math.imul(al3,bh9)|0;mid=mid+Math.imul(ah3,bl9)|0;hi=hi+Math.imul(ah3,bh9)|0;var w12=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w12>>>26)|0;w12&=67108863;lo=Math.imul(al9,bl4);mid=Math.imul(al9,bh4);mid=mid+Math.imul(ah9,bl4)|0;hi=Math.imul(ah9,bh4);lo=lo+Math.imul(al8,bl5)|0;mid=mid+Math.imul(al8,bh5)|0;mid=mid+Math.imul(ah8,bl5)|0;hi=hi+Math.imul(ah8,bh5)|0;lo=lo+Math.imul(al7,bl6)|0;mid=mid+Math.imul(al7,bh6)|0;mid=mid+Math.imul(ah7,bl6)|0;hi=hi+Math.imul(ah7,bh6)|0;lo=lo+Math.imul(al6,bl7)|0;mid=mid+Math.imul(al6,bh7)|0;mid=mid+Math.imul(ah6,bl7)|0;hi=hi+Math.imul(ah6,bh7)|0;lo=lo+Math.imul(al5,bl8)|0;mid=mid+Math.imul(al5,bh8)|0;mid=mid+Math.imul(ah5,bl8)|0;hi=hi+Math.imul(ah5,bh8)|0;lo=lo+Math.imul(al4,bl9)|0;mid=mid+Math.imul(al4,bh9)|0;mid=mid+Math.imul(ah4,bl9)|0;hi=hi+Math.imul(ah4,bh9)|0;var w13=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w13>>>26)|0;w13&=67108863;lo=Math.imul(al9,bl5);mid=Math.imul(al9,bh5);mid=mid+Math.imul(ah9,bl5)|0;hi=Math.imul(ah9,bh5);lo=lo+Math.imul(al8,bl6)|0;mid=mid+Math.imul(al8,bh6)|0;mid=mid+Math.imul(ah8,bl6)|0;hi=hi+Math.imul(ah8,bh6)|0;lo=lo+Math.imul(al7,bl7)|0;mid=mid+Math.imul(al7,bh7)|0;mid=mid+Math.imul(ah7,bl7)|0;hi=hi+Math.imul(ah7,bh7)|0;lo=lo+Math.imul(al6,bl8)|0;mid=mid+Math.imul(al6,bh8)|0;mid=mid+Math.imul(ah6,bl8)|0;hi=hi+Math.imul(ah6,bh8)|0;lo=lo+Math.imul(al5,bl9)|0;mid=mid+Math.imul(al5,bh9)|0;mid=mid+Math.imul(ah5,bl9)|0;hi=hi+Math.imul(ah5,bh9)|0;var w14=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w14>>>26)|0;w14&=67108863;lo=Math.imul(al9,bl6);mid=Math.imul(al9,bh6);mid=mid+Math.imul(ah9,bl6)|0;hi=Math.imul(ah9,bh6);lo=lo+Math.imul(al8,bl7)|0;mid=mid+Math.imul(al8,bh7)|0;mid=mid+Math.imul(ah8,bl7)|0;hi=hi+Math.imul(ah8,bh7)|0;lo=lo+Math.imul(al7,bl8)|0;mid=mid+Math.imul(al7,bh8)|0;mid=mid+Math.imul(ah7,bl8)|0;hi=hi+Math.imul(ah7,bh8)|0;lo=lo+Math.imul(al6,bl9)|0;mid=mid+Math.imul(al6,bh9)|0;mid=mid+Math.imul(ah6,bl9)|0;hi=hi+Math.imul(ah6,bh9)|0;var w15=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w15>>>26)|0;w15&=67108863;lo=Math.imul(al9,bl7);mid=Math.imul(al9,bh7);mid=mid+Math.imul(ah9,bl7)|0;hi=Math.imul(ah9,bh7);lo=lo+Math.imul(al8,bl8)|0;mid=mid+Math.imul(al8,bh8)|0;mid=mid+Math.imul(ah8,bl8)|0;hi=hi+Math.imul(ah8,bh8)|0;lo=lo+Math.imul(al7,bl9)|0;mid=mid+Math.imul(al7,bh9)|0;mid=mid+Math.imul(ah7,bl9)|0;hi=hi+Math.imul(ah7,bh9)|0;var w16=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w16>>>26)|0;w16&=67108863;lo=Math.imul(al9,bl8);mid=Math.imul(al9,bh8);mid=mid+Math.imul(ah9,bl8)|0;hi=Math.imul(ah9,bh8);lo=lo+Math.imul(al8,bl9)|0;mid=mid+Math.imul(al8,bh9)|0;mid=mid+Math.imul(ah8,bl9)|0;hi=hi+Math.imul(ah8,bh9)|0;var w17=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w17>>>26)|0;w17&=67108863;lo=Math.imul(al9,bl9);mid=Math.imul(al9,bh9);mid=mid+Math.imul(ah9,bl9)|0;hi=Math.imul(ah9,bh9);var w18=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w18>>>26)|0;w18&=67108863;o[0]=w0;o[1]=w1;o[2]=w2;o[3]=w3;o[4]=w4;o[5]=w5;o[6]=w6;o[7]=w7;o[8]=w8;o[9]=w9;o[10]=w10;o[11]=w11;o[12]=w12;o[13]=w13;o[14]=w14;o[15]=w15;o[16]=w16;o[17]=w17;o[18]=w18;if(c!==0){o[19]=c;out.length++}return out};if(!Math.imul){comb10MulTo=smallMulTo}function bigMulTo(self,num,out){out.negative=num.negative^self.negative;out.length=self.length+num.length;var carry=0;var hncarry=0;for(var k=0;k>>26)|0;hncarry+=ncarry>>>26;ncarry&=67108863}out.words[k]=rword;carry=ncarry;ncarry=hncarry}if(carry!==0){out.words[k]=carry}else{out.length--}return out.strip()}function jumboMulTo(self,num,out){var fftm=new FFTM;return fftm.mulp(self,num,out)}BN.prototype.mulTo=function mulTo(num,out){var res;var len=this.length+num.length;if(this.length===10&&num.length===10){res=comb10MulTo(this,num,out)}else if(len<63){res=smallMulTo(this,num,out)}else if(len<1024){res=bigMulTo(this,num,out)}else{res=jumboMulTo(this,num,out)}return res};function FFTM(x,y){this.x=x;this.y=y}FFTM.prototype.makeRBT=function makeRBT(N){var t=new Array(N);var l=BN.prototype._countBits(N)-1;for(var i=0;i>=1}return rb};FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>1){i++}return 1<>>13;rws[2*i+1]=carry&8191;carry=carry>>>13}for(i=2*len;i>=26;carry+=w/67108864|0;carry+=lo>>>26;this.words[i]=lo&67108863}if(carry!==0){this.words[i]=carry;this.length++}return this};BN.prototype.muln=function muln(num){return this.clone().imuln(num)};BN.prototype.sqr=function sqr(){return this.mul(this)};BN.prototype.isqr=function isqr(){return this.imul(this.clone())};BN.prototype.pow=function pow(num){var w=toBitArray(num);if(w.length===0)return new BN(1);var res=this;for(var i=0;i=0);var r=bits%26;var s=(bits-r)/26;var carryMask=67108863>>>26-r<<26-r;var i;if(r!==0){var carry=0;for(i=0;i>>26-r}if(carry){this.words[i]=carry;this.length++}}if(s!==0){for(i=this.length-1;i>=0;i--){this.words[i+s]=this.words[i]}for(i=0;i=0);var h;if(hint){h=(hint-hint%26)/26}else{h=0}var r=bits%26;var s=Math.min((bits-r)/26,this.length);var mask=67108863^67108863>>>r<s){this.length-=s;for(i=0;i=0&&(carry!==0||i>=h);i--){var word=this.words[i]|0;this.words[i]=carry<<26-r|word>>>r;carry=word&mask}if(maskedWords&&carry!==0){maskedWords.words[maskedWords.length++]=carry}if(this.length===0){this.words[0]=0;this.length=1}return this.strip()};BN.prototype.ishrn=function ishrn(bits,hint,extended){assert(this.negative===0);return this.iushrn(bits,hint,extended)};BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)};BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)};BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)};BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)};BN.prototype.testn=function testn(bit){assert(typeof bit==="number"&&bit>=0);var r=bit%26;var s=(bit-r)/26;var q=1<=0);var r=bits%26;var s=(bits-r)/26;assert(this.negative===0,"imaskn works only with positive numbers");if(this.length<=s){return this}if(r!==0){s++}this.length=Math.min(s,this.length);if(r!==0){var mask=67108863^67108863>>>r<=67108864;i++){this.words[i]-=67108864;if(i===this.length-1){this.words[i+1]=1}else{this.words[i+1]++}}this.length=Math.max(this.length,i+1);return this};BN.prototype.isubn=function isubn(num){assert(typeof num==="number");assert(num<67108864);if(num<0)return this.iaddn(-num);if(this.negative!==0){this.negative=0;this.iaddn(num);this.negative=1;return this}this.words[0]-=num;if(this.length===1&&this.words[0]<0){this.words[0]=-this.words[0];this.negative=1}else{for(var i=0;i>26)-(right/67108864|0);this.words[i+shift]=w&67108863}for(;i>26;this.words[i+shift]=w&67108863}if(carry===0)return this.strip();assert(carry===-1);carry=0;for(i=0;i>26;this.words[i]=w&67108863}this.negative=1;return this.strip()};BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=this.length-num.length;var a=this.clone();var b=num;var bhi=b.words[b.length-1]|0;var bhiBits=this._countBits(bhi);shift=26-bhiBits;if(shift!==0){b=b.ushln(shift);a.iushln(shift);bhi=b.words[b.length-1]|0}var m=a.length-b.length;var q;if(mode!=="mod"){q=new BN(null);q.length=m+1;q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=(a.words[b.length+j]|0)*67108864+(a.words[b.length+j-1]|0);qj=Math.min(qj/bhi|0,67108863);a._ishlnsubmul(b,qj,j);while(a.negative!==0){qj--;a.negative=0;a._ishlnsubmul(b,1,j);if(!a.isZero()){a.negative^=1}}if(q){q.words[j]=qj}}if(q){q.strip()}a.strip();if(mode!=="div"&&shift!==0){a.iushrn(shift)}return{div:q||null,mod:a}};BN.prototype.divmod=function divmod(num,mode,positive){assert(!num.isZero());if(this.isZero()){return{div:new BN(0),mod:new BN(0)}}var div,mod,res;if(this.negative!==0&&num.negative===0){res=this.neg().divmod(num,mode);if(mode!=="mod"){div=res.div.neg()}if(mode!=="div"){mod=res.mod.neg();if(positive&&mod.negative!==0){mod.iadd(num)}}return{div:div,mod:mod}}if(this.negative===0&&num.negative!==0){res=this.divmod(num.neg(),mode);if(mode!=="mod"){div=res.div.neg()}return{div:div,mod:res.mod}}if((this.negative&num.negative)!==0){res=this.neg().divmod(num.neg(),mode);if(mode!=="div"){mod=res.mod.neg();if(positive&&mod.negative!==0){mod.isub(num)}}return{div:res.div,mod:mod}}if(num.length>this.length||this.cmp(num)<0){return{div:new BN(0),mod:this}}if(num.length===1){if(mode==="div"){return{div:this.divn(num.words[0]),mod:null}}if(mode==="mod"){return{div:null,mod:new BN(this.modn(num.words[0]))}}return{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}}return this._wordDiv(num,mode)};BN.prototype.div=function div(num){return this.divmod(num,"div",false).div};BN.prototype.mod=function mod(num){return this.divmod(num,"mod",false).mod};BN.prototype.umod=function umod(num){return this.divmod(num,"mod",true).mod};BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=dm.div.negative!==0?dm.mod.isub(num):dm.mod;var half=num.ushrn(1);var r2=num.andln(1);var cmp=mod.cmp(half);if(cmp<0||r2===1&&cmp===0)return dm.div;return dm.div.negative!==0?dm.div.isubn(1):dm.div.iaddn(1)};BN.prototype.modn=function modn(num){assert(num<=67108863);var p=(1<<26)%num;var acc=0;for(var i=this.length-1;i>=0;i--){acc=(p*acc+(this.words[i]|0))%num}return acc};BN.prototype.idivn=function idivn(num){assert(num<=67108863);var carry=0;for(var i=this.length-1;i>=0;i--){var w=(this.words[i]|0)+carry*67108864;this.words[i]=w/num|0;carry=w%num}return this.strip()};BN.prototype.divn=function divn(num){return this.clone().idivn(num)};BN.prototype.egcd=function egcd(p){assert(p.negative===0);assert(!p.isZero());var x=this;var y=p.clone();if(x.negative!==0){x=x.umod(p)}else{x=x.clone()}var A=new BN(1);var B=new BN(0);var C=new BN(0);var D=new BN(1);var g=0;while(x.isEven()&&y.isEven()){x.iushrn(1);y.iushrn(1);++g}var yp=y.clone();var xp=x.clone();while(!x.isZero()){for(var i=0,im=1;(x.words[0]&im)===0&&i<26;++i,im<<=1);if(i>0){x.iushrn(i);while(i-- >0){if(A.isOdd()||B.isOdd()){A.iadd(yp);B.isub(xp)}A.iushrn(1);B.iushrn(1)}}for(var j=0,jm=1;(y.words[0]&jm)===0&&j<26;++j,jm<<=1);if(j>0){y.iushrn(j);while(j-- >0){if(C.isOdd()||D.isOdd()){C.iadd(yp);D.isub(xp)}C.iushrn(1);D.iushrn(1)}}if(x.cmp(y)>=0){x.isub(y);A.isub(C);B.isub(D)}else{y.isub(x);C.isub(A);D.isub(B)}}return{a:C,b:D,gcd:y.iushln(g)}};BN.prototype._invmp=function _invmp(p){assert(p.negative===0);assert(!p.isZero());var a=this;var b=p.clone();if(a.negative!==0){a=a.umod(p)}else{a=a.clone()}var x1=new BN(1);var x2=new BN(0);var delta=b.clone();while(a.cmpn(1)>0&&b.cmpn(1)>0){for(var i=0,im=1;(a.words[0]&im)===0&&i<26;++i,im<<=1);if(i>0){a.iushrn(i);while(i-- >0){if(x1.isOdd()){x1.iadd(delta)}x1.iushrn(1)}}for(var j=0,jm=1;(b.words[0]&jm)===0&&j<26;++j,jm<<=1);if(j>0){b.iushrn(j);while(j-- >0){if(x2.isOdd()){x2.iadd(delta)}x2.iushrn(1)}}if(a.cmp(b)>=0){a.isub(b);x1.isub(x2)}else{b.isub(a);x2.isub(x1)}}var res;if(a.cmpn(1)===0){res=x1}else{res=x2}if(res.cmpn(0)<0){res.iadd(p)}return res};BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone();var b=num.clone();a.negative=0;b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++){a.iushrn(1);b.iushrn(1)}do{while(a.isEven()){a.iushrn(1)}while(b.isEven()){b.iushrn(1)}var r=a.cmp(b);if(r<0){var t=a;a=b;b=t}else if(r===0||b.cmpn(1)===0){break}a.isub(b)}while(true);return b.iushln(shift)};BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)};BN.prototype.isEven=function isEven(){return(this.words[0]&1)===0};BN.prototype.isOdd=function isOdd(){return(this.words[0]&1)===1};BN.prototype.andln=function andln(num){return this.words[0]&num};BN.prototype.bincn=function bincn(bit){assert(typeof bit==="number");var r=bit%26;var s=(bit-r)/26;var q=1<>>26;w&=67108863;this.words[i]=w}if(carry!==0){this.words[i]=carry;this.length++}return this};BN.prototype.isZero=function isZero(){return this.length===1&&this.words[0]===0};BN.prototype.cmpn=function cmpn(num){var negative=num<0;if(this.negative!==0&&!negative)return-1;if(this.negative===0&&negative)return 1;this.strip();var res;if(this.length>1){res=1}else{if(negative){num=-num}assert(num<=67108863,"Number is too big");var w=this.words[0]|0;res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=this.words[i]|0;var b=num.words[i]|0;if(a===b)continue;if(ab){res=1}break}return res};BN.prototype.gtn=function gtn(num){return this.cmpn(num)===1};BN.prototype.gt=function gt(num){return this.cmp(num)===1};BN.prototype.gten=function gten(num){return this.cmpn(num)>=0};BN.prototype.gte=function gte(num){return this.cmp(num)>=0};BN.prototype.ltn=function ltn(num){return this.cmpn(num)===-1};BN.prototype.lt=function lt(num){return this.cmp(num)===-1};BN.prototype.lten=function lten(num){return this.cmpn(num)<=0};BN.prototype.lte=function lte(num){return this.cmp(num)<=0};BN.prototype.eqn=function eqn(num){return this.cmpn(num)===0};BN.prototype.eq=function eq(num){return this.cmp(num)===0};BN.red=function red(num){return new Red(num)};BN.prototype.toRed=function toRed(ctx){assert(!this.red,"Already a number in reduction context");assert(this.negative===0,"red works only with positives");return ctx.convertTo(this)._forceRed(ctx)};BN.prototype.fromRed=function fromRed(){assert(this.red,"fromRed works only with numbers in reduction context") ;return this.red.convertFrom(this)};BN.prototype._forceRed=function _forceRed(ctx){this.red=ctx;return this};BN.prototype.forceRed=function forceRed(ctx){assert(!this.red,"Already a number in reduction context");return this._forceRed(ctx)};BN.prototype.redAdd=function redAdd(num){assert(this.red,"redAdd works only with red numbers");return this.red.add(this,num)};BN.prototype.redIAdd=function redIAdd(num){assert(this.red,"redIAdd works only with red numbers");return this.red.iadd(this,num)};BN.prototype.redSub=function redSub(num){assert(this.red,"redSub works only with red numbers");return this.red.sub(this,num)};BN.prototype.redISub=function redISub(num){assert(this.red,"redISub works only with red numbers");return this.red.isub(this,num)};BN.prototype.redShl=function redShl(num){assert(this.red,"redShl works only with red numbers");return this.red.shl(this,num)};BN.prototype.redMul=function redMul(num){assert(this.red,"redMul works only with red numbers");this.red._verify2(this,num);return this.red.mul(this,num)};BN.prototype.redIMul=function redIMul(num){assert(this.red,"redMul works only with red numbers");this.red._verify2(this,num);return this.red.imul(this,num)};BN.prototype.redSqr=function redSqr(){assert(this.red,"redSqr works only with red numbers");this.red._verify1(this);return this.red.sqr(this)};BN.prototype.redISqr=function redISqr(){assert(this.red,"redISqr works only with red numbers");this.red._verify1(this);return this.red.isqr(this)};BN.prototype.redSqrt=function redSqrt(){assert(this.red,"redSqrt works only with red numbers");this.red._verify1(this);return this.red.sqrt(this)};BN.prototype.redInvm=function redInvm(){assert(this.red,"redInvm works only with red numbers");this.red._verify1(this);return this.red.invm(this)};BN.prototype.redNeg=function redNeg(){assert(this.red,"redNeg works only with red numbers");this.red._verify1(this);return this.red.neg(this)};BN.prototype.redPow=function redPow(num){assert(this.red&&!num.red,"redPow(normalNum)");this.red._verify1(this);return this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name;this.p=new BN(p,16);this.n=this.p.bitLength();this.k=new BN(1).iushln(this.n).isub(this.p);this.tmp=this._tmp()}MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);tmp.words=new Array(Math.ceil(this.n/13));return tmp};MPrime.prototype.ireduce=function ireduce(num){var r=num;var rlen;do{this.split(r,this.tmp);r=this.imulK(r);r=r.iadd(this.tmp);rlen=r.bitLength()}while(rlen>this.n);var cmp=rlen0){r.isub(this.p)}else{r.strip()}return r};MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)};MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)};function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}inherits(K256,MPrime);K256.prototype.split=function split(input,output){var mask=4194303;var outLen=Math.min(input.length,9);for(var i=0;i>>22;prev=next}prev>>>=22;input.words[i-10]=prev;if(prev===0&&input.length>10){input.length-=10}else{input.length-=9}};K256.prototype.imulK=function imulK(num){num.words[num.length]=0;num.words[num.length+1]=0;num.length+=2;var lo=0;for(var i=0;i>>=26;num.words[i]=lo;carry=hi}if(carry!==0){num.words[num.length++]=carry}return num};BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if(name==="k256"){prime=new K256}else if(name==="p224"){prime=new P224}else if(name==="p192"){prime=new P192}else if(name==="p25519"){prime=new P25519}else{throw new Error("Unknown prime "+name)}primes[name]=prime;return prime};function Red(m){if(typeof m==="string"){var prime=BN._prime(m);this.m=prime.p;this.prime=prime}else{assert(m.gtn(1),"modulus must be greater than 1");this.m=m;this.prime=null}}Red.prototype._verify1=function _verify1(a){assert(a.negative===0,"red works only with positives");assert(a.red,"red works only with red numbers")};Red.prototype._verify2=function _verify2(a,b){assert((a.negative|b.negative)===0,"red works only with positives");assert(a.red&&a.red===b.red,"red works only with red numbers")};Red.prototype.imod=function imod(a){if(this.prime)return this.prime.ireduce(a)._forceRed(this);return a.umod(this.m)._forceRed(this)};Red.prototype.neg=function neg(a){if(a.isZero()){return a.clone()}return this.m.sub(a)._forceRed(this)};Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);if(res.cmp(this.m)>=0){res.isub(this.m)}return res._forceRed(this)};Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);if(res.cmp(this.m)>=0){res.isub(this.m)}return res};Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);if(res.cmpn(0)<0){res.iadd(this.m)}return res._forceRed(this)};Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);if(res.cmpn(0)<0){res.iadd(this.m)}return res};Red.prototype.shl=function shl(a,num){this._verify1(a);return this.imod(a.ushln(num))};Red.prototype.imul=function imul(a,b){this._verify2(a,b);return this.imod(a.imul(b))};Red.prototype.mul=function mul(a,b){this._verify2(a,b);return this.imod(a.mul(b))};Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())};Red.prototype.sqr=function sqr(a){return this.mul(a,a)};Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);assert(mod3%2===1);if(mod3===3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}var q=this.m.subn(1);var s=0;while(!q.isZero()&&q.andln(1)===0){s++;q.iushrn(1)}assert(!q.isZero());var one=new BN(1).toRed(this);var nOne=one.redNeg();var lpow=this.m.subn(1).iushrn(1);var z=this.m.bitLength();z=new BN(2*z*z).toRed(this);while(this.pow(z,lpow).cmp(nOne)!==0){z.redIAdd(nOne)}var c=this.pow(z,q);var r=this.pow(a,q.addn(1).iushrn(1));var t=this.pow(a,q);var m=s;while(t.cmp(one)!==0){var tmp=t;for(var i=0;tmp.cmp(one)!==0;i++){tmp=tmp.redSqr()}assert(i=0;i--){var word=num.words[i];for(var j=start-1;j>=0;j--){var bit=word>>j&1;if(res!==wnd[0]){res=this.sqr(res)}if(bit===0&¤t===0){currentLen=0;continue}current<<=1;current|=bit;currentLen++;if(currentLen!==windowSize&&(i!==0||j!==0))continue;res=this.mul(res,wnd[current]);currentLen=0;current=0}start=26}return res};Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r};Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();res.red=null;return res};BN.mont=function mont(num){return new Mont(num)};function Mont(m){Red.call(this,m);this.shift=this.m.bitLength();if(this.shift%26!==0){this.shift+=26-this.shift%26}this.r=new BN(1).iushln(this.shift);this.r2=this.imod(this.r.sqr());this.rinv=this.r._invmp(this.m);this.minv=this.rinv.mul(this.r).isubn(1).div(this.m);this.minv=this.minv.umod(this.r);this.minv=this.r.sub(this.minv)}inherits(Mont,Red);Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))};Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));r.red=null;return r};Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero()){a.words[0]=0;a.length=1;return a}var t=a.imul(b);var c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);var u=t.isub(c).iushrn(this.shift);var res=u;if(u.cmp(this.m)>=0){res=u.isub(this.m)}else if(u.cmpn(0)<0){res=u.iadd(this.m)}return res._forceRed(this)};Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b);var c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);var u=t.isub(c).iushrn(this.shift);var res=u;if(u.cmp(this.m)>=0){res=u.isub(this.m)}else if(u.cmpn(0)<0){res=u.iadd(this.m)}return res._forceRed(this)};Mont.prototype.invm=function invm(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}})(typeof module==="undefined"||module,this)},{}],40:[function(require,module,exports){(function(Buffer){var bn=require("bn.js");var randomBytes=require("randombytes");module.exports=crt;function blind(priv){var r=getr(priv);var blinder=r.toRed(bn.mont(priv.modulus)).redPow(new bn(priv.publicExponent)).fromRed();return{blinder:blinder,unblinder:r.invm(priv.modulus)}}function crt(msg,priv){var blinds=blind(priv);var len=priv.modulus.byteLength();var mod=bn.mont(priv.modulus);var blinded=new bn(msg).mul(blinds.blinder).umod(priv.modulus);var c1=blinded.toRed(bn.mont(priv.prime1));var c2=blinded.toRed(bn.mont(priv.prime2));var qinv=priv.coefficient;var p=priv.prime1;var q=priv.prime2;var m1=c1.redPow(priv.exponent1);var m2=c2.redPow(priv.exponent2);m1=m1.fromRed();m2=m2.fromRed();var h=m1.isub(m2).imul(qinv).umod(p);h.imul(q);m2.iadd(h);return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false,len))}crt.getr=getr;function getr(priv){var len=priv.modulus.byteLength();var r=new bn(randomBytes(len));while(r.cmp(priv.modulus)>=0||!r.umod(priv.prime1)||!r.umod(priv.prime2)){r=new bn(randomBytes(len))}return r}}).call(this,require("buffer").Buffer)},{"bn.js":39,buffer:2,randombytes:202}],41:[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":66,"./elliptic/curve":44,"./elliptic/curves":47,"./elliptic/ec":48,"./elliptic/eddsa":51,"./elliptic/utils":55,brorand:56}],42:[function(require,module,exports){"use strict";var BN=require("bn.js");var elliptic=require("../../elliptic");var utils=elliptic.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);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);var I=(1<=j;k--)nafW=(nafW<<1)+naf[k];repr.push(nafW)}var a=this.jpoint(null,null,null);var b=this.jpoint(null,null,null);for(var i=I;i>0;i--){for(var j=0;j=0;i--){for(var k=0;i>=0&&naf[i]===0;i--)k++;if(i>=0)k++;acc=acc.dblp(k);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;for(var i=0;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]);naf[b]=getNAF(coeffs[b],wndWidth[b]);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(var j=0;j=0;i--){var k=0;while(i>=0){var zero=true;for(var j=0;j=0)k++;acc=acc.dblp(k);if(i<0)break;for(var j=0;j0)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(var i=0;i=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";return""};Point.prototype.isInfinity=function isInfinity(){return this.x.cmpn(0)===0&&this.y.cmp(this.z)===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;if(this.curve.twisted){var 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{var h=this.z.redSqr();var 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{var e=c.redAdd(d);var h=this.curve._mulC(this.c.redMul(this.z)).redSqr();var 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}return false};Point.prototype.toP=Point.prototype.normalize;Point.prototype.mixedAdd=Point.prototype.add},{"../../elliptic":41,"../curve":44,"bn.js":39,inherits:204}],44:[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":42,"./edwards":43,"./mont":45,"./short":46}],45:[function(require,module,exports){"use strict";var curve=require("../curve");var BN=require("bn.js");var inherits=require("inherits");var Base=curve.base;var elliptic=require("../../elliptic");var utils=elliptic.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"";return""};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()}},{"../../elliptic":41,"../curve":44,"bn.js":39,inherits:204}],46:[function(require,module,exports){"use strict";var curve=require("../curve");var elliptic=require("../../elliptic");var BN=require("bn.js");var inherits=require("inherits");var Base=curve.base;var assert=elliptic.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";return""};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._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();if(this.curve.zeroA||this.curve.threeA){var r=this;for(var i=0;i=0)return false;rx.redIAdd(t);if(this.x.cmp(rx)===0)return true}return false};JPoint.prototype.inspect=function inspect(){if(this.isInfinity())return"";return""};JPoint.prototype.isInfinity=function isInfinity(){return this.z.cmpn(0)===0}},{"../../elliptic":41,"../curve":44,"bn.js":39,inherits:204}],47:[function(require,module,exports){"use strict";var curves=exports;var hash=require("hash.js");var elliptic=require("../elliptic");var assert=elliptic.utils.assert;function PresetCurve(options){if(options.type==="short")this.curve=new elliptic.curve.short(options);else if(options.type==="edwards")this.curve=new elliptic.curve.edwards(options);else this.curve=new elliptic.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]})},{"../elliptic":41,"./precomputed/secp256k1":54,"hash.js":57}],48:[function(require,module,exports){"use strict";var BN=require("bn.js");var HmacDRBG=require("hmac-drbg");var elliptic=require("../../elliptic");var utils=elliptic.utils;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(elliptic.curves.hasOwnProperty(options),"Unknown curve "+options);options=elliptic.curves[options]}if(options instanceof elliptic.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||elliptic.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));do{var priv=new BN(drbg.generate(bytes));if(priv.cmp(ns2)>0)continue;priv.iaddn(1);return this.keyFromPrivate(priv)}while(true)};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;true;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);if(!this.curve._maxwellTrick){var p=this.g.mulAdd(u1,key.getPublic(),u2);if(p.isInfinity())return false;return p.getX().umod(this.n).cmp(r)===0}var 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")}},{"../../elliptic":41,"./key":49,"./signature":50,"bn.js":39,"hmac-drbg":63}],49:[function(require,module,exports){"use strict";var BN=require("bn.js");var elliptic=require("../../elliptic");var utils=elliptic.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){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""}},{"../../elliptic":41,"bn.js":39}],50:[function(require,module,exports){"use strict";var BN=require("bn.js");var elliptic=require("../../elliptic");var utils=elliptic.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;var val=0;for(var i=0,off=p.place;i>>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)}},{"../../elliptic":41,"bn.js":39}],51:[function(require,module,exports){"use strict";var hash=require("hash.js");var elliptic=require("../../elliptic");var utils=elliptic.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);var curve=elliptic.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=0){var z;if(k.isOdd()){var mod=k.andln(ws-1);if(mod>(ws>>1)-1)z=(ws>>1)-mod;else z=mod;k.isubn(z)}else{z=0}naf.push(z);var shift=k.cmpn(0)!==0&&k.andln(ws-1)===0?w+1:1;for(var i=1;i0||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{var 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{var 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":39,"minimalistic-assert":64,"minimalistic-crypto-utils":65}],56:[function(require,module,exports){var r;module.exports=function rand(len){if(!r)r=new Rand(null);return r.generate(len)};function Rand(rand){this.rand=rand}module.exports.Rand=Rand;Rand.prototype.generate=function generate(len){return this._rand(len)};Rand.prototype._rand=function _rand(n){if(this.rand.getBytes)return this.rand.getBytes(n);var res=new Uint8Array(n);for(var i=0;i=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>>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(var t=8;tthis.blockSize)key=(new this.Hash).update(key).digest();assert(key.length<=this.blockSize);for(var i=key.length;i>>3}function g1_256(x){return rotr32(x,17)^rotr32(x,19)^x>>>10}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)}function ch64_hi(xh,xl,yh,yl,zh,zl){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,zl){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}},{"../hash":57}],62:[function(require,module,exports){var utils=exports;var inherits=require("inherits");function toArray(msg,enc){if(Array.isArray(msg))return msg.slice();if(!msg)return[];var res=[];if(typeof msg==="string"){if(!enc){for(var i=0;i>8;var lo=c&255;if(hi)res.push(hi,lo);else res.push(lo)}}else if(enc==="hex"){msg=msg.replace(/[^a-z0-9]+/gi,"");if(msg.length%2!==0)msg="0"+msg;for(var i=0;i>>24|w>>>8&65280|w<<8&16711680|(w&255)<<24;return res>>>0}utils.htonl=htonl;function toHex32(msg,endian){var res="";for(var i=0;i>>0}return res}utils.join32=join32;function split32(msg,endian){var res=new Array(msg.length*4);for(var i=0,k=0;i>>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}utils.split32=split32;function rotr32(w,b){return w>>>b|w<<32-b}utils.rotr32=rotr32;function rotl32(w,b){return w<>>32-b}utils.rotl32=rotl32;function sum32(a,b){return a+b>>>0}utils.sum32=sum32;function sum32_3(a,b,c){return a+b+c>>>0}utils.sum32_3=sum32_3;function sum32_4(a,b,c,d){return a+b+c+d>>>0}utils.sum32_4=sum32_4;function sum32_5(a,b,c,d,e){return a+b+c+d+e>>>0}utils.sum32_5=sum32_5;function assert(cond,msg){if(!cond)throw new Error(msg||"Assertion failed")}utils.assert=assert;utils.inherits=inherits;function sum64(buf,pos,ah,al){var bh=buf[pos];var bl=buf[pos+1];var lo=al+bl>>>0;var hi=(lo>>0;buf[pos+1]=lo}exports.sum64=sum64;function sum64_hi(ah,al,bh,bl){var lo=al+bl>>>0;var hi=(lo>>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>>0;carry+=lo>>0;carry+=lo>>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>>0;carry+=lo>>0;carry+=lo>>0;carry+=lo>>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:204}],63:[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.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>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>6];var primitive=(tag&32)===0;if((tag&31)===31){var oct=tag;tag=0;while((oct&128)===128){oct=buf.readUInt8(fail);if(buf.isError(oct))return oct;tag<<=7;tag|=oct&127}}else{tag&=31}var tagStr=der.tag[tag];return{cls:cls,primitive:primitive,tag:tag,tagStr:tagStr}}function derDecodeLen(buf,primitive,fail){var len=buf.readUInt8(fail);if(buf.isError(len))return len;if(!primitive&&len===128)return null;if((len&128)===0){return len}var num=len&127;if(num>4)return buf.error("length octect is too long");len=0;for(var i=0;i=256;i>>=8)lenOctets++;var header=new Buffer(1+1+lenOctets);header[0]=encodedTag;header[1]=128|lenOctets;for(var i=1+lenOctets,j=content.length;j>0;i--,j>>=8)header[i]=j&255;return this._createEncoderBuffer([header,content])};DERNode.prototype._encodeStr=function encodeStr(str,tag){if(tag==="bitstr"){return this._createEncoderBuffer([str.unused|0,str.data])}else if(tag==="bmpstr"){var buf=new Buffer(str.length*2);for(var i=0;i=40)return this.reporter.error("Second objid identifier OOB");id.splice(0,2,id[0]*40+id[1])}var size=0;for(var i=0;i=128;ident>>=7)size++}var objid=new Buffer(size);var offset=objid.length-1;for(var i=id.length-1;i>=0;i--){var ident=id[i];objid[offset--]=ident&127;while((ident>>=7)>0)objid[offset--]=128|ident&127}return this._createEncoderBuffer(objid)};function two(num){if(num<10)return"0"+num;else return num}DERNode.prototype._encodeTime=function encodeTime(time,tag){var str;var date=new Date(time);if(tag==="gentime"){str=[two(date.getFullYear()),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),"Z"].join("")}else if(tag==="utctime"){str=[two(date.getFullYear()%100),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),"Z"].join("")}else{this.reporter.error("Encoding "+tag+" time is not supported yet")}return this._encodeStr(str,"octstr")};DERNode.prototype._encodeNull=function encodeNull(){return this._createEncoderBuffer("")};DERNode.prototype._encodeInt=function encodeInt(num,values){if(typeof num==="string"){if(!values)return this.reporter.error("String int or enum given, but no values map");if(!values.hasOwnProperty(num)){return this.reporter.error("Values map doesn't contain: "+JSON.stringify(num))}num=values[num]}if(typeof num!=="number"&&!Buffer.isBuffer(num)){var numArray=num.toArray();if(!num.sign&&numArray[0]&128){numArray.unshift(0)}num=new Buffer(numArray)}if(Buffer.isBuffer(num)){var size=num.length;if(num.length===0)size++;var out=new Buffer(size);num.copy(out);if(num.length===0)out[0]=0;return this._createEncoderBuffer(out)}if(num<128)return this._createEncoderBuffer(num);if(num<256)return this._createEncoderBuffer([0,num]);var size=1;for(var i=num;i>=256;i>>=8)size++;var out=new Array(size);for(var i=out.length-1;i>=0;i--){out[i]=num&255;num>>=8}if(out[0]&128){out.unshift(0)}return this._createEncoderBuffer(new Buffer(out))};DERNode.prototype._encodeBool=function encodeBool(value){return this._createEncoderBuffer(value?255:0)};DERNode.prototype._use=function use(entity,obj){if(typeof entity==="function")entity=entity(obj);return entity._getEncoder("der").tree};DERNode.prototype._skipDefault=function skipDefault(dataBuffer,reporter,parent){var state=this._baseState;var i;if(state["default"]===null)return false;var data=dataBuffer.join();if(state.defaultBuffer===undefined)state.defaultBuffer=this._encodeValue(state["default"],reporter,parent).join();if(data.length!==state.defaultBuffer.length)return false;for(i=0;i=31)return reporter.error("Multi-octet tag encoding unsupported");if(!primitive)res|=32;res|=der.tagClassByName[cls||"universal"]<<6;return res}},{"../../asn1":71,buffer:2,inherits:204}],83:[function(require,module,exports){var encoders=exports;encoders.der=require("./der");encoders.pem=require("./pem")},{"./der":82,"./pem":84}],84:[function(require,module,exports){var inherits=require("inherits");var DEREncoder=require("./der");function PEMEncoder(entity){DEREncoder.call(this,entity);this.enc="pem"}inherits(PEMEncoder,DEREncoder);module.exports=PEMEncoder;PEMEncoder.prototype.encode=function encode(data,options){var buf=DEREncoder.prototype.encode.call(this,data);var p=buf.toString("base64");var out=["-----BEGIN "+options.label+"-----"];for(var i=0;i0){bits.ishrn(shift)}return bits}function bits2octets(bits,q){bits=bits2int(bits,q);bits=bits.mod(q);var out=new Buffer(bits.toArray());if(out.length=q){throw new Error("invalid sig")}}module.exports=verify}).call(this,require("buffer").Buffer)},{"./curves":38,"bn.js":39,buffer:2,elliptic:41,"parse-asn1":70}],106:[function(require,module,exports){(function(Buffer){var elliptic=require("elliptic");var BN=require("bn.js");module.exports=function createECDH(curve){return new ECDH(curve)};var aliases={secp256k1:{name:"secp256k1",byteLength:32},secp224r1:{name:"p224",byteLength:28},prime256v1:{name:"p256",byteLength:32},prime192v1:{name:"p192",byteLength:24},ed25519:{name:"ed25519",byteLength:32},secp384r1:{name:"p384",byteLength:48},secp521r1:{name:"p521",byteLength:66}};aliases.p224=aliases.secp224r1;aliases.p256=aliases.secp256r1=aliases.prime256v1;aliases.p192=aliases.secp192r1=aliases.prime192v1;aliases.p384=aliases.secp384r1;aliases.p521=aliases.secp521r1;function ECDH(curve){this.curveType=aliases[curve];if(!this.curveType){this.curveType={name:curve}}this.curve=new elliptic.ec(this.curveType.name);this.keys=void 0}ECDH.prototype.generateKeys=function(enc,format){this.keys=this.curve.genKeyPair();return this.getPublicKey(enc,format)};ECDH.prototype.computeSecret=function(other,inenc,enc){inenc=inenc||"utf8";if(!Buffer.isBuffer(other)){other=new Buffer(other,inenc)}var otherPub=this.curve.keyFromPublic(other).getPublic();var out=otherPub.mul(this.keys.getPrivate()).getX();return formatReturnValue(out,enc,this.curveType.byteLength)};ECDH.prototype.getPublicKey=function(enc,format){var key=this.keys.getPublic(format==="compressed",true);if(format==="hybrid"){if(key[key.length-1]%2){key[0]=7}else{key[0]=6}}return formatReturnValue(key,enc)};ECDH.prototype.getPrivateKey=function(enc){return formatReturnValue(this.keys.getPrivate(),enc)};ECDH.prototype.setPublicKey=function(pub,enc){enc=enc||"utf8";if(!Buffer.isBuffer(pub)){pub=new Buffer(pub,enc)}this.keys._importPublic(pub);return this};ECDH.prototype.setPrivateKey=function(priv,enc){enc=enc||"utf8";if(!Buffer.isBuffer(priv)){priv=new Buffer(priv,enc)}var _priv=new BN(priv);_priv=_priv.toString(16);this.keys._importPrivate(_priv);return this};function formatReturnValue(bn,enc,len){if(!Array.isArray(bn)){bn=bn.toArray()}var buf=new Buffer(bn);if(len&&buf.length>5]|=128<>>9<<4)+14]=len;var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;for(var i=0;i>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&65535}function bit_rol(num,cnt){return num<>>32-cnt}module.exports=function md5(buf){return helpers.hash(buf,core_md5,16)}},{"./helpers":135}],137:[function(require,module,exports){arguments[4][23][0].apply(exports,arguments)},{buffer:2,dup:23,inherits:204,stream:223,string_decoder:224}],138:[function(require,module,exports){(function(Buffer){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 bytesToWords(bytes){var words=[];for(var i=0,b=0;i>>5]|=bytes[i]<<24-b%32}return words}function wordsToBytes(words){var bytes=[];for(var b=0;b>>5]>>>24-b%32&255)}return bytes}function processBlock(H,M,offset){for(var i=0;i<16;i++){var offset_i=offset+i;var M_offset_i=M[offset_i];M[offset_i]=(M_offset_i<<8|M_offset_i>>>24)&16711935|(M_offset_i<<24|M_offset_i>>>8)&4278255360}var al,bl,cl,dl,el;var ar,br,cr,dr,er;ar=al=H[0];br=bl=H[1];cr=cl=H[2];dr=dl=H[3];er=el=H[4];var t;for(i=0;i<80;i+=1){t=al+M[offset+zl[i]]|0;if(i<16){t+=f1(bl,cl,dl)+hl[0]}else if(i<32){t+=f2(bl,cl,dl)+hl[1]}else if(i<48){t+=f3(bl,cl,dl)+hl[2]}else if(i<64){t+=f4(bl,cl,dl)+hl[3]}else{t+=f5(bl,cl,dl)+hl[4]}t=t|0;t=rotl(t,sl[i]);t=t+el|0;al=el;el=dl;dl=rotl(cl,10);cl=bl;bl=t;t=ar+M[offset+zr[i]]|0;if(i<16){t+=f5(br,cr,dr)+hr[0]}else if(i<32){t+=f4(br,cr,dr)+hr[1]}else if(i<48){t+=f3(br,cr,dr)+hr[2]}else if(i<64){t+=f2(br,cr,dr)+hr[3]}else{t+=f1(br,cr,dr)+hr[4]}t=t|0;t=rotl(t,sr[i]);t=t+er|0;ar=er;er=dr;dr=rotl(cr,10);cr=br;br=t}t=H[1]+cl+dr|0;H[1]=H[2]+dl+er|0;H[2]=H[3]+el+ar|0;H[3]=H[4]+al+br|0;H[4]=H[0]+bl+cr|0;H[0]=t}function f1(x,y,z){return x^y^z}function f2(x,y,z){return x&y|~x&z}function f3(x,y,z){return(x|~y)^z}function f4(x,y,z){return x&z|y&~z}function f5(x,y,z){return x^(y|~z)}function rotl(x,n){return x<>>32-n}function ripemd160(message){var H=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof message==="string"){message=new Buffer(message,"utf8")}var m=bytesToWords(message);var nBitsLeft=message.length*8;var nBitsTotal=message.length*8;m[nBitsLeft>>>5]|=128<<24-nBitsLeft%32;m[(nBitsLeft+64>>>9<<4)+14]=(nBitsTotal<<8|nBitsTotal>>>24)&16711935|(nBitsTotal<<24|nBitsTotal>>>8)&4278255360;for(var i=0;i>>24)&16711935|(H_i<<24|H_i>>>8)&4278255360}var digestbytes=wordsToBytes(H);return new Buffer(digestbytes)}module.exports=ripemd160}).call(this,require("buffer").Buffer)},{buffer:2}],139:[function(require,module,exports){(function(Buffer){function Hash(blockSize,finalSize){this._block=new Buffer(blockSize);this._finalSize=finalSize;this._blockSize=blockSize;this._len=0;this._s=0}Hash.prototype.update=function(data,enc){if(typeof data==="string"){enc=enc||"utf8";data=new Buffer(data,enc)}var l=this._len+=data.length;var s=this._s||0;var f=0;var buffer=this._block;while(s=this._finalSize*8){this._update(this._block);this._block.fill(0)}this._block.writeInt32BE(l,this._blockSize-4);var hash=this._update(this._block)||this._hash();return enc?hash.toString(enc):hash};Hash.prototype._update=function(){throw new Error("_update must be implemented by subclass")};module.exports=Hash}).call(this,require("buffer").Buffer)},{buffer:2}],140:[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":141,"./sha1":142,"./sha224":143,"./sha256":144,"./sha384":145,"./sha512":146}],141:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");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=new Buffer(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}).call(this,require("buffer").Buffer)},{"./hash":139,buffer:2,inherits:204}],142:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");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=new Buffer(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}).call(this,require("buffer").Buffer)},{"./hash":139,buffer:2,inherits:204}],143:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Sha256=require("./sha256");var Hash=require("./hash");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=new Buffer(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}).call(this,require("buffer").Buffer)},{"./hash":139,"./sha256":144,buffer:2,inherits:204}],144:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");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=new Buffer(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}).call(this,require("buffer").Buffer)},{"./hash":139,buffer:2,inherits:204}],145:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var SHA512=require("./sha512");var Hash=require("./hash");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=new Buffer(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}).call(this,require("buffer").Buffer)},{"./hash":139,"./sha512":146,buffer:2,inherits:204}],146:[function(require,module,exports){(function(Buffer){var inherits=require("inherits");var Hash=require("./hash");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>>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=new Buffer(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}).call(this,require("buffer").Buffer)},{"./hash":139,buffer:2,inherits:204}],147:[function(require,module,exports){(function(Buffer){"use strict";var createHash=require("create-hash/browser");var inherits=require("inherits");var Transform=require("stream").Transform;var ZEROS=new Buffer(128);ZEROS.fill(0);function Hmac(alg,key){Transform.call(this);alg=alg.toLowerCase();if(typeof key==="string"){key=new Buffer(key)}var blocksize=alg==="sha512"||alg==="sha384"?128:64;this._alg=alg;this._key=key;if(key.length>blocksize){key=createHash(alg).update(key).digest()}else if(key.lengthbits){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":152,"miller-rabin":153,randombytes:202}],151:[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"}}},{}],152:[function(require,module,exports){arguments[4][39][0].apply(exports,arguments)},{dup:39}],153:[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._rand=function _rand(n){var len=n.bitLength();var buf=this.rand.generate(Math.ceil(len/8));buf[0]|=3;var mask=len&7;if(mask!==0)buf[buf.length-1]>>=7-mask;return new bn(buf)};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);var n2=n1.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._rand(n2);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;i0;k--){var a=this._rand(n2);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=6?"utf-8":"binary"}exports.pbkdf2Sync=function(password,salt,iterations,keylen,digest){if(!Buffer.isBuffer(password))password=new Buffer(password,defaultEncoding);if(!Buffer.isBuffer(salt))salt=new Buffer(salt,defaultEncoding);checkParameters(iterations,keylen);digest=digest||"sha1";var hLen;var l=1;var DK=new Buffer(keylen);var block1=new Buffer(salt.length+4);salt.copy(block1,0,0,salt.length);var r;var T;for(var i=1;i<=l;i++){block1.writeUInt32BE(i,salt.length);var U=createHmac(digest,password).update(block1).digest();if(!hLen){hLen=U.length;T=new Buffer(hLen);l=Math.ceil(keylen/hLen);r=keylen-(l-1)*hLen}U.copy(T,0,0,hLen);for(var j=1;jMAX_ALLOC||keylen!==keylen){throw new TypeError("Bad key length")}}},{}],157:[function(require,module,exports){exports.publicEncrypt=require("./publicEncrypt");exports.privateDecrypt=require("./privateDecrypt");exports.privateEncrypt=function privateEncrypt(key,buf){return exports.publicEncrypt(key,buf,true)};exports.publicDecrypt=function publicDecrypt(key,buf){return exports.privateDecrypt(key,buf,true)}},{"./privateDecrypt":198,"./publicEncrypt":199}],158:[function(require,module,exports){(function(Buffer){var createHash=require("create-hash");module.exports=function(seed,len){var t=new Buffer("");var i=0,c;while(t.lengthk||new bn(enc).cmp(key.modulus)>=0){throw new Error("decryption error")}var msg;if(reverse){msg=withPublic(new bn(enc),key)}else{msg=crt(enc,key)}var zBuffer=new Buffer(k-msg.length);zBuffer.fill(0);msg=Buffer.concat([zBuffer,msg],k);if(padding===4){return oaep(key,msg)}else if(padding===1){return pkcs1(key,msg,reverse)}else if(padding===3){return msg}else{throw new Error("unknown padding")}};function oaep(key,msg){var n=key.modulus;var k=key.modulus.byteLength();var mLen=msg.length;var iHash=createHash("sha1").update(new Buffer("")).digest();var hLen=iHash.length;var hLen2=2*hLen;if(msg[0]!==0){throw new Error("decryption error")}var maskedSeed=msg.slice(1,hLen+1);var maskedDb=msg.slice(hLen+1);var seed=xor(maskedSeed,mgf(maskedDb,hLen));var db=xor(maskedDb,mgf(seed,k-hLen-1));if(compare(iHash,db.slice(0,hLen))){throw new Error("decryption error")}var i=hLen;while(db[i]===0){i++}if(db[i++]!==1){throw new Error("decryption error")}return db.slice(i)}function pkcs1(key,msg,reverse){var p1=msg.slice(0,2);var i=2;var status=0;while(msg[i++]!==0){if(i>=msg.length){status++;break}}var ps=msg.slice(2,i-1);var p2=msg.slice(i-1,i);if(p1.toString("hex")!=="0002"&&!reverse||p1.toString("hex")!=="0001"&&reverse){status++}if(ps.length<8){status++}if(status){throw new Error("decryption error")}return msg.slice(i)}function compare(a,b){a=new Buffer(a);b=new Buffer(b);var dif=0;var len=a.length;if(a.length!==b.length){dif++;len=Math.min(a.length,b.length)}var i=-1;while(++i=0){throw new Error("data too long for modulus")}}else{throw new Error("unknown padding")}if(reverse){return crt(paddedMsg,key)}else{return withPublic(paddedMsg,key)}};function oaep(key,msg){var k=key.modulus.byteLength();var mLen=msg.length;var iHash=createHash("sha1").update(new Buffer("")).digest();var hLen=iHash.length;var hLen2=2*hLen;if(mLen>k-hLen2-2){throw new Error("message too long")}var ps=new Buffer(k-mLen-hLen2-2);ps.fill(0);var dblen=k-hLen-1;var seed=randomBytes(hLen);var maskedDb=xor(Buffer.concat([iHash,ps,new Buffer([1]),msg],dblen),mgf(seed,dblen));var maskedSeed=xor(seed,mgf(maskedDb,hLen));return new bn(Buffer.concat([new Buffer([0]),maskedSeed,maskedDb],k))}function pkcs1(key,msg,reverse){var mLen=msg.length;var k=key.modulus.byteLength();if(mLen>k-11){throw new Error("message too long")}var ps;if(reverse){ps=new Buffer(k-mLen-3);ps.fill(255)}else{ps=nonZero(k-mLen-3)}return new bn(Buffer.concat([new Buffer([0,reverse?1:2]),ps,new Buffer([0]),msg],k))}function nonZero(len,crypto){var out=new Buffer(len);var i=0;var cache=randomBytes(len*2);var cur=0;var num;while(i65536)throw new Error("requested too many random bytes");var rawBytes=new global.Uint8Array(size);if(size>0){crypto.getRandomValues(rawBytes)}var bytes=new Buffer(rawBytes.buffer);if(typeof cb==="function"){return process.nextTick(function(){cb(null,bytes)})}return bytes}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{_process:206,buffer:2}],203:[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;i0&&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}},{}],204:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,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){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],205:[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))}},{}],206:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex1){for(var i=1;i0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;if(state.decoder&&!addToFront&&!encoding){chunk=state.decoder.write(chunk);skipAdd=!state.objectMode&&chunk.length===0}if(!addToFront)state.reading=false;if(!skipAdd){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}}maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}Readable.prototype.read=function(n){debug("read",n);n=parseInt(n,10);var state=this._readableState;var nOrig=n;if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}else{state.length-=n}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)processNextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;processNextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",er)}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&EElistenerCount(src,"data")){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var i=0;i=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.head.data;else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(nstr.length?str.length:n;if(nb===str.length)ret+=str;else ret+=str.slice(0,n);n-=nb;if(n===0){if(nb===str.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=str.slice(nb)}break}++c}list.length-=c;return ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n);var p=list.head;var c=1;p.data.copy(ret);n-=p.data.length;while(p=p.next){var buf=p.data;var nb=n>buf.length?buf.length:n;buf.copy(ret,ret.length-n,0,nb);n-=nb;if(n===0){if(nb===buf.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=buf.slice(nb)}break}++c}list.length-=c;return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!state.endEmitted){state.ended=true;processNextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function forEach(xs,f){for(var i=0,l=xs.length;i-1?setImmediate:processNextTick;var Duplex;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")};var Stream;(function(){try{Stream=require("st"+"ream")}catch(_){}finally{if(!Stream)Stream=require("events").EventEmitter}})();var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims") ;util.inherits(Writable,Stream);function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=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.")})}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;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}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);processNextTick(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(!Buffer.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}if(er){stream.emit("error",er);processNextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;if(typeof encoding==="function"){cb=encoding;encoding=null}if(Buffer.isBuffer(chunk))encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,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=bufferShim.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){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(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(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(n){if(this.length===0)return bufferShim.alloc(0);if(this.length===1)return this.head.data;var ret=bufferShim.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret}},{buffer:2,"buffer-shims":214}],214:[function(require,module,exports){(function(global){"use strict";var buffer=require("buffer");var Buffer=buffer.Buffer;var SlowBuffer=buffer.SlowBuffer;var MAX_LEN=buffer.kMaxLength||2147483647;exports.alloc=function alloc(size,fill,encoding){if(typeof Buffer.alloc==="function"){return Buffer.alloc(size,fill,encoding)}if(typeof encoding==="number"){throw new TypeError("encoding must not be number")}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>MAX_LEN){throw new RangeError("size is too large")}var enc=encoding;var _fill=fill;if(_fill===undefined){enc=undefined;_fill=0}var buf=new Buffer(size);if(typeof _fill==="string"){var fillBuf=new Buffer(_fill,enc);var flen=fillBuf.length;var i=-1;while(++iMAX_LEN){throw new RangeError("size is too large")}return new Buffer(size)};exports.from=function from(value,encodingOrOffset,length){if(typeof Buffer.from==="function"&&(!global.Uint8Array||Uint8Array.from!==Buffer.from)){return Buffer.from(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof value==="string"){return new Buffer(value,encodingOrOffset)}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(arguments.length===1){return new Buffer(value)}if(typeof offset==="undefined"){offset=0}var len=length;if(typeof len==="undefined"){len=value.byteLength-offset}if(offset>=value.byteLength){throw new RangeError("'offset' is out of bounds")}if(len>value.byteLength-offset){throw new RangeError("'length' is out of bounds")}return new Buffer(value.slice(offset,offset+len))}if(Buffer.isBuffer(value)){var out=new Buffer(value.length);value.copy(out,0,0,value.length);return out}if(value){if(Array.isArray(value)||typeof ArrayBuffer!=="undefined"&&value.buffer instanceof ArrayBuffer||"length"in value){return new Buffer(value)}if(value.type==="Buffer"&&Array.isArray(value.data)){return new Buffer(value.data)}}throw new TypeError("First argument must be a string, Buffer, "+"ArrayBuffer, Array, or array-like object.")};exports.allocUnsafeSlow=function allocUnsafeSlow(size){if(typeof Buffer.allocUnsafeSlow==="function"){return Buffer.allocUnsafeSlow(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>=MAX_LEN){throw new RangeError("size is too large")}return new SlowBuffer(size)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{buffer:2}],215:[function(require,module,exports){(function(Buffer){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,{isBuffer:require("../../../../insert-module-globals/node_modules/is-buffer/index.js")})},{"../../../../insert-module-globals/node_modules/is-buffer/index.js":205}],216:[function(require,module,exports){arguments[4][5][0].apply(exports,arguments)},{dup:5}],217:[function(require,module,exports){(function(process){"use strict";if(!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){module.exports=nextTick}else{module.exports=process.nextTick}function nextTick(fn,arg1,arg2,arg3){if(typeof fn!=="function"){throw new TypeError('"callback" argument must be a function')}var len=arguments.length;var args,i;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function afterTickOne(){fn.call(null,arg1)});case 3:return process.nextTick(function afterTickTwo(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function afterTickThree(){fn.call(null,arg1,arg2,arg3)});default:args=new Array(len-1);i=0;while(i=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:2}],225:[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>>0;if(""+uint32Index!==index||uint32Index===4294967295){return NaN}index=uint32Index}return index<0?ensureSize(iter)+index:index}function returnTrue(){return true}function wholeSlice(begin,end,size){return(begin===0||size!==undefined&&begin<=-size)&&(end===undefined||size!==undefined&&end>=size)}function resolveBegin(begin,size){return resolveIndex(begin,size,0)}function resolveEnd(end,size){return resolveIndex(end,size,size)}function resolveIndex(index,size,defaultIndex){return index===undefined?defaultIndex:index<0?Math.max(0,size+index):size===undefined?index:Math.min(size,index)}var ITERATE_KEYS=0;var ITERATE_VALUES=1;var ITERATE_ENTRIES=2;var REAL_ITERATOR_SYMBOL=typeof Symbol==="function"&&Symbol.iterator;var FAUX_ITERATOR_SYMBOL="@@iterator";var ITERATOR_SYMBOL=REAL_ITERATOR_SYMBOL||FAUX_ITERATOR_SYMBOL;function Iterator(next){this.next=next}Iterator.prototype.toString=function(){return"[Iterator]"};Iterator.KEYS=ITERATE_KEYS;Iterator.VALUES=ITERATE_VALUES;Iterator.ENTRIES=ITERATE_ENTRIES;Iterator.prototype.inspect=Iterator.prototype.toSource=function(){return this.toString()};Iterator.prototype[ITERATOR_SYMBOL]=function(){return this};function iteratorValue(type,k,v,iteratorResult){var value=type===0?k:type===1?v:[k,v];iteratorResult?iteratorResult.value=value:iteratorResult={value:value,done:false};return iteratorResult}function iteratorDone(){return{value:undefined,done:true}}function hasIterator(maybeIterable){return!!getIteratorFn(maybeIterable)}function isIterator(maybeIterator){return maybeIterator&&typeof maybeIterator.next==="function"}function getIterator(iterable){var iteratorFn=getIteratorFn(iterable);return iteratorFn&&iteratorFn.call(iterable)}function getIteratorFn(iterable){var iteratorFn=iterable&&(REAL_ITERATOR_SYMBOL&&iterable[REAL_ITERATOR_SYMBOL]||iterable[FAUX_ITERATOR_SYMBOL]);if(typeof iteratorFn==="function"){return iteratorFn}}function isArrayLike(value){return value&&typeof value.length==="number"}createClass(Seq,Iterable);function Seq(value){return value===null||value===undefined?emptySequence():isIterable(value)?value.toSeq():seqFromValue(value)}Seq.of=function(){return Seq(arguments)};Seq.prototype.toSeq=function(){return this};Seq.prototype.toString=function(){return this.__toString("Seq {","}")};Seq.prototype.cacheResult=function(){if(!this._cache&&this.__iterateUncached){this._cache=this.entrySeq().toArray();this.size=this._cache.length}return this};Seq.prototype.__iterate=function(fn,reverse){return seqIterate(this,fn,reverse,true)};Seq.prototype.__iterator=function(type,reverse){return seqIterator(this,type,reverse,true)};createClass(KeyedSeq,Seq);function KeyedSeq(value){return value===null||value===undefined?emptySequence().toKeyedSeq():isIterable(value)?isKeyed(value)?value.toSeq():value.fromEntrySeq():keyedSeqFromValue(value)}KeyedSeq.prototype.toKeyedSeq=function(){return this};createClass(IndexedSeq,Seq);function IndexedSeq(value){return value===null||value===undefined?emptySequence():!isIterable(value)?indexedSeqFromValue(value):isKeyed(value)?value.entrySeq():value.toIndexedSeq()}IndexedSeq.of=function(){return IndexedSeq(arguments)};IndexedSeq.prototype.toIndexedSeq=function(){return this};IndexedSeq.prototype.toString=function(){return this.__toString("Seq [","]")};IndexedSeq.prototype.__iterate=function(fn,reverse){return seqIterate(this,fn,reverse,false)};IndexedSeq.prototype.__iterator=function(type,reverse){return seqIterator(this,type,reverse,false)};createClass(SetSeq,Seq);function SetSeq(value){return(value===null||value===undefined?emptySequence():!isIterable(value)?indexedSeqFromValue(value):isKeyed(value)?value.entrySeq():value).toSetSeq()}SetSeq.of=function(){return SetSeq(arguments)};SetSeq.prototype.toSetSeq=function(){return this};Seq.isSeq=isSeq;Seq.Keyed=KeyedSeq;Seq.Set=SetSeq;Seq.Indexed=IndexedSeq;var IS_SEQ_SENTINEL="@@__IMMUTABLE_SEQ__@@";Seq.prototype[IS_SEQ_SENTINEL]=true;createClass(ArraySeq,IndexedSeq);function ArraySeq(array){this._array=array;this.size=array.length}ArraySeq.prototype.get=function(index,notSetValue){return this.has(index)?this._array[wrapIndex(this,index)]:notSetValue};ArraySeq.prototype.__iterate=function(fn,reverse){var array=this._array;var maxIndex=array.length-1;for(var ii=0;ii<=maxIndex;ii++){if(fn(array[reverse?maxIndex-ii:ii],ii,this)===false){return ii+1}}return ii};ArraySeq.prototype.__iterator=function(type,reverse){var array=this._array;var maxIndex=array.length-1;var ii=0;return new Iterator(function(){return ii>maxIndex?iteratorDone():iteratorValue(type,ii,array[reverse?maxIndex-ii++:ii++])})};createClass(ObjectSeq,KeyedSeq);function ObjectSeq(object){var keys=Object.keys(object);this._object=object;this._keys=keys;this.size=keys.length} ObjectSeq.prototype.get=function(key,notSetValue){if(notSetValue!==undefined&&!this.has(key)){return notSetValue}return this._object[key]};ObjectSeq.prototype.has=function(key){return this._object.hasOwnProperty(key)};ObjectSeq.prototype.__iterate=function(fn,reverse){var object=this._object;var keys=this._keys;var maxIndex=keys.length-1;for(var ii=0;ii<=maxIndex;ii++){var key=keys[reverse?maxIndex-ii:ii];if(fn(object[key],key,this)===false){return ii+1}}return ii};ObjectSeq.prototype.__iterator=function(type,reverse){var object=this._object;var keys=this._keys;var maxIndex=keys.length-1;var ii=0;return new Iterator(function(){var key=keys[reverse?maxIndex-ii:ii];return ii++>maxIndex?iteratorDone():iteratorValue(type,key,object[key])})};ObjectSeq.prototype[IS_ORDERED_SENTINEL]=true;createClass(IterableSeq,IndexedSeq);function IterableSeq(iterable){this._iterable=iterable;this.size=iterable.length||iterable.size}IterableSeq.prototype.__iterateUncached=function(fn,reverse){if(reverse){return this.cacheResult().__iterate(fn,reverse)}var iterable=this._iterable;var iterator=getIterator(iterable);var iterations=0;if(isIterator(iterator)){var step;while(!(step=iterator.next()).done){if(fn(step.value,iterations++,this)===false){break}}}return iterations};IterableSeq.prototype.__iteratorUncached=function(type,reverse){if(reverse){return this.cacheResult().__iterator(type,reverse)}var iterable=this._iterable;var iterator=getIterator(iterable);if(!isIterator(iterator)){return new Iterator(iteratorDone)}var iterations=0;return new Iterator(function(){var step=iterator.next();return step.done?step:iteratorValue(type,iterations++,step.value)})};createClass(IteratorSeq,IndexedSeq);function IteratorSeq(iterator){this._iterator=iterator;this._iteratorCache=[]}IteratorSeq.prototype.__iterateUncached=function(fn,reverse){if(reverse){return this.cacheResult().__iterate(fn,reverse)}var iterator=this._iterator;var cache=this._iteratorCache;var iterations=0;while(iterations=cache.length){var step=iterator.next();if(step.done){return step}cache[iterations]=step.value}return iteratorValue(type,iterations,cache[iterations++])})};function isSeq(maybeSeq){return!!(maybeSeq&&maybeSeq[IS_SEQ_SENTINEL])}var EMPTY_SEQ;function emptySequence(){return EMPTY_SEQ||(EMPTY_SEQ=new ArraySeq([]))}function keyedSeqFromValue(value){var seq=Array.isArray(value)?new ArraySeq(value).fromEntrySeq():isIterator(value)?new IteratorSeq(value).fromEntrySeq():hasIterator(value)?new IterableSeq(value).fromEntrySeq():typeof value==="object"?new ObjectSeq(value):undefined;if(!seq){throw new TypeError("Expected Array or iterable object of [k, v] entries, "+"or keyed object: "+value)}return seq}function indexedSeqFromValue(value){var seq=maybeIndexedSeqFromValue(value);if(!seq){throw new TypeError("Expected Array or iterable object of values: "+value)}return seq}function seqFromValue(value){var seq=maybeIndexedSeqFromValue(value)||typeof value==="object"&&new ObjectSeq(value);if(!seq){throw new TypeError("Expected Array or iterable object of values, or keyed object: "+value)}return seq}function maybeIndexedSeqFromValue(value){return isArrayLike(value)?new ArraySeq(value):isIterator(value)?new IteratorSeq(value):hasIterator(value)?new IterableSeq(value):undefined}function seqIterate(seq,fn,reverse,useKeys){var cache=seq._cache;if(cache){var maxIndex=cache.length-1;for(var ii=0;ii<=maxIndex;ii++){var entry=cache[reverse?maxIndex-ii:ii];if(fn(entry[1],useKeys?entry[0]:ii,seq)===false){return ii+1}}return ii}return seq.__iterateUncached(fn,reverse)}function seqIterator(seq,type,reverse,useKeys){var cache=seq._cache;if(cache){var maxIndex=cache.length-1;var ii=0;return new Iterator(function(){var entry=cache[reverse?maxIndex-ii:ii];return ii++>maxIndex?iteratorDone():iteratorValue(type,useKeys?entry[0]:ii-1,entry[1])})}return seq.__iteratorUncached(type,reverse)}function fromJS(json,converter){return converter?fromJSWith(converter,json,"",{"":json}):fromJSDefault(json)}function fromJSWith(converter,json,key,parentJSON){if(Array.isArray(json)){return converter.call(parentJSON,key,IndexedSeq(json).map(function(v,k){return fromJSWith(converter,v,k,json)}))}if(isPlainObj(json)){return converter.call(parentJSON,key,KeyedSeq(json).map(function(v,k){return fromJSWith(converter,v,k,json)}))}return json}function fromJSDefault(json){if(Array.isArray(json)){return IndexedSeq(json).map(fromJSDefault).toList()}if(isPlainObj(json)){return KeyedSeq(json).map(fromJSDefault).toMap()}return json}function isPlainObj(value){return value&&(value.constructor===Object||value.constructor===undefined)}function is(valueA,valueB){if(valueA===valueB||valueA!==valueA&&valueB!==valueB){return true}if(!valueA||!valueB){return false}if(typeof valueA.valueOf==="function"&&typeof valueB.valueOf==="function"){valueA=valueA.valueOf();valueB=valueB.valueOf();if(valueA===valueB||valueA!==valueA&&valueB!==valueB){return true}if(!valueA||!valueB){return false}}if(typeof valueA.equals==="function"&&typeof valueB.equals==="function"&&valueA.equals(valueB)){return true}return false}function deepEqual(a,b){if(a===b){return true}if(!isIterable(b)||a.size!==undefined&&b.size!==undefined&&a.size!==b.size||a.__hash!==undefined&&b.__hash!==undefined&&a.__hash!==b.__hash||isKeyed(a)!==isKeyed(b)||isIndexed(a)!==isIndexed(b)||isOrdered(a)!==isOrdered(b)){return false}if(a.size===0&&b.size===0){return true}var notAssociative=!isAssociative(a);if(isOrdered(a)){var entries=a.entries();return b.every(function(v,k){var entry=entries.next().value;return entry&&is(entry[1],v)&&(notAssociative||is(entry[0],k))})&&entries.next().done}var flipped=false;if(a.size===undefined){if(b.size===undefined){if(typeof a.cacheResult==="function"){a.cacheResult()}}else{flipped=true;var _=a;a=b;b=_}}var allEqual=true;var bSize=b.__iterate(function(v,k){if(notAssociative?!a.has(v):flipped?!is(v,a.get(k,NOT_SET)):!is(a.get(k,NOT_SET),v)){allEqual=false;return false}});return allEqual&&a.size===bSize}createClass(Repeat,IndexedSeq);function Repeat(value,times){if(!(this instanceof Repeat)){return new Repeat(value,times)}this._value=value;this.size=times===undefined?Infinity:Math.max(0,times);if(this.size===0){if(EMPTY_REPEAT){return EMPTY_REPEAT}EMPTY_REPEAT=this}}Repeat.prototype.toString=function(){if(this.size===0){return"Repeat []"}return"Repeat [ "+this._value+" "+this.size+" times ]"};Repeat.prototype.get=function(index,notSetValue){return this.has(index)?this._value:notSetValue};Repeat.prototype.includes=function(searchValue){return is(this._value,searchValue)};Repeat.prototype.slice=function(begin,end){var size=this.size;return wholeSlice(begin,end,size)?this:new Repeat(this._value,resolveEnd(end,size)-resolveBegin(begin,size))};Repeat.prototype.reverse=function(){return this};Repeat.prototype.indexOf=function(searchValue){if(is(this._value,searchValue)){return 0}return-1};Repeat.prototype.lastIndexOf=function(searchValue){if(is(this._value,searchValue)){return this.size}return-1};Repeat.prototype.__iterate=function(fn,reverse){for(var ii=0;ii=0&&possibleIndex=0&&indexmaxIndex?iteratorDone():iteratorValue(type,ii++,v)})};Range.prototype.equals=function(other){return other instanceof Range?this._start===other._start&&this._end===other._end&&this._step===other._step:deepEqual(this,other)};var EMPTY_RANGE;createClass(Collection,Iterable);function Collection(){throw TypeError("Abstract")}createClass(KeyedCollection,Collection);function KeyedCollection(){}createClass(IndexedCollection,Collection);function IndexedCollection(){}createClass(SetCollection,Collection);function SetCollection(){}Collection.Keyed=KeyedCollection;Collection.Indexed=IndexedCollection;Collection.Set=SetCollection;var imul=typeof Math.imul==="function"&&Math.imul(4294967295,2)===-2?Math.imul:function imul(a,b){a=a|0;b=b|0;var c=a&65535;var d=b&65535;return c*d+((a>>>16)*d+c*(b>>>16)<<16>>>0)|0};function smi(i32){return i32>>>1&1073741824|i32&3221225471}function hash(o){if(o===false||o===null||o===undefined){return 0}if(typeof o.valueOf==="function"){o=o.valueOf();if(o===false||o===null||o===undefined){return 0}}if(o===true){return 1}var type=typeof o;if(type==="number"){if(o!==o||o===Infinity){return 0}var h=o|0;if(h!==o){h^=o*4294967295}while(o>4294967295){o/=4294967295;h^=o}return smi(h)}if(type==="string"){return o.length>STRING_HASH_CACHE_MIN_STRLEN?cachedHashString(o):hashString(o)}if(typeof o.hashCode==="function"){return o.hashCode()}if(type==="object"){return hashJSObj(o)}if(typeof o.toString==="function"){return hashString(o.toString())}throw new Error("Value type "+type+" cannot be hashed.")}function cachedHashString(string){var hash=stringHashCache[string];if(hash===undefined){hash=hashString(string);if(STRING_HASH_CACHE_SIZE===STRING_HASH_CACHE_MAX_SIZE){STRING_HASH_CACHE_SIZE=0;stringHashCache={}}STRING_HASH_CACHE_SIZE++;stringHashCache[string]=hash}return hash}function hashString(string){var hash=0;for(var ii=0;ii0){switch(node.nodeType){case 1:return node.uniqueID;case 9:return node.documentElement&&node.documentElement.uniqueID}}}var usingWeakMap=typeof WeakMap==="function";var weakMap;if(usingWeakMap){weakMap=new WeakMap}var objHashUID=0;var UID_HASH_KEY="__immutablehash__";if(typeof Symbol==="function"){UID_HASH_KEY=Symbol(UID_HASH_KEY)}var STRING_HASH_CACHE_MIN_STRLEN=16;var STRING_HASH_CACHE_MAX_SIZE=255;var STRING_HASH_CACHE_SIZE=0;var stringHashCache={};function assertNotInfinite(size){invariant(size!==Infinity,"Cannot perform this action with an infinite size.")}createClass(Map,KeyedCollection);function Map(value){return value===null||value===undefined?emptyMap():isMap(value)&&!isOrdered(value)?value:emptyMap().withMutations(function(map){var iter=KeyedIterable(value);assertNotInfinite(iter.size);iter.forEach(function(v,k){return map.set(k,v)})})}Map.of=function(){var keyValues=SLICE$0.call(arguments,0);return emptyMap().withMutations(function(map){for(var i=0;i=keyValues.length){throw new Error("Missing value for key: "+keyValues[i])}map.set(keyValues[i],keyValues[i+1])}})};Map.prototype.toString=function(){return this.__toString("Map {","}")};Map.prototype.get=function(k,notSetValue){return this._root?this._root.get(0,undefined,k,notSetValue):notSetValue};Map.prototype.set=function(k,v){return updateMap(this,k,v)};Map.prototype.setIn=function(keyPath,v){return this.updateIn(keyPath,NOT_SET,function(){return v})};Map.prototype.remove=function(k){return updateMap(this,k,NOT_SET)};Map.prototype.deleteIn=function(keyPath){return this.updateIn(keyPath,function(){return NOT_SET})};Map.prototype.update=function(k,notSetValue,updater){return arguments.length===1?k(this):this.updateIn([k],notSetValue,updater)};Map.prototype.updateIn=function(keyPath,notSetValue,updater){if(!updater){updater=notSetValue;notSetValue=undefined}var updatedValue=updateInDeepMap(this,forceIterator(keyPath),notSetValue,updater);return updatedValue===NOT_SET?undefined:updatedValue};Map.prototype.clear=function(){if(this.size===0){return this}if(this.__ownerID){this.size=0;this._root=null;this.__hash=undefined;this.__altered=true;return this}return emptyMap()};Map.prototype.merge=function(){return mergeIntoMapWith(this,undefined,arguments)};Map.prototype.mergeWith=function(merger){var iters=SLICE$0.call(arguments,1);return mergeIntoMapWith(this,merger,iters)};Map.prototype.mergeIn=function(keyPath){var iters=SLICE$0.call(arguments,1);return this.updateIn(keyPath,emptyMap(),function(m){return typeof m.merge==="function"?m.merge.apply(m,iters):iters[iters.length-1]})};Map.prototype.mergeDeep=function(){return mergeIntoMapWith(this,deepMerger,arguments)};Map.prototype.mergeDeepWith=function(merger){var iters=SLICE$0.call(arguments,1);return mergeIntoMapWith(this,deepMergerWith(merger),iters)};Map.prototype.mergeDeepIn=function(keyPath){var iters=SLICE$0.call(arguments,1);return this.updateIn(keyPath,emptyMap(),function(m){return typeof m.mergeDeep==="function"?m.mergeDeep.apply(m,iters):iters[iters.length-1]})};Map.prototype.sort=function(comparator){return OrderedMap(sortFactory(this,comparator))};Map.prototype.sortBy=function(mapper,comparator){return OrderedMap(sortFactory(this,comparator,mapper))};Map.prototype.withMutations=function(fn){var mutable=this.asMutable();fn(mutable);return mutable.wasAltered()?mutable.__ensureOwner(this.__ownerID):this};Map.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new OwnerID)};Map.prototype.asImmutable=function(){return this.__ensureOwner()};Map.prototype.wasAltered=function(){return this.__altered};Map.prototype.__iterator=function(type,reverse){return new MapIterator(this,type,reverse)};Map.prototype.__iterate=function(fn,reverse){var this$0=this;var iterations=0;this._root&&this._root.iterate(function(entry){iterations++;return fn(entry[1],entry[0],this$0)},reverse);return iterations};Map.prototype.__ensureOwner=function(ownerID){if(ownerID===this.__ownerID){return this}if(!ownerID){this.__ownerID=ownerID;this.__altered=false;return this}return makeMap(this.size,this._root,ownerID,this.__hash)};function isMap(maybeMap){return!!(maybeMap&&maybeMap[IS_MAP_SENTINEL])}Map.isMap=isMap;var IS_MAP_SENTINEL="@@__IMMUTABLE_MAP__@@";var MapPrototype=Map.prototype;MapPrototype[IS_MAP_SENTINEL]=true;MapPrototype[DELETE]=MapPrototype.remove;MapPrototype.removeIn=MapPrototype.deleteIn;function ArrayMapNode(ownerID,entries){this.ownerID=ownerID;this.entries=entries}ArrayMapNode.prototype.get=function(shift,keyHash,key,notSetValue){var entries=this.entries;for(var ii=0,len=entries.length;ii=MAX_ARRAY_MAP_SIZE){return createNodes(ownerID,entries,key,value)}var isEditable=ownerID&&ownerID===this.ownerID;var newEntries=isEditable?entries:arrCopy(entries);if(exists){if(removed){idx===len-1?newEntries.pop():newEntries[idx]=newEntries.pop()}else{newEntries[idx]=[key,value]}}else{newEntries.push([key,value])}if(isEditable){this.entries=newEntries;return this}return new ArrayMapNode(ownerID,newEntries)};function BitmapIndexedNode(ownerID,bitmap,nodes){this.ownerID=ownerID;this.bitmap=bitmap;this.nodes=nodes}BitmapIndexedNode.prototype.get=function(shift,keyHash,key,notSetValue){if(keyHash===undefined){keyHash=hash(key)}var bit=1<<((shift===0?keyHash:keyHash>>>shift)&MASK);var bitmap=this.bitmap;return(bitmap&bit)===0?notSetValue:this.nodes[popCount(bitmap&bit-1)].get(shift+SHIFT,keyHash,key,notSetValue)};BitmapIndexedNode.prototype.update=function(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){if(keyHash===undefined){keyHash=hash(key)}var keyHashFrag=(shift===0?keyHash:keyHash>>>shift)&MASK;var bit=1<=MAX_BITMAP_INDEXED_SIZE){return expandNodes(ownerID,nodes,bitmap,keyHashFrag,newNode)}if(exists&&!newNode&&nodes.length===2&&isLeafNode(nodes[idx^1])){return nodes[idx^1]}if(exists&&newNode&&nodes.length===1&&isLeafNode(newNode)){return newNode}var isEditable=ownerID&&ownerID===this.ownerID;var newBitmap=exists?newNode?bitmap:bitmap^bit:bitmap|bit;var newNodes=exists?newNode?setIn(nodes,idx,newNode,isEditable):spliceOut(nodes,idx,isEditable):spliceIn(nodes,idx,newNode,isEditable);if(isEditable){this.bitmap=newBitmap;this.nodes=newNodes;return this}return new BitmapIndexedNode(ownerID,newBitmap,newNodes)};function HashArrayMapNode(ownerID,count,nodes){this.ownerID=ownerID;this.count=count;this.nodes=nodes}HashArrayMapNode.prototype.get=function(shift,keyHash,key,notSetValue){if(keyHash===undefined){keyHash=hash(key)}var idx=(shift===0?keyHash:keyHash>>>shift)&MASK;var node=this.nodes[idx];return node?node.get(shift+SHIFT,keyHash,key,notSetValue):notSetValue};HashArrayMapNode.prototype.update=function(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){if(keyHash===undefined){keyHash=hash(key)}var idx=(shift===0?keyHash:keyHash>>>shift)&MASK;var removed=value===NOT_SET;var nodes=this.nodes;var node=nodes[idx];if(removed&&!node){return this}var newNode=updateNode(node,ownerID,shift+SHIFT,keyHash,key,value,didChangeSize,didAlter);if(newNode===node){return this}var newCount=this.count;if(!node){newCount++}else if(!newNode){newCount--;if(newCount>>shift)&MASK;var idx2=(shift===0?keyHash:keyHash>>>shift)&MASK;var newNode;var nodes=idx1===idx2?[mergeIntoNode(node,ownerID,shift+SHIFT,keyHash,entry)]:(newNode=new ValueNode(ownerID,keyHash,entry),idx1>>=1){expandedNodes[ii]=bitmap&1?nodes[count++]:undefined}expandedNodes[including]=node;return new HashArrayMapNode(ownerID,count+1,expandedNodes)}function mergeIntoMapWith(map,merger,iterables){var iters=[];for(var ii=0;ii>1&1431655765);x=(x&858993459)+(x>>2&858993459);x=x+(x>>4)&252645135;x=x+(x>>8);x=x+(x>>16);return x&127}function setIn(array,idx,val,canEdit){var newArray=canEdit?array:arrCopy(array);newArray[idx]=val;return newArray}function spliceIn(array,idx,val,canEdit){var newLen=array.length+1;if(canEdit&&idx+1===newLen){array[idx]=val;return array}var newArray=new Array(newLen);var after=0;for(var ii=0;ii0&&size=0&&index>>level&MASK;if(originIndex>=this.array.length){return new VNode([],ownerID)}var removingFirst=originIndex===0;var newChild;if(level>0){var oldChild=this.array[originIndex];newChild=oldChild&&oldChild.removeBefore(ownerID,level-SHIFT,index);if(newChild===oldChild&&removingFirst){return this}}if(removingFirst&&!newChild){return this}var editable=editableVNode(this,ownerID);if(!removingFirst){for(var ii=0;ii>>level&MASK;if(sizeIndex>=this.array.length){return this}var newChild;if(level>0){var oldChild=this.array[sizeIndex];newChild=oldChild&&oldChild.removeAfter(ownerID,level-SHIFT,index);if(newChild===oldChild&&sizeIndex===this.array.length-1){return this}}var editable=editableVNode(this,ownerID);editable.array.splice(sizeIndex+1);if(newChild){editable.array[sizeIndex]=newChild}return editable};var DONE={};function iterateList(list,reverse){var left=list._origin;var right=list._capacity;var tailPos=getTailOffset(right);var tail=list._tail;return iterateNodeOrLeaf(list._root,list._level,0);function iterateNodeOrLeaf(node,level,offset){return level===0?iterateLeaf(node,offset):iterateNode(node,level,offset)}function iterateLeaf(node,offset){var array=offset===tailPos?tail&&tail.array:node&&node.array;var from=offset>left?0:left-offset;var to=right-offset;if(to>SIZE){to=SIZE}return function(){if(from===to){return DONE}var idx=reverse?--to:from++;return array&&array[idx]}}function iterateNode(node,level,offset){var values;var array=node&&node.array;var from=offset>left?0:left-offset>>level;var to=(right-offset>>level)+1;if(to>SIZE){to=SIZE}return function(){do{if(values){var value=values();if(value!==DONE){return value}values=null}if(from===to){return DONE}var idx=reverse?--to:from++;values=iterateNodeOrLeaf(array&&array[idx],level-SHIFT,offset+(idx<=list.size||index<0){return list.withMutations(function(list){index<0?setListBounds(list,index).set(0,value):setListBounds(list,0,index+1).set(index,value)})}index+=list._origin;var newTail=list._tail;var newRoot=list._root;var didAlter=MakeRef(DID_ALTER);if(index>=getTailOffset(list._capacity)){newTail=updateVNode(newTail,list.__ownerID,0,index,value,didAlter)}else{newRoot=updateVNode(newRoot,list.__ownerID,list._level,index,value,didAlter)}if(!didAlter.value){return list}if(list.__ownerID){list._root=newRoot;list._tail=newTail;list.__hash=undefined;list.__altered=true;return list}return makeList(list._origin,list._capacity,list._level,newRoot,newTail)}function updateVNode(node,ownerID,level,index,value,didAlter){var idx=index>>>level&MASK;var nodeHas=node&&idx0){var lowerNode=node&&node.array[idx];var newLowerNode=updateVNode(lowerNode,ownerID,level-SHIFT,index,value,didAlter);if(newLowerNode===lowerNode){return node}newNode=editableVNode(node,ownerID);newNode.array[idx]=newLowerNode;return newNode}if(nodeHas&&node.array[idx]===value){return node}SetRef(didAlter);newNode=editableVNode(node,ownerID);if(value===undefined&&idx===newNode.array.length-1){newNode.array.pop()}else{newNode.array[idx]=value}return newNode}function editableVNode(node,ownerID){if(ownerID&&node&&ownerID===node.ownerID){return node}return new VNode(node?node.array.slice():[],ownerID)}function listNodeFor(list,rawIndex){if(rawIndex>=getTailOffset(list._capacity)){return list._tail}if(rawIndex<1<0){node=node.array[rawIndex>>>level&MASK];level-=SHIFT}return node}}function setListBounds(list,begin,end){if(begin!==undefined){begin=begin|0}if(end!==undefined){end=end|0}var owner=list.__ownerID||new OwnerID;var oldOrigin=list._origin;var oldCapacity=list._capacity;var newOrigin=oldOrigin+begin;var newCapacity=end===undefined?oldCapacity:end<0?oldCapacity+end:oldOrigin+end;if(newOrigin===oldOrigin&&newCapacity===oldCapacity){return list}if(newOrigin>=newCapacity){return list.clear()}var newLevel=list._level;var newRoot=list._root;var offsetShift=0;while(newOrigin+offsetShift<0){newRoot=new VNode(newRoot&&newRoot.array.length?[undefined,newRoot]:[],owner);newLevel+=SHIFT;offsetShift+=1<=1<oldTailOffset?new VNode([],owner):oldTail;if(oldTail&&newTailOffset>oldTailOffset&&newOriginSHIFT;level-=SHIFT){var idx=oldTailOffset>>>level&MASK;node=node.array[idx]=editableVNode(node.array[idx],owner)}node.array[oldTailOffset>>>SHIFT&MASK]=oldTail}if(newCapacity=newTailOffset){newOrigin-=newTailOffset;newCapacity-=newTailOffset;newLevel=SHIFT;newRoot=null;newTail=newTail&&newTail.removeBefore(owner,0,newOrigin)}else if(newOrigin>oldOrigin||newTailOffset>>newLevel&MASK;if(beginIndex!==newTailOffset>>>newLevel&MASK){break}if(beginIndex){offsetShift+=(1<oldOrigin){newRoot=newRoot.removeBefore(owner,newLevel,newOrigin-offsetShift)}if(newRoot&&newTailOffsetmaxSize){maxSize=iter.size}if(!isIterable(value)){iter=iter.map(function(v){return fromJS(v)})}iters.push(iter)}if(maxSize>list.size){list=list.setSize(maxSize)}return mergeIntoCollectionWith(list,merger,iters)}function getTailOffset(size){return size>>SHIFT<=SIZE&&list.size>=map.size*2){newList=list.filter(function(entry,idx){return entry!==undefined&&i!==idx});newMap=newList.toKeyedSeq().map(function(entry){return entry[0]}).flip().toMap();if(omap.__ownerID){newMap.__ownerID=newList.__ownerID=omap.__ownerID}}else{newMap=map.remove(k);newList=i===list.size-1?list.pop():list.set(i,undefined)}}else{if(has){if(v===list.get(i)[1]){return omap}newMap=map;newList=list.set(i,[k,v])}else{newMap=map.set(k,list.size);newList=list.set(list.size,[k,v])}}if(omap.__ownerID){omap.size=newMap.size;omap._map=newMap;omap._list=newList;omap.__hash=undefined;return omap}return makeOrderedMap(newMap,newList)}createClass(ToKeyedSequence,KeyedSeq);function ToKeyedSequence(indexed,useKeys){this._iter=indexed;this._useKeys=useKeys;this.size=indexed.size}ToKeyedSequence.prototype.get=function(key,notSetValue){return this._iter.get(key,notSetValue)};ToKeyedSequence.prototype.has=function(key){return this._iter.has(key)};ToKeyedSequence.prototype.valueSeq=function(){return this._iter.valueSeq()};ToKeyedSequence.prototype.reverse=function(){var this$0=this;var reversedSequence=reverseFactory(this,true);if(!this._useKeys){reversedSequence.valueSeq=function(){return this$0._iter.toSeq().reverse()}}return reversedSequence};ToKeyedSequence.prototype.map=function(mapper,context){var this$0=this;var mappedSequence=mapFactory(this,mapper,context);if(!this._useKeys){mappedSequence.valueSeq=function(){return this$0._iter.toSeq().map(mapper,context)}}return mappedSequence};ToKeyedSequence.prototype.__iterate=function(fn,reverse){var this$0=this;var ii;return this._iter.__iterate(this._useKeys?function(v,k){return fn(v,k,this$0)}:(ii=reverse?resolveSize(this):0,function(v){return fn(v,reverse?--ii:ii++,this$0)}),reverse)};ToKeyedSequence.prototype.__iterator=function(type,reverse){if(this._useKeys){return this._iter.__iterator(type,reverse)}var iterator=this._iter.__iterator(ITERATE_VALUES,reverse);var ii=reverse?resolveSize(this):0;return new Iterator(function(){var step=iterator.next();return step.done?step:iteratorValue(type,reverse?--ii:ii++,step.value,step)})};ToKeyedSequence.prototype[IS_ORDERED_SENTINEL]=true;createClass(ToIndexedSequence,IndexedSeq);function ToIndexedSequence(iter){this._iter=iter;this.size=iter.size}ToIndexedSequence.prototype.includes=function(value){return this._iter.includes(value)};ToIndexedSequence.prototype.__iterate=function(fn,reverse){var this$0=this;var iterations=0;return this._iter.__iterate(function(v){return fn(v,iterations++,this$0)},reverse)};ToIndexedSequence.prototype.__iterator=function(type,reverse){var iterator=this._iter.__iterator(ITERATE_VALUES,reverse);var iterations=0;return new Iterator(function(){var step=iterator.next();return step.done?step:iteratorValue(type,iterations++,step.value,step)})};createClass(ToSetSequence,SetSeq);function ToSetSequence(iter){this._iter=iter;this.size=iter.size}ToSetSequence.prototype.has=function(key){return this._iter.includes(key)};ToSetSequence.prototype.__iterate=function(fn,reverse){var this$0=this;return this._iter.__iterate(function(v){return fn(v,v,this$0)},reverse)};ToSetSequence.prototype.__iterator=function(type,reverse){var iterator=this._iter.__iterator(ITERATE_VALUES,reverse);return new Iterator(function(){var step=iterator.next();return step.done?step:iteratorValue(type,step.value,step.value,step)})};createClass(FromEntriesSequence,KeyedSeq);function FromEntriesSequence(entries){this._iter=entries;this.size=entries.size}FromEntriesSequence.prototype.entrySeq=function(){return this._iter.toSeq()};FromEntriesSequence.prototype.__iterate=function(fn,reverse){var this$0=this;return this._iter.__iterate(function(entry){if(entry){validateEntry(entry);var indexedIterable=isIterable(entry);return fn(indexedIterable?entry.get(1):entry[1],indexedIterable?entry.get(0):entry[0],this$0)}},reverse)};FromEntriesSequence.prototype.__iterator=function(type,reverse){var iterator=this._iter.__iterator(ITERATE_VALUES,reverse);return new Iterator(function(){while(true){var step=iterator.next();if(step.done){return step}var entry=step.value;if(entry){validateEntry(entry);var indexedIterable=isIterable(entry);return iteratorValue(type,indexedIterable?entry.get(0):entry[0],indexedIterable?entry.get(1):entry[1],step)}}})};ToIndexedSequence.prototype.cacheResult=ToKeyedSequence.prototype.cacheResult=ToSetSequence.prototype.cacheResult=FromEntriesSequence.prototype.cacheResult=cacheResultThrough;function flipFactory(iterable){var flipSequence=makeSequence(iterable);flipSequence._iter=iterable;flipSequence.size=iterable.size;flipSequence.flip=function(){return iterable};flipSequence.reverse=function(){var reversedSequence=iterable.reverse.apply(this);reversedSequence.flip=function(){return iterable.reverse()};return reversedSequence};flipSequence.has=function(key){return iterable.includes(key)};flipSequence.includes=function(key){return iterable.has(key)};flipSequence.cacheResult=cacheResultThrough;flipSequence.__iterateUncached=function(fn,reverse){var this$0=this;return iterable.__iterate(function(v,k){return fn(k,v,this$0)!==false},reverse)};flipSequence.__iteratorUncached=function(type,reverse){if(type===ITERATE_ENTRIES){var iterator=iterable.__iterator(type,reverse);return new Iterator(function(){var step=iterator.next();if(!step.done){var k=step.value[0];step.value[0]=step.value[1];step.value[1]=k}return step})}return iterable.__iterator(type===ITERATE_VALUES?ITERATE_KEYS:ITERATE_VALUES,reverse)};return flipSequence}function mapFactory(iterable,mapper,context){var mappedSequence=makeSequence(iterable);mappedSequence.size=iterable.size;mappedSequence.has=function(key){return iterable.has(key)};mappedSequence.get=function(key,notSetValue){var v=iterable.get(key,NOT_SET);return v===NOT_SET?notSetValue:mapper.call(context,v,key,iterable)};mappedSequence.__iterateUncached=function(fn,reverse){var this$0=this;return iterable.__iterate(function(v,k,c){return fn(mapper.call(context,v,k,c),k,this$0)!==false},reverse)};mappedSequence.__iteratorUncached=function(type,reverse){var iterator=iterable.__iterator(ITERATE_ENTRIES,reverse);return new Iterator(function(){var step=iterator.next();if(step.done){return step}var entry=step.value;var key=entry[0];return iteratorValue(type,key,mapper.call(context,entry[1],key,iterable),step)})};return mappedSequence}function reverseFactory(iterable,useKeys){var reversedSequence=makeSequence(iterable);reversedSequence._iter=iterable;reversedSequence.size=iterable.size;reversedSequence.reverse=function(){return iterable};if(iterable.flip){reversedSequence.flip=function(){var flipSequence=flipFactory(iterable);flipSequence.reverse=function(){return iterable.flip()};return flipSequence}}reversedSequence.get=function(key,notSetValue){return iterable.get(useKeys?key:-1-key,notSetValue)};reversedSequence.has=function(key){return iterable.has(useKeys?key:-1-key)};reversedSequence.includes=function(value){return iterable.includes(value)};reversedSequence.cacheResult=cacheResultThrough;reversedSequence.__iterate=function(fn,reverse){var this$0=this;return iterable.__iterate(function(v,k){return fn(v,k,this$0)},!reverse)};reversedSequence.__iterator=function(type,reverse){return iterable.__iterator(type,!reverse)};return reversedSequence}function filterFactory(iterable,predicate,context,useKeys){var filterSequence=makeSequence(iterable);if(useKeys){filterSequence.has=function(key){var v=iterable.get(key,NOT_SET);return v!==NOT_SET&&!!predicate.call(context,v,key,iterable)};filterSequence.get=function(key,notSetValue){var v=iterable.get(key,NOT_SET);return v!==NOT_SET&&predicate.call(context,v,key,iterable)?v:notSetValue}}filterSequence.__iterateUncached=function(fn,reverse){var this$0=this;var iterations=0;iterable.__iterate(function(v,k,c){if(predicate.call(context,v,k,c)){iterations++;return fn(v,useKeys?k:iterations-1,this$0)}},reverse);return iterations};filterSequence.__iteratorUncached=function(type,reverse){var iterator=iterable.__iterator(ITERATE_ENTRIES,reverse);var iterations=0;return new Iterator(function(){while(true){var step=iterator.next();if(step.done){return step}var entry=step.value;var key=entry[0];var value=entry[1];if(predicate.call(context,value,key,iterable)){return iteratorValue(type,useKeys?key:iterations++,value,step)}}})};return filterSequence}function countByFactory(iterable,grouper,context){var groups=Map().asMutable();iterable.__iterate(function(v,k){groups.update(grouper.call(context,v,k,iterable),0,function(a){return a+1})});return groups.asImmutable()}function groupByFactory(iterable,grouper,context){var isKeyedIter=isKeyed(iterable);var groups=(isOrdered(iterable)?OrderedMap():Map()).asMutable();iterable.__iterate(function(v,k){groups.update(grouper.call(context,v,k,iterable),function(a){return a=a||[],a.push(isKeyedIter?[k,v]:v),a})});var coerce=iterableClass(iterable);return groups.map(function(arr){return reify(iterable,coerce(arr))})}function sliceFactory(iterable,begin,end,useKeys){var originalSize=iterable.size;if(begin!==undefined){begin=begin|0}if(end!==undefined){if(end===Infinity){end=originalSize}else{end=end|0}}if(wholeSlice(begin,end,originalSize)){return iterable}var resolvedBegin=resolveBegin(begin,originalSize);var resolvedEnd=resolveEnd(end,originalSize);if(resolvedBegin!==resolvedBegin||resolvedEnd!==resolvedEnd){return sliceFactory(iterable.toSeq().cacheResult(),begin,end,useKeys)}var resolvedSize=resolvedEnd-resolvedBegin;var sliceSize;if(resolvedSize===resolvedSize){sliceSize=resolvedSize<0?0:resolvedSize}var sliceSeq=makeSequence(iterable);sliceSeq.size=sliceSize===0?sliceSize:iterable.size&&sliceSize||undefined;if(!useKeys&&isSeq(iterable)&&sliceSize>=0){sliceSeq.get=function(index,notSetValue){index=wrapIndex(this,index);return index>=0&&indexsliceSize){return iteratorDone()}var step=iterator.next();if(useKeys||type===ITERATE_VALUES){return step}else if(type===ITERATE_KEYS){return iteratorValue(type,iterations-1,undefined,step)}else{return iteratorValue(type,iterations-1,step.value[1],step)}})};return sliceSeq}function takeWhileFactory(iterable,predicate,context){var takeSequence=makeSequence(iterable);takeSequence.__iterateUncached=function(fn,reverse){var this$0=this;if(reverse){return this.cacheResult().__iterate(fn,reverse)}var iterations=0;iterable.__iterate(function(v,k,c){return predicate.call(context,v,k,c)&&++iterations&&fn(v,k,this$0)});return iterations};takeSequence.__iteratorUncached=function(type,reverse){var this$0=this;if(reverse){return this.cacheResult().__iterator(type,reverse)}var iterator=iterable.__iterator(ITERATE_ENTRIES,reverse);var iterating=true;return new Iterator(function(){if(!iterating){return iteratorDone()}var step=iterator.next();if(step.done){return step}var entry=step.value;var k=entry[0];var v=entry[1];if(!predicate.call(context,v,k,this$0)){iterating=false;return iteratorDone()}return type===ITERATE_ENTRIES?step:iteratorValue(type,k,v,step)})};return takeSequence}function skipWhileFactory(iterable,predicate,context,useKeys){var skipSequence=makeSequence(iterable);skipSequence.__iterateUncached=function(fn,reverse){var this$0=this;if(reverse){return this.cacheResult().__iterate(fn,reverse)}var isSkipping=true;var iterations=0;iterable.__iterate(function(v,k,c){if(!(isSkipping&&(isSkipping=predicate.call(context,v,k,c)))){iterations++;return fn(v,useKeys?k:iterations-1,this$0)}});return iterations};skipSequence.__iteratorUncached=function(type,reverse){var this$0=this;if(reverse){return this.cacheResult().__iterator(type,reverse)}var iterator=iterable.__iterator(ITERATE_ENTRIES,reverse);var skipping=true;var iterations=0;return new Iterator(function(){var step,k,v;do{step=iterator.next();if(step.done){if(useKeys||type===ITERATE_VALUES){return step}else if(type===ITERATE_KEYS){return iteratorValue(type,iterations++,undefined,step)}else{return iteratorValue(type,iterations++,step.value[1],step)}}var entry=step.value;k=entry[0];v=entry[1];skipping&&(skipping=predicate.call(context,v,k,this$0))}while(skipping);return type===ITERATE_ENTRIES?step:iteratorValue(type,k,v,step)})};return skipSequence}function concatFactory(iterable,values){var isKeyedIterable=isKeyed(iterable);var iters=[iterable].concat(values).map(function(v){if(!isIterable(v)){v=isKeyedIterable?keyedSeqFromValue(v):indexedSeqFromValue(Array.isArray(v)?v:[v])}else if(isKeyedIterable){v=KeyedIterable(v)}return v}).filter(function(v){return v.size!==0});if(iters.length===0){return iterable}if(iters.length===1){var singleton=iters[0];if(singleton===iterable||isKeyedIterable&&isKeyed(singleton)||isIndexed(iterable)&&isIndexed(singleton)){return singleton}}var concatSeq=new ArraySeq(iters);if(isKeyedIterable){concatSeq=concatSeq.toKeyedSeq()}else if(!isIndexed(iterable)){concatSeq=concatSeq.toSetSeq()}concatSeq=concatSeq.flatten(true);concatSeq.size=iters.reduce(function(sum,seq){if(sum!==undefined){var size=seq.size;if(size!==undefined){return sum+size}}},0);return concatSeq}function flattenFactory(iterable,depth,useKeys){var flatSequence=makeSequence(iterable);flatSequence.__iterateUncached=function(fn,reverse){var iterations=0;var stopped=false;function flatDeep(iter,currentDepth){var this$0=this;iter.__iterate(function(v,k){if((!depth||currentDepth0}function zipWithFactory(keyIter,zipper,iters){var zipSequence=makeSequence(keyIter);zipSequence.size=new ArraySeq(iters).map(function(i){return i.size}).min();zipSequence.__iterate=function(fn,reverse){var iterator=this.__iterator(ITERATE_VALUES,reverse);var step;var iterations=0;while(!(step=iterator.next()).done){if(fn(step.value,iterations++,this)===false){break}}return iterations};zipSequence.__iteratorUncached=function(type,reverse){var iterators=iters.map(function(i){return i=Iterable(i),getIterator(reverse?i.reverse():i)});var iterations=0;var isDone=false;return new Iterator(function(){var steps;if(!isDone){steps=iterators.map(function(i){return i.next()});isDone=steps.some(function(s){return s.done})}if(isDone){return iteratorDone()}return iteratorValue(type,iterations++,zipper.apply(null,steps.map(function(s){return s.value})))})};return zipSequence}function reify(iter,seq){return isSeq(iter)?seq:iter.constructor(seq)}function validateEntry(entry){if(entry!==Object(entry)){throw new TypeError("Expected [K, V] tuple: "+entry)}}function resolveSize(iter){assertNotInfinite(iter.size);return ensureSize(iter)}function iterableClass(iterable){return isKeyed(iterable)?KeyedIterable:isIndexed(iterable)?IndexedIterable:SetIterable}function makeSequence(iterable){return Object.create((isKeyed(iterable)?KeyedSeq:isIndexed(iterable)?IndexedSeq:SetSeq).prototype)}function cacheResultThrough(){if(this._iter.cacheResult){this._iter.cacheResult();this.size=this._iter.size;return this}else{return Seq.prototype.cacheResult.call(this)}}function defaultComparator(a,b){return a>b?1:a=0;ii--){head={value:arguments[ii],next:head}}if(this.__ownerID){this.size=newSize;this._head=head;this.__hash=undefined;this.__altered=true;return this}return makeStack(newSize,head)};Stack.prototype.pushAll=function(iter){iter=IndexedIterable(iter);if(iter.size===0){return this}assertNotInfinite(iter.size);var newSize=this.size;var head=this._head;iter.reverse().forEach(function(value){newSize++;head={value:value,next:head}});if(this.__ownerID){this.size=newSize;this._head=head;this.__hash=undefined;this.__altered=true;return this}return makeStack(newSize,head)};Stack.prototype.pop=function(){return this.slice(1)};Stack.prototype.unshift=function(){return this.push.apply(this,arguments)};Stack.prototype.unshiftAll=function(iter){return this.pushAll(iter)};Stack.prototype.shift=function(){return this.pop.apply(this,arguments)};Stack.prototype.clear=function(){if(this.size===0){return this}if(this.__ownerID){this.size=0;this._head=undefined;this.__hash=undefined;this.__altered=true;return this}return emptyStack()};Stack.prototype.slice=function(begin,end){if(wholeSlice(begin,end,this.size)){return this}var resolvedBegin=resolveBegin(begin,this.size);var resolvedEnd=resolveEnd(end,this.size);if(resolvedEnd!==this.size){return IndexedCollection.prototype.slice.call(this,begin,end)}var newSize=this.size-resolvedBegin;var head=this._head;while(resolvedBegin--){head=head.next}if(this.__ownerID){this.size=newSize;this._head=head;this.__hash=undefined;this.__altered=true;return this}return makeStack(newSize,head)};Stack.prototype.__ensureOwner=function(ownerID){if(ownerID===this.__ownerID){return this}if(!ownerID){this.__ownerID=ownerID;this.__altered=false;return this}return makeStack(this.size,this._head,ownerID,this.__hash)};Stack.prototype.__iterate=function(fn,reverse){if(reverse){return this.reverse().__iterate(fn)}var iterations=0;var node=this._head;while(node){if(fn(node.value,iterations++,this)===false){break}node=node.next}return iterations};Stack.prototype.__iterator=function(type,reverse){if(reverse){return this.reverse().__iterator(type)}var iterations=0;var node=this._head;return new Iterator(function(){if(node){var value=node.value;node=node.next;return iteratorValue(type,iterations++,value)}return iteratorDone()})};function isStack(maybeStack){return!!(maybeStack&&maybeStack[IS_STACK_SENTINEL])}Stack.isStack=isStack;var IS_STACK_SENTINEL="@@__IMMUTABLE_STACK__@@";var StackPrototype=Stack.prototype;StackPrototype[IS_STACK_SENTINEL]=true;StackPrototype.withMutations=MapPrototype.withMutations;StackPrototype.asMutable=MapPrototype.asMutable;StackPrototype.asImmutable=MapPrototype.asImmutable;StackPrototype.wasAltered=MapPrototype.wasAltered;function makeStack(size,head,ownerID,hash){var map=Object.create(StackPrototype);map.size=size;map._head=head;map.__ownerID=ownerID;map.__hash=hash;map.__altered=false;return map}var EMPTY_STACK;function emptyStack(){return EMPTY_STACK||(EMPTY_STACK=makeStack(0))}function mixin(ctor,methods){var keyCopier=function(key){ctor.prototype[key]=methods[key]};Object.keys(methods).forEach(keyCopier);Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(methods).forEach(keyCopier);return ctor}Iterable.Iterator=Iterator;mixin(Iterable,{toArray:function(){assertNotInfinite(this.size);var array=new Array(this.size||0);this.valueSeq().__iterate(function(v,i){array[i]=v});return array},toIndexedSeq:function(){return new ToIndexedSequence(this)},toJS:function(){return this.toSeq().map(function(value){return value&&typeof value.toJS==="function"?value.toJS():value}).__toJS()},toJSON:function(){return this.toSeq().map(function(value){return value&&typeof value.toJSON==="function"?value.toJSON():value}).__toJS()},toKeyedSeq:function(){return new ToKeyedSequence(this,true)},toMap:function(){return Map(this.toKeyedSeq())},toObject:function(){assertNotInfinite(this.size);var object={};this.__iterate(function(v,k){object[k]=v});return object},toOrderedMap:function(){return OrderedMap(this.toKeyedSeq())},toOrderedSet:function(){return OrderedSet(isKeyed(this)?this.valueSeq():this)},toSet:function(){return Set(isKeyed(this)?this.valueSeq():this)},toSetSeq:function(){return new ToSetSequence(this)},toSeq:function(){return isIndexed(this)?this.toIndexedSeq():isKeyed(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return Stack(isKeyed(this)?this.valueSeq():this)},toList:function(){return List(isKeyed(this)?this.valueSeq():this)},toString:function(){return"[Iterable]"},__toString:function(head,tail){if(this.size===0){return head+tail}return head+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+tail},concat:function(){var values=SLICE$0.call(arguments,0);return reify(this,concatFactory(this,values))},includes:function(searchValue){return this.some(function(value){return is(value,searchValue)})},entries:function(){return this.__iterator(ITERATE_ENTRIES)},every:function(predicate,context){assertNotInfinite(this.size);var returnValue=true;this.__iterate(function(v,k,c){if(!predicate.call(context,v,k,c)){returnValue=false;return false}});return returnValue},filter:function(predicate,context){return reify(this,filterFactory(this,predicate,context,true))},find:function(predicate,context,notSetValue){var entry=this.findEntry(predicate,context);return entry?entry[1]:notSetValue},forEach:function(sideEffect,context){assertNotInfinite(this.size);return this.__iterate(context?sideEffect.bind(context):sideEffect)},join:function(separator){assertNotInfinite(this.size);separator=separator!==undefined?""+separator:",";var joined="";var isFirst=true;this.__iterate(function(v){isFirst?isFirst=false:joined+=separator;joined+=v!==null&&v!==undefined?v.toString():""});return joined},keys:function(){return this.__iterator(ITERATE_KEYS)},map:function(mapper,context){return reify(this,mapFactory(this,mapper,context))},reduce:function(reducer,initialReduction,context){assertNotInfinite(this.size);var reduction;var useFirst;if(arguments.length<2){useFirst=true}else{reduction=initialReduction}this.__iterate(function(v,k,c){if(useFirst){useFirst=false;reduction=v}else{reduction=reducer.call(context,reduction,v,k,c)}});return reduction},reduceRight:function(reducer,initialReduction,context){var reversed=this.toKeyedSeq().reverse();return reversed.reduce.apply(reversed,arguments)},reverse:function(){return reify(this,reverseFactory(this,true))},slice:function(begin,end){return reify(this,sliceFactory(this,begin,end,true))},some:function(predicate,context){return!this.every(not(predicate),context)},sort:function(comparator){return reify(this,sortFactory(this,comparator))},values:function(){return this.__iterator(ITERATE_VALUES)},butLast:function(){return this.slice(0,-1)},isEmpty:function(){return this.size!==undefined?this.size===0:!this.some(function(){return true})},count:function(predicate,context){return ensureSize(predicate?this.toSeq().filter(predicate,context):this)},countBy:function(grouper,context){return countByFactory(this,grouper,context)},equals:function(other){return deepEqual(this,other)},entrySeq:function(){var iterable=this;if(iterable._cache){return new ArraySeq(iterable._cache)}var entriesSequence=iterable.toSeq().map(entryMapper).toIndexedSeq();entriesSequence.fromEntrySeq=function(){return iterable.toSeq()};return entriesSequence},filterNot:function(predicate,context){return this.filter(not(predicate),context)},findEntry:function(predicate,context,notSetValue){var found=notSetValue;this.__iterate(function(v,k,c){if(predicate.call(context,v,k,c)){found=[k,v];return false}});return found},findKey:function(predicate,context){var entry=this.findEntry(predicate,context);return entry&&entry[0]},findLast:function(predicate,context,notSetValue){return this.toKeyedSeq().reverse().find(predicate,context,notSetValue)},findLastEntry:function(predicate,context,notSetValue){return this.toKeyedSeq().reverse().findEntry(predicate,context,notSetValue)},findLastKey:function(predicate,context){return this.toKeyedSeq().reverse().findKey(predicate,context)},first:function(){return this.find(returnTrue)},flatMap:function(mapper,context){return reify(this,flatMapFactory(this,mapper,context))},flatten:function(depth){return reify(this,flattenFactory(this,depth,true))},fromEntrySeq:function(){return new FromEntriesSequence(this)},get:function(searchKey,notSetValue){return this.find(function(_,key){return is(key,searchKey)},undefined,notSetValue)},getIn:function(searchKeyPath,notSetValue){var nested=this;var iter=forceIterator(searchKeyPath);var step;while(!(step=iter.next()).done){var key=step.value;nested=nested&&nested.get?nested.get(key,NOT_SET):NOT_SET;if(nested===NOT_SET){return notSetValue}}return nested},groupBy:function(grouper,context){return groupByFactory(this,grouper,context)},has:function(searchKey){return this.get(searchKey,NOT_SET)!==NOT_SET},hasIn:function(searchKeyPath){return this.getIn(searchKeyPath,NOT_SET)!==NOT_SET},isSubset:function(iter){iter=typeof iter.includes==="function"?iter:Iterable(iter);return this.every(function(value){return iter.includes(value)})},isSuperset:function(iter){iter=typeof iter.isSubset==="function"?iter:Iterable(iter);return iter.isSubset(this)},keyOf:function(searchValue){return this.findKey(function(value){return is(value,searchValue)})},keySeq:function(){return this.toSeq().map(keyMapper).toIndexedSeq()},last:function(){return this.toSeq().reverse().first()},lastKeyOf:function(searchValue){return this.toKeyedSeq().reverse().keyOf(searchValue)},max:function(comparator){return maxFactory(this,comparator)},maxBy:function(mapper,comparator){return maxFactory(this,comparator,mapper)},min:function(comparator){return maxFactory(this,comparator?neg(comparator):defaultNegComparator)},minBy:function(mapper,comparator){return maxFactory(this,comparator?neg(comparator):defaultNegComparator,mapper)},rest:function(){return this.slice(1)},skip:function(amount){return this.slice(Math.max(0,amount))},skipLast:function(amount){return reify(this,this.toSeq().reverse().skip(amount).reverse())},skipWhile:function(predicate,context){return reify(this,skipWhileFactory(this,predicate,context,true))},skipUntil:function(predicate,context){return this.skipWhile(not(predicate),context)},sortBy:function(mapper,comparator){return reify(this,sortFactory(this,comparator,mapper))},take:function(amount){return this.slice(0,Math.max(0,amount))},takeLast:function(amount){return reify(this,this.toSeq().reverse().take(amount).reverse())},takeWhile:function(predicate,context){return reify(this,takeWhileFactory(this,predicate,context))},takeUntil:function(predicate,context){return this.takeWhile(not(predicate),context)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=hashIterable(this))}});var IterablePrototype=Iterable.prototype;IterablePrototype[IS_ITERABLE_SENTINEL]=true;IterablePrototype[ITERATOR_SYMBOL]=IterablePrototype.values;IterablePrototype.__toJS=IterablePrototype.toArray;IterablePrototype.__toStringMapper=quoteString;IterablePrototype.inspect=IterablePrototype.toSource=function(){return this.toString()};IterablePrototype.chain=IterablePrototype.flatMap;IterablePrototype.contains=IterablePrototype.includes;mixin(KeyedIterable,{flip:function(){return reify(this,flipFactory(this))},mapEntries:function(mapper,context){var this$0=this;var iterations=0;return reify(this,this.toSeq().map(function(v,k){return mapper.call(context,[k,v],iterations++,this$0)}).fromEntrySeq())},mapKeys:function(mapper,context){var this$0=this;return reify(this,this.toSeq().flip().map(function(k,v){return mapper.call(context,k,v,this$0)}).flip())}});var KeyedIterablePrototype=KeyedIterable.prototype;KeyedIterablePrototype[IS_KEYED_SENTINEL]=true;KeyedIterablePrototype[ITERATOR_SYMBOL]=IterablePrototype.entries;KeyedIterablePrototype.__toJS=IterablePrototype.toObject;KeyedIterablePrototype.__toStringMapper=function(v,k){return JSON.stringify(k)+": "+quoteString(v)};mixin(IndexedIterable,{toKeyedSeq:function(){return new ToKeyedSequence(this,false)},filter:function(predicate,context){return reify(this,filterFactory(this,predicate,context,false))},findIndex:function(predicate,context){var entry=this.findEntry(predicate,context);return entry?entry[0]:-1},indexOf:function(searchValue){var key=this.keyOf(searchValue);return key===undefined?-1:key},lastIndexOf:function(searchValue){var key=this.lastKeyOf(searchValue);return key===undefined?-1:key},reverse:function(){return reify(this,reverseFactory(this,false))},slice:function(begin,end){return reify(this,sliceFactory(this,begin,end,false))},splice:function(index,removeNum){var numArgs=arguments.length;removeNum=Math.max(removeNum|0,0);if(numArgs===0||numArgs===2&&!removeNum){return this}index=resolveBegin(index,index<0?this.count():this.size);var spliced=this.slice(0,index);return reify(this,numArgs===1?spliced:spliced.concat(arrCopy(arguments,2),this.slice(index+removeNum)))},findLastIndex:function(predicate,context){var entry=this.findLastEntry(predicate,context);return entry?entry[0]:-1},first:function(){return this.get(0)},flatten:function(depth){return reify(this,flattenFactory(this,depth,false))},get:function(index,notSetValue){index=wrapIndex(this,index);return index<0||(this.size===Infinity||this.size!==undefined&&index>this.size)?notSetValue:this.find(function(_,key){return key===index},undefined,notSetValue)},has:function(index){index=wrapIndex(this,index);return index>=0&&(this.size!==undefined?this.size===Infinity||indexb?-1:0}function hashIterable(iterable){if(iterable.size===Infinity){return 0}var ordered=isOrdered(iterable);var keyed=isKeyed(iterable);var h=ordered?1:0;var size=iterable.__iterate(keyed?ordered?function(v,k){h=31*h+hashMerge(hash(v),hash(k))|0}:function(v,k){h=h+hashMerge(hash(v),hash(k))|0}:ordered?function(v){h=31*h+hash(v)|0}:function(v){h=h+hash(v)|0});return murmurHashOfSize(size,h)}function murmurHashOfSize(size,h){h=imul(h,3432918353);h=imul(h<<15|h>>>-15,461845907);h=imul(h<<13|h>>>-13,5);h=(h+3864292196|0)^size;h=imul(h^h>>>16,2246822507);h=imul(h^h>>>13,3266489909);h=smi(h^h>>>16);return h}function hashMerge(a,b){return a^b+2654435769+(a<<6)+(a>>2)|0}var Immutable={Iterable:Iterable,Seq:Seq,Collection:Collection,Map:Map,OrderedMap:OrderedMap,List:List,Stack:Stack,Set:Set,OrderedSet:OrderedSet,Record:Record,Range:Range,Repeat:Repeat,is:is,fromJS:fromJS};return Immutable})},{}],228:[function(require,module,exports){var RandomID=require("./randomid.js");var Dataspace=require("./dataspace.js").Dataspace;var Struct=require("./struct.js");var Patch=require("./patch.js");var ack=Struct.makeConstructor("ack",["id"]);function Ack(metaLevel,id){this.metaLevel=metaLevel||0;this.id=id||RandomID.randomId(16);this.done=false}Ack.prototype.arm=function(){Dataspace.stateChange(Patch.sub(ack(this.id),this.metaLevel));Dataspace.send(ack(this.id),this.metaLevel)};Ack.prototype.disarm=function(){Dataspace.stateChange(Patch.unsub(ack(this.id),this.metaLevel))};Ack.prototype.check=function(e){if(!this.done){if(e.type==="message"){var m=Patch.stripAtMeta(e.message,this.metaLevel);if(ack.isClassOf(m)&&m[0]===this.id){this.disarm();this.done=true}}}return this.done};module.exports.ack=ack;module.exports.Ack=Ack},{"./dataspace.js":233,"./patch.js":239,"./randomid.js":240,"./struct.js":244}],229:[function(require,module,exports){"use strict";var Immutable=require("immutable");var _Dataspace=require("./dataspace.js");var Dataspace=_Dataspace.Dataspace;var __=_Dataspace.__;var Mux=require("./mux.js");var Patch=require("./patch.js");var Trie=require("./trie.js");var Util=require("./util.js");var Dataflow=require("./dataflow.js");function spawnActor(bootFn,optName){Dataspace.spawn(new Actor(bootFn,optName))}function Actor(bootFn,optName){this.fields={};this.facets=Immutable.Set();this.mux=new Mux.Mux;this.previousKnowledge=Trie.emptyTrie;this.knowledge=Trie.emptyTrie;this.pendingActions=[];this.dataflowGraph=new Dataflow.Graph;if(typeof optName!=="undefined"){this.name=optName}this.boot=function(){var self=this;withCurrentFacet(null,function(){bootFn.call(self.fields)});this.quiesce()}}(function(){var priorities=["PRIORITY_QUERY_HIGH","PRIORITY_QUERY","PRIORITY_QUERY_HANDLER","PRIORITY_NORMAL"];for(var i=0;i0){return probe?true:q.shift()}}return false};Actor.prototype.handleEvent=function(e){var actor=this;if(e.type==="stateChange"){this.previousKnowledge=this.knowledge;this.knowledge=e.patch.updateInterests(this.knowledge)}if(this.nextPendingAction(true)){throw new Error("Syndicate: pendingActions must not be nonempty at start of handleEvent")}this.facets.forEach(function(f){withCurrentFacet(f,function(){f.handleEvent(e,false)})});this.quiesce()};Actor.prototype.quiesce=function(){var actor=this;while(true){var entry=this.nextPendingAction(false);if(!entry)break;withCurrentFacet(entry.facet,entry.action);this.dataflowGraph.repairDamage(function(subjectId){var facet=subjectId[0];var endpoint=subjectId[1];if(!facet.terminated){withCurrentFacet(facet,function(){var patch=Patch.retract(__).andThen(endpoint.subscriptionFn.call(facet.fields));var newInterests=patch.prunedBy(facet.actor.mux.interestsOf(endpoint.eid));var newlyRelevantKnowledge=Patch.biasedIntersection(facet.actor.knowledge,newInterests.added);var r=facet.actor.mux.updateStream(endpoint.eid,patch);Dataspace.stateChange(r.deltaAggregate);facet.handleEvent(_Dataspace.stateChange(new Patch.Patch(newlyRelevantKnowledge,Trie.emptyTrie)),true)})}})}this.checkForTermination()};Actor.prototype.pushAction=function(a,priorityOpt){var priority=typeof priorityOpt==="undefined"?Actor.PRIORITY_NORMAL:priorityOpt;while(this.pendingActions.length0){var shouldTerminate=isTerminal;objects.forEach(function(o){var instantiated=Trie.instantiateProjection(spec,o);if(facet.interestWas(eventType,instantiated,isSynthetic)){if(shouldTerminate){shouldTerminate=false;facet.terminate()}facet.actor.pushAction(function(){Util.kwApply(handlerFn,facet.fields,o)},priority)}})}}}));case"risingEdge":var endpoint=new Endpoint(function(){var newValue=subscriptionFn.call(facet.fields);if(newValue&&!this.currentValue){if(isTerminal){facet.terminate()}facet.actor.pushAction(function(){handlerFn.call(facet.fields)},priority)}this.currentValue=newValue;return Patch.emptyPatch},function(e){});endpoint.currentValue=false;return this.addEndpoint(endpoint);default:throw new Error("Unsupported Facet eventType: "+eventType)}};Facet.prototype.interestWas=function(assertedOrRetracted,pat,isSyntheticEvent){function orStar(a,b){return a||b}var previousKnowledge=isSyntheticEvent?Trie.emptyTrie:this.actor.previousKnowledge;var oldExists=Trie.matchValue(previousKnowledge,pat,false,orStar);var newExists=Trie.matchValue(this.actor.knowledge,pat,false,orStar);switch(assertedOrRetracted){case"asserted":return!oldExists&&newExists;case"retracted":return oldExists&&!newExists;default:throw new Error("Unexpected assertedOrRetracted in Facet.interestWas: "+assertedOrRetracted)}} ;Facet.prototype.addEndpoint=function(endpoint){var facet=this;var patch=facet.actor.dataflowGraph.withSubject([facet,endpoint],function(){return endpoint.subscriptionFn.call(facet.fields)});var r=facet.actor.mux.addStream(patch);endpoint.eid=r.pid;facet.endpoints=facet.endpoints.set(endpoint.eid,endpoint);Dataspace.stateChange(r.deltaAggregate);return facet};Facet.prototype.addInitBlock=function(thunk){this.initBlocks=this.initBlocks.push(thunk);return this};Facet.prototype.addDoneBlock=function(thunk){this.doneBlocks=this.doneBlocks.push(thunk);return this};Facet.prototype.completeBuild=function(){var facet=this;this.actor.addFacet(this);if(this.parent){this.parent.children=this.parent.children.add(this)}withCurrentFacet(facet,function(){facet.initBlocks.forEach(function(b){b.call(facet.fields)})});var initialEvent=_Dataspace.stateChange(new Patch.Patch(facet.actor.knowledge,Trie.emptyTrie));withCurrentFacet(facet,function(){facet.handleEvent(initialEvent,true)})};Facet.prototype.terminate=function(){var facet=this;if(facet.terminated)return;facet.terminated=true;var aggregate=Patch.emptyPatch;this.endpoints.forEach(function(endpoint,eid){var r=facet.actor.mux.removeStream(eid);aggregate=aggregate.andThen(r.deltaAggregate)});Dataspace.stateChange(aggregate);this.endpoints=Immutable.Map();if(this.parent){this.parent.children=this.parent.children.remove(this)}this.actor.removeFacet(this);this.children.forEach(function(child){child.terminate()});withCurrentFacet(facet,function(){facet.doneBlocks.forEach(function(b){b.call(facet.fields)})})};function Endpoint(subscriptionFn,handlerFn){this.subscriptionFn=subscriptionFn;this.handlerFn=handlerFn;this.eid="uninitialized_eid"}function referenceField(obj,prop){if(!(prop in obj)){Dataspace.activeBehavior().dataflowGraph.recordObservation(Immutable.List.of(obj,prop))}return obj[prop]}function declareField(obj,prop,init){if(prop in obj){obj[prop]=init}else{Dataspace.activeBehavior().dataflowGraph.defineObservableProperty(obj,prop,init,{objectId:Immutable.List.of(obj,prop)})}}function deleteField(obj,prop){Dataspace.activeBehavior().dataflowGraph.recordDamage(Immutable.List.of(obj,prop));return delete obj[prop]}module.exports.spawnActor=spawnActor;module.exports.Facet=Facet;module.exports.referenceField=referenceField;module.exports.declareField=declareField;module.exports.deleteField=deleteField},{"./dataflow.js":232,"./dataspace.js":233,"./mux.js":238,"./patch.js":239,"./trie.js":246,"./util.js":248,immutable:227}],230:[function(require,module,exports){"use strict";var Immutable=require("immutable");var Trie=require("./trie.js");var Patch=require("./patch.js");var Struct=require("./struct.js");var DemandMatcher=require("./demand-matcher.js").DemandMatcher;var Codec=require("./codec");var Dataspace_=require("./dataspace.js");var Dataspace=Dataspace_.Dataspace;var __=Dataspace_.__;var _$=Dataspace_._$;var DEFAULT_RECONNECT_DELAY=100;var MAX_RECONNECT_DELAY=3e4;var DEFAULT_IDLE_TIMEOUT=3e5;var DEFAULT_PING_INTERVAL=DEFAULT_IDLE_TIMEOUT-1e4;var toBroker=Struct.makeConstructor("toBroker",["url","assertion"]);var fromBroker=Struct.makeConstructor("fromBroker",["url","assertion"]);var brokerConnection=Struct.makeConstructor("brokerConnection",["url"]);var brokerConnected=Struct.makeConstructor("brokerConnected",["url"]);var forceBrokerDisconnect=Struct.makeConstructor("forceBrokerDisconnect",["url"]);function spawnBrokerClientDriver(){var URL=_$("url");Dataspace.spawn(new Dataspace(function(){Dataspace.spawn(new DemandMatcher([brokerConnection(URL)],[brokerConnection(URL)],function(c){Dataspace.spawn(new BrokerClientConnection(c.url))},{demandMetaLevel:1,supplyMetaLevel:0}))}))}function BrokerClientConnection(wsurl){this.wsurl=wsurl;this.sock=null;this.sendsAttempted=0;this.sendsTransmitted=0;this.receiveCount=0;this.connectionCount=0;this.reconnectDelay=DEFAULT_RECONNECT_DELAY;this.idleTimeout=DEFAULT_IDLE_TIMEOUT;this.pingInterval=DEFAULT_PING_INTERVAL;this.localAssertions=Trie.emptyTrie;this.connectionInterrupted=false;this.activityTimestamp=0;this.idleTimer=null;this.pingTimer=null}BrokerClientConnection.prototype.clearHeartbeatTimers=function(){if(this.idleTimer){clearTimeout(this.idleTimer);this.idleTimer=null}if(this.pingTimer){clearTimeout(this.pingTimer);this.pingTimer=null}};BrokerClientConnection.prototype.recordActivity=function(){var self=this;this.activityTimestamp=+new Date;this.clearHeartbeatTimers();this.idleTimer=setTimeout(function(){self.forceclose()},this.idleTimeout);this.pingTimer=setTimeout(function(){self.safeSend(JSON.stringify("ping"))},this.pingInterval)};BrokerClientConnection.prototype.boot=function(){this.reconnect();var initialAssertions=Patch.sub(toBroker(this.wsurl,__),1).andThen(Patch.sub(Patch.observe(fromBroker(this.wsurl,__)),1)).andThen(Patch.assert(brokerConnection(this.wsurl))).andThen(Patch.sub(brokerConnection(this.wsurl),1)).andThen(Patch.sub(forceBrokerDisconnect(this.wsurl),1));return initialAssertions};BrokerClientConnection.prototype.trapexit=function(){this.forceclose()};BrokerClientConnection.prototype.isConnected=function(){return this.sock&&this.sock.readyState===this.sock.OPEN};BrokerClientConnection.prototype.safeSend=function(m){try{this.sendsAttempted++;if(this.isConnected()){this.sock.send(m);this.sendsTransmitted++}}catch(e){console.warn("Trapped exn while sending",e)}};BrokerClientConnection.prototype.sendPatch=function(p){var j=JSON.stringify(Codec.encodeEvent(Syndicate.stateChange(p)));this.safeSend(j)};BrokerClientConnection.prototype.handleEvent=function(e){switch(e.type){case"stateChange":if(e.patch.project(Patch.atMeta(brokerConnection(_$))).hasRemoved()){Dataspace.exit()}var pTo=e.patch.project(Patch.atMeta(toBroker(__,_$)));var pObsFrom=e.patch.project(Patch.atMeta(Patch.observe(fromBroker(__,_$))));pObsFrom=new Patch.Patch(Trie.compilePattern(true,Patch.observe(Trie.embeddedTrie(pObsFrom.added))),Trie.compilePattern(true,Patch.observe(Trie.embeddedTrie(pObsFrom.removed))));var newLocalAssertions=this.localAssertions;newLocalAssertions=pTo.label(Immutable.Set.of("to")).applyTo(newLocalAssertions);newLocalAssertions=pObsFrom.label(Immutable.Set.of("obsFrom")).applyTo(newLocalAssertions);var trueSet=Immutable.Set.of(true);var alwaysTrueSet=function(v){return trueSet};var p=Patch.computePatch(Trie.relabel(this.localAssertions,alwaysTrueSet),Trie.relabel(newLocalAssertions,alwaysTrueSet));this.localAssertions=newLocalAssertions;this.sendPatch(p);break;case"message":var m=e.message;if(Patch.atMeta.isClassOf(m)){m=m[0];if(toBroker.isClassOf(m)){var j=JSON.stringify(Codec.encodeEvent(Syndicate.message(m[1])));this.safeSend(j)}else if(forceBrokerDisconnect.isClassOf(m)){this.forceclose()}}break}};BrokerClientConnection.prototype.forceclose=function(keepReconnectDelay){if(!keepReconnectDelay){this.reconnectDelay=DEFAULT_RECONNECT_DELAY}this.clearHeartbeatTimers();if(this.sock){console.log("BrokerClientConnection.forceclose called");this.sock.close();this.sock=null}};BrokerClientConnection.prototype.reconnect=function(){var self=this;this.forceclose(true);this.connectionCount++;this.sock=new WebSocket(this.wsurl);this.sock.onopen=Dataspace.wrap(function(e){return self.onopen(e)});this.sock.onmessage=Dataspace.wrap(function(e){self.receiveCount++;return self.onmessage(e)});this.sock.onclose=Dataspace.wrap(function(e){return self.onclose(e)})};BrokerClientConnection.prototype.onopen=function(e){console.log("connected to "+this.sock.url);this.recordActivity();Dataspace.stateChange(Patch.assert(brokerConnected(this.wsurl),1));this.reconnectDelay=DEFAULT_RECONNECT_DELAY;this.sendPatch(new Patch.Patch(this.localAssertions,Trie.emptyTrie).strip())};BrokerClientConnection.prototype.onmessage=function(wse){this.recordActivity();var j=JSON.parse(wse.data,Struct.reviver);if(j==="ping"){this.safeSend(JSON.stringify("pong"));return}else if(j==="pong"){return}var e=Codec.decodeAction(j);switch(e.type){case"stateChange":{var added=fromBroker(this.wsurl,Trie.embeddedTrie(e.patch.added));var removed=fromBroker(this.wsurl,Trie.embeddedTrie(e.patch.removed));var p=Patch.assert(added,1).andThen(Patch.retract(removed,1));if(!p.isEmpty()){if(this.connectionInterrupted){p=Patch.retract(fromBroker(this.wsurl,__),1).andThen(p);this.connectionInterrupted=false}Dataspace.stateChange(p)}break}case"message":{Dataspace.send(fromBroker(this.wsurl,e.message),1);break}}};BrokerClientConnection.prototype.onclose=function(e){var self=this;Dataspace.stateChange(Patch.retract(brokerConnected(this.wsurl),1));this.connectionInterrupted=true;console.log("reconnecting to "+this.wsurl+" in "+this.reconnectDelay+"ms");setTimeout(Dataspace.wrap(function(){self.reconnect()}),this.reconnectDelay);this.reconnectDelay=this.reconnectDelay*1.618+Math.random()*1e3;this.reconnectDelay=this.reconnectDelay>MAX_RECONNECT_DELAY?MAX_RECONNECT_DELAY+Math.random()*1e3:this.reconnectDelay};module.exports.toBroker=toBroker;module.exports.fromBroker=fromBroker;module.exports.brokerConnection=brokerConnection;module.exports.brokerConnected=brokerConnected;module.exports.forceBrokerDisconnect=forceBrokerDisconnect;module.exports.spawnBrokerClientDriver=spawnBrokerClientDriver;module.exports.BrokerClientConnection=BrokerClientConnection},{"./codec":231,"./dataspace.js":233,"./demand-matcher.js":234,"./patch.js":239,"./struct.js":244,"./trie.js":246,immutable:227}],231:[function(require,module,exports){"use strict";var Trie=require("./trie.js");var Patch=require("./patch.js");var Struct=require("./struct.js");function _encode(e){switch(e.type){case"stateChange":return["patch",e.patch.toJSON()];case"message":return["message",e.message]}}function _decode(what){return function(j){switch(j[0]){case"patch":return Syndicate.stateChange(Patch.fromJSON(j[1]));case"message":return Syndicate.message(j[1]);default:throw new Error("Invalid JSON-encoded "+what+": "+JSON.stringify(j))}}}module.exports.encodeEvent=_encode;module.exports.decodeEvent=_decode("event");module.exports.encodeAction=_encode;module.exports.decodeAction=_decode("action")},{"./patch.js":239,"./struct.js":244,"./trie.js":246}],232:[function(require,module,exports){"use strict";var Immutable=require("immutable");var MapSet=require("./mapset.js");function Graph(){this.edgesForward=Immutable.Map();this.edgesReverse=Immutable.Map();this.damagedNodes=Immutable.Set();this.currentSubjectId=null}Graph.prototype.withSubject=function(subjectId,f){var oldSubjectId=this.currentSubjectId;this.currentSubjectId=subjectId;var result;try{result=f()}catch(e){this.currentSubjectId=oldSubjectId;throw e}this.currentSubjectId=oldSubjectId;return result};Graph.prototype.recordObservation=function(objectId){if(this.currentSubjectId){this.edgesForward=MapSet.add(this.edgesForward,objectId,this.currentSubjectId);this.edgesReverse=MapSet.add(this.edgesReverse,this.currentSubjectId,objectId)}};Graph.prototype.recordDamage=function(objectId){this.damagedNodes=this.damagedNodes.add(objectId)};Graph.prototype.forgetSubject=function(subjectId){var self=this;var subjectObjects=self.edgesReverse.get(subjectId)||Immutable.Set();self.edgesReverse=self.edgesReverse.remove(subjectId);subjectObjects.forEach(function(objectId){self.edgesForward=MapSet.remove(self.edgesForward,objectId,subjectId)})};Graph.prototype.repairDamage=function(repairNode){var self=this;var repairedThisRound=Immutable.Set();while(true){var workSet=self.damagedNodes;self.damagedNodes=Immutable.Set();var alreadyDamaged=workSet.intersect(repairedThisRound);if(!alreadyDamaged.isEmpty()){console.warn("Cyclic dependencies involving",alreadyDamaged)}workSet=workSet.subtract(repairedThisRound);repairedThisRound=repairedThisRound.union(workSet);if(workSet.isEmpty())break;workSet.forEach(function(objectId){var subjects=self.edgesForward.get(objectId)||Immutable.Set();subjects.forEach(function(subjectId){self.forgetSubject(subjectId);self.withSubject(subjectId,function(){repairNode(subjectId)})})})}};Graph.prototype.defineObservableProperty=function(obj,prop,value,maybeOptions){var graph=this;var options=typeof maybeOptions==="undefined"?{}:maybeOptions;var objectId=options.objectId||"__"+prop;Object.defineProperty(obj,prop,{configurable:true,enumerable:true,get:function(){graph.recordObservation(objectId);return value},set:function(newValue){if(!options.noopGuard||!options.noopGuard(value,newValue)){graph.recordDamage(objectId);value=newValue}}});graph.recordDamage(objectId);return objectId};Graph.newScope=function(o){function O(){}O.prototype=o;return new O};module.exports.Graph=Graph},{"./mapset.js":237,immutable:227}],233:[function(require,module,exports){"use strict";var Immutable=require("immutable");var Patch=require("./patch.js");var Mux=require("./mux.js");function stateChange(patch){return{type:"stateChange",patch:patch}}function message(body){return{type:"message",message:body}}function spawn(behavior){return{type:"spawn",behavior:behavior}}function terminate(){return{type:"terminate"}}function terminateDataspace(){return{type:"terminateDataspace"}}function Dataspace(bootFn){this.pendingPatch=null;this.pendingActions=Immutable.List();this.processTable=Immutable.Map();this.runnablePids=Immutable.Set();this.mux=new Mux.Mux;this.onStateChange=function(mux,deltaAggregate){};this.asChild("meta",function(){return bootFn()},true)}Dataspace.noisy=false;Dataspace.stack=Immutable.List();Dataspace.current=function(){return Dataspace.stack.last().dataspace};Dataspace.activePid=function(){return Dataspace.stack.last().activePid};Dataspace.activeBehavior=function(){var entry=Dataspace.stack.last();var p=entry.dataspace.processTable.get(entry.activePid);return p?p.behavior:null};Dataspace.withDataspaceStack=function(stack,f){var oldStack=Dataspace.stack;Dataspace.stack=stack;var result;try{result=f()}catch(e){Dataspace.stack=oldStack;throw e}Dataspace.stack=oldStack;return result};Dataspace.wrap=function(f){var savedStack=Dataspace.stack;return function(){var actuals=arguments;return Dataspace.withDataspaceStack(savedStack,function(){var result=Dataspace.current().asChild(Dataspace.activePid(),function(){return f.apply(null,actuals)});Dataspace.stack.reverse().forEach(function(entry){entry.dataspace.markRunnable(entry.activePid)});return result})}};Dataspace.enqueueAction=function(action){var entry=Dataspace.stack.last();entry.dataspace.enqueueAction(entry.activePid,action)};Dataspace.send=function(body,metaLevel){Dataspace.enqueueAction(message(Patch.prependAtMeta(body,metaLevel||0)))};Dataspace.stateChange=function(patch){Dataspace.enqueueAction(stateChange(patch))};Dataspace.spawn=function(behavior){Dataspace.enqueueAction(spawn(behavior))};Dataspace.exit=function(exn){Dataspace.current().kill(Dataspace.activePid(),exn)};Dataspace.exitDataspace=function(){Dataspace.enqueueAction(terminateDataspace())};Dataspace.inertBehavior=function(oldBehavior){var b={handleEvent:function(e){}};if("name"in oldBehavior){b.name=oldBehavior.name}return b};Dataspace.prototype.debugName=function(pid){var p=this.processTable.get(pid,null);if(p===null){return"(dead)["+pid+"]"}if("name"in p.behavior){return JSON.stringify(p.behavior.name)+"["+pid+"]"}return"(anon)["+pid+"]"};Dataspace.prototype.asChild=function(pid,f,omitLivenessCheck){var self=this;var p=self.processTable.get(pid,null);if(!omitLivenessCheck&&p===null){console.warn("Dataspace.asChild eliding invocation of dead process",self.debugName(pid));return}var result=Dataspace.withDataspaceStack(Dataspace.stack.push({dataspace:self,activePid:pid}),function(){try{return f(p)}catch(e){self.kill(pid,e)}});self.flushPendingPatch();return result};Dataspace.prototype.kill=function(pid,exn){if(exn){if(exn.stack){console.error("Process crashed",this.debugName(pid),exn,exn.stack)}else{console.error("Process crashed",this.debugName(pid),exn)}}else if(Dataspace.noisy){console.log("Process exiting",this.debugName(pid))}var p=this.processTable.get(pid);this.processTable=this.processTable.set(pid,{behavior:Dataspace.inertBehavior(p.behavior)});if(p){if(p.behavior.trapexit){this.asChild(pid,function(){return p.behavior.trapexit(exn)},true)}this.enqueueAction(pid,terminate())}};Dataspace.prototype.boot=function(){};Dataspace.prototype.handleEvent=function(e){switch(e.type){case"stateChange":this.enqueueAction("meta",stateChange(e.patch.lift()));break;case"message":this.enqueueAction("meta",message(Patch.atMeta(e.message)));break;default:var exn=new Error("Event type "+e.type+" not understood");exn.event=e;throw exn}this.flushPendingPatch();return true};Dataspace.prototype.step=function(){return this.dispatchActions()&&this.runRunnablePids()&&(this.pendingActions.size>0||this.runnablePids.size>0)};Dataspace.prototype.flushPendingPatch=function(){if(this.pendingPatch){this.pendingActions=this.pendingActions.push([this.pendingPatch[0],stateChange(this.pendingPatch[1])]);this.pendingPatch=null}};Dataspace.prototype.enqueueAction=function(pid,action){if(action.type==="stateChange"&&this.pendingPatch&&this.pendingPatch[0]===pid){this.pendingPatch[1]=this.pendingPatch[1].andThen(action.patch);return}this.flushPendingPatch();if(action.type==="stateChange"){this.pendingPatch=[pid,action.patch]}else{this.pendingActions=this.pendingActions.push([pid,action])}};Dataspace.prototype.dispatchActions=function(){var self=this;var actionQueue=this.pendingActions;this.pendingActions=Immutable.List();var alive=true;actionQueue.forEach(function(entry){var pid=entry[0];var action=entry[1];if(!self.interpretAction(pid,action)){alive=false;return false}});return alive};Dataspace.prototype.markRunnable=function(pid){this.runnablePids=this.runnablePids.add(pid)};Dataspace.prototype.runRunnablePids=function(){var self=this;var pidSet=this.runnablePids;this.runnablePids=Immutable.Set();pidSet.forEach(function(pid){var childBusy=self.asChild(pid,function(p){return p.behavior.step&&p.behavior.step()});if(childBusy)self.markRunnable(pid)});return true};Dataspace.prototype.interpretAction=function(pid,action){var self=this;switch(action.type){case"stateChange":var oldMux=this.mux.shallowCopy();this.deliverPatches(oldMux,this.mux.updateStream(pid,action.patch));return true;case"message":if(Patch.observe.isClassOf(action.message)){console.warn("Process "+this.debugName(pid)+" sent message containing query",action.message)}if(pid!=="meta"&&Patch.atMeta.isClassOf(action.message)){Dataspace.send(action.message[0])}else{this.mux.routeMessage(action.message).forEach(function(pid){self.deliverEvent(pid,action)})}return true;case"spawn":var oldMux=this.mux.shallowCopy();var p={behavior:action.behavior};var pid=this.mux.nextPid;this.processTable=this.processTable.set(pid,p);var initialPatch=Patch.emptyPatch;if(p.behavior.boot){initialPatch=this.asChild(pid,function(){return p.behavior.boot()});initialPatch=initialPatch||Patch.emptyPatch;this.markRunnable(pid)}this.deliverPatches(oldMux,this.mux.addStream(initialPatch));return true;case"terminate":var oldMux=this.mux.shallowCopy();this.deliverPatches(oldMux,this.mux.removeStream(pid));if(Dataspace.noisy)console.log("Process exit complete",this.debugName(pid));this.processTable=this.processTable.remove(pid);return true;case"terminateDataspace":Dataspace.exit();return false;default:var exn=new Error("Action type "+action.type+" not understood");exn.action=action;throw exn}};Dataspace.prototype.deliverPatches=function(oldMux,updateStreamResult){var self=this;var events=Mux.computeEvents(oldMux,this.mux,updateStreamResult);events.eventMap.forEach(function(patch,pid){self.deliverEvent(pid,stateChange(patch))});events.metaEvents.forEach(Dataspace.stateChange);if(!updateStreamResult.deltaAggregate.isEmpty()){this.onStateChange(this.mux,updateStreamResult.deltaAggregate)}};Dataspace.prototype.deliverEvent=function(pid,event){var childBusy=this.asChild(pid,function(p){return p.behavior.handleEvent(event)});if(childBusy)this.markRunnable(pid)};Dataspace.prototype.setOnStateChange=function(handler){this.onStateChange=handler;this.onStateChange(this.mux,Patch.emptyPatch)};module.exports.stateChange=stateChange;module.exports.message=message;module.exports.spawn=spawn;module.exports.terminate=terminate;module.exports.terminateDataspace=terminateDataspace;module.exports.Dataspace=Dataspace},{"./mux.js":238,"./patch.js":239,immutable:227}],234:[function(require,module,exports){var Immutable=require("immutable");var Trie=require("./trie.js");var Patch=require("./patch.js");var Util=require("./util.js");var IS_CHANGING=1;var IS_PRESENT=2;var LOW=0;var RISING=IS_CHANGING;var HIGH=IS_PRESENT;var FALLING=IS_PRESENT|IS_CHANGING;function defaultTaskSupervisor(demandState,supplyState,supervisionState,taskFn,onTaskExit){var oldESI=supervisionState?supervisionState.expectSupplyIncrease:false;var oldESD=supervisionState?supervisionState.expectSupplyDecrease:false;var newESI=oldESI;var newESD=oldESD;if(demandState===FALLING&&(supplyState===RISING||supplyState===HIGH||oldESI)){newESD=true}if(!oldESI&&(demandState===RISING||demandState===HIGH)&&(supplyState===LOW||supplyState===FALLING)){if(demandState===HIGH&&!oldESD){onTaskExit()}else{taskFn();newESI=true}}if(supplyState===FALLING)newESD=false;if(supplyState===RISING)newESI=false;if(newESI||newESD){return{expectSupplyIncrease:newESI,expectSupplyDecrease:newESD}}else{return null}}function defaultOnTaskExit(captures){console.error("Syndicate: DemandMatcher detected unexpected drop in supply",captures)}function DemandMatcher(demandSpecs,supplySpecs,startTask,options){options=Util.extend({metaLevel:0,demandMetaLevel:null,supplyMetaLevel:null,taskSupervisor:defaultTaskSupervisor,onTaskExit:defaultOnTaskExit},options);if(typeof startTask!=="function"){throw new Error("Syndicate: DemandMatcher expects 'startTask' function as third argument")}this.demandProjectionNames=ensureMatchingProjectionNames(demandSpecs);this.supplyProjectionNames=ensureMatchingProjectionNames(supplySpecs);ensureMatchingProjectionNames([demandSpecs[0],supplySpecs[0]]);this.demandSpecs=demandSpecs;this.supplySpecs=supplySpecs;this.demandPatterns=demandSpecs.map(function(s){return Trie.projectionToPattern(s)});this.supplyPatterns=supplySpecs.map(function(s){return Trie.projectionToPattern(s)});this.demandMetaLevel=options.demandMetaLevel===null?options.metaLevel:options.demandMetaLevel;this.supplyMetaLevel=options.supplyMetaLevel===null?options.metaLevel:options.supplyMetaLevel;function metaWrap(n){return function(s){return Patch.prependAtMeta(s,n)}}this.demandProjections=demandSpecs.map(metaWrap(this.demandMetaLevel));this.supplyProjections=supplySpecs.map(metaWrap(this.supplyMetaLevel));this.taskSupervisor=options.taskSupervisor;this.startTask=startTask;this.onTaskExit=options.onTaskExit;this.currentDemand=Immutable.Set();this.currentSupply=Immutable.Set();this.supervisionStates=Immutable.Map();if("name"in options){this.name=options.name}}function ensureMatchingProjectionNames(specs){if(!(specs.length>0)){throw new Error("Syndicate: DemandMatcher needs at least one spec")}var names=null;specs.forEach(function(spec){if(names===null){names=Trie.projectionNames(spec)}else{if(JSON.stringify(names)!==JSON.stringify(Trie.projectionNames(spec))){throw new Error("Syndicate: DemandMatcher needs identical capture names")}}});return names}DemandMatcher.prototype.boot=function(){var p=Patch.emptyPatch;function extend(ml){return function(pat){p=p.andThen(Patch.sub(pat,ml))}}this.demandPatterns.forEach(extend(this.demandMetaLevel));this.supplyPatterns.forEach(extend(this.supplyMetaLevel));return p};DemandMatcher.prototype.handleEvent=function(e){if(e.type==="stateChange"){this.handlePatch(e.patch)}};DemandMatcher.prototype.handlePatch=function(p){var self=this;var dN=self.demandProjectionNames.length;var sN=self.supplyProjectionNames.length;var addedDemand=self.extractKeys(p.added,self.demandProjections,dN,"demand");var removedDemand=self.extractKeys(p.removed,self.demandProjections,dN,"demand");var addedSupply=self.extractKeys(p.added,self.supplyProjections,sN,"supply");var removedSupply=self.extractKeys(p.removed,self.supplyProjections,sN,"supply");var demandOverlap=addedDemand.intersect(removedDemand);var supplyOverlap=addedSupply.intersect(removedSupply);addedDemand=addedDemand.subtract(demandOverlap);removedDemand=removedDemand.subtract(demandOverlap);addedSupply=addedSupply.subtract(supplyOverlap);removedSupply=removedSupply.subtract(supplyOverlap);var allTasks=addedDemand.union(addedSupply).union(removedDemand).union(removedSupply);allTasks.forEach(function(captures){function taskFn(){self.startTask(Trie.captureToObject(captures,self.demandProjectionNames))}function onTaskExit(){self.onTaskExit(Trie.captureToObject(captures,self.demandProjectionNames))}var demandState=computeState(self.currentDemand,addedDemand,removedDemand,captures);var supplyState=computeState(self.currentSupply,addedSupply,removedSupply,captures);var oldSupervisionState=self.supervisionStates.get(captures,null);var newSupervisionState=self.taskSupervisor(demandState,supplyState,oldSupervisionState,taskFn,onTaskExit);if(newSupervisionState===null){self.supervisionStates=self.supervisionStates.remove(captures)}else{self.supervisionStates=self.supervisionStates.set(captures,newSupervisionState)}});self.currentSupply=self.currentSupply.union(addedSupply).subtract(removedSupply);self.currentDemand=self.currentDemand.union(addedDemand).subtract(removedDemand)};DemandMatcher.prototype.extractKeys=function(trie,projections,keyCount,whichSide){var ks=Immutable.Set();projections.forEach(function(proj){var moreKs=Trie.trieKeys(Trie.project(trie,proj),keyCount);if(!moreKs){throw new Error("Syndicate: wildcard "+whichSide+" detected:\n"+JSON.stringify(proj)+"\n"+Trie.prettyTrie(trie))}ks=ks.union(moreKs)});return ks};function computeState(current,added,removed,captures){var isPresent=current.has(captures);var isChanging=added.has(captures)||removed.has(captures);return(isPresent?IS_PRESENT:0)|(isChanging?IS_CHANGING:0)}module.exports.DemandMatcher=DemandMatcher},{"./patch.js":239,"./trie.js":246,"./util.js":248,immutable:227}],235:[function(require,module,exports){"use strict";var Immutable=require("immutable");var Dataspace=require("./dataspace.js").Dataspace;function Ground(bootFn){var self=this;this.stepperId=null;this.stepping=false;this.startingFuel=100;this.baseStack=Immutable.List.of({dataspace:this,activePid:-1});Dataspace.withDataspaceStack(this.baseStack,function(){self.dataspace=new Dataspace(bootFn)})}Ground.prototype.step=function(){var self=this;return Dataspace.withDataspaceStack(this.baseStack,function(){return self.dataspace.step()})};Ground.prototype.checkPid=function(pid){if(pid!==-1)console.error("Weird pid in Ground",pid)};Ground.prototype.markRunnable=function(pid){this.checkPid(pid);this.startStepping()};Ground.prototype.startStepping=function(){var self=this;if(this.stepperId)return;if(this.stepping)return;this.stepping=true;try{var stillBusy=false;for(var fuel=this.startingFuel;fuel>0;fuel--){stillBusy=this.step();if(!stillBusy)break}if(stillBusy){this.stepperId=setTimeout(function(){self.stepperId=null;self.startStepping()},0)}}catch(e){this.stepping=false;throw e}this.stepping=false;return this};Ground.prototype.stopStepping=function(){if(this.stepperId){clearTimeout(this.stepperId);this.stepperId=null}};Ground.prototype.kill=function(pid,exn){this.checkPid(pid);console.log("Ground dataspace terminated");this.stopStepping()};Ground.prototype.enqueueAction=function(pid,action){this.checkPid(pid);switch(action.type){case"stateChange":if(action.patch.isNonEmpty()){console.error("You have subscribed to a nonexistent event source.",action.patch.pretty())}break;case"message":console.error("You have sent a message into the outer void.",action);break;default:console.error("Internal error: unexpected action at ground level",action);break}};module.exports.Ground=Ground},{"./dataspace.js":233,immutable:227}],236:[function(require,module,exports){"use strict";function copyKeys(keys,to,from){for(var i=0;i>4&15]);encoded.push("0123456789abcdef"[buf[i]&15])}return encoded.join("")}else{return btoa(String.fromCharCode.apply(null,buf)).replace(/=/g,"")}};return true}if(typeof window!=="undefined"&&typeof window.crypto!=="undefined"&&browserCryptoObject(window.crypto)){}else if(typeof self!=="undefined"&&typeof self.crypto!=="undefined"&&browserCryptoObject(self.crypto)){}else{var crypto;try{crypto=require("crypto")}catch(e){}if(typeof crypto!=="undefined"&&typeof crypto.randomBytes!=="undefined"){randomId=function(byteCount,hexOutput){if(hexOutput){return crypto.randomBytes(byteCount).hexSlice().replace(/=/g,"")}else{return crypto.randomBytes(byteCount).base64Slice().replace(/=/g,"")}}}else{console.warn("No suitable implementation for RandomID.randomId available.")}}module.exports.randomId=randomId},{crypto:6}],241:[function(require,module,exports){"use strict";var FN_ARGS=/^function\s*[^\(]*\(\s*([^\)]*)\)/m;var FN_ARG_SPLIT=/,/;var STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;function formalParameters(fn){var result=[];var fnText=fn.toString().replace(STRIP_COMMENTS,"");var argDecl=fnText.match(FN_ARGS);var args=argDecl[1].split(FN_ARG_SPLIT);for(var i=0;i0){r=rwild(r)}return r}function equal_upto_wilds(n,r1,r2){while(true){if(n===0||is_emptyTrie(r1)){return Immutable.is(r1,r2)}if(!(r1 instanceof $Branch)||r1.count>0){return false}n=n-1;r1=r1.wild}}function rupdate_inplace(r,arity,key,k){if(equal_upto_wilds(arity,k,r.wild)){var m=r.edges.get(arity);if(!m)return;if(m.has(key))r.count--;m=m.remove(key);r.edges=m.isEmpty()?r.edges.remove(arity):r.edges.set(arity,m)}else{var m=r.edges.get(arity)||Immutable.Map();if(!m.has(key))r.count++;r.edges=r.edges.set(arity,m.set(key,k))}}function rlookup(r,arity,key){var m=r.edges.get(arity);m=m&&m.get(key);return m||prepend_wilds(arity,r.wild)}function collapse(r){if(r instanceof $Branch&&is_emptyTrie(r.wild)&&r.count===0){return emptyTrie}else{return r}}function newEmptyBranch(){return new $Branch(emptyTrie,Immutable.Map(),0)}var canonicalExpandedEmpty=newEmptyBranch();function expand(r){if(is_emptyTrie(r)){return canonicalExpandedEmpty}else{return r}}function compilePattern(v,p){if(!p)die("compilePattern: missing pattern");return walk(p,rsuccess(v));function walk(p,acc){if(p===__)return rwild(acc);if(Array.isArray(p)){for(var i=p.length-1;i>=0;i--){acc=walk(p[i],acc)}return rseq(p.length,SOA,acc)}if(Immutable.List.isList(p)){p.reverse().forEach(function(element){acc=walk(element,acc)});return rseq(p.size,SOA,acc)}if(Struct.isStructure(p)){for(var i=p.meta.arity-1;i>=0;i--){acc=walk(p[i],acc)}return rseq(p.meta.arity,p.meta,acc)}if(p instanceof $Embedded){acc=appendTrie(p.trie,function(v){return acc});if(p.arrayLength!==null){acc=rseq(p.arrayLength,SOA,acc)}return acc}else{return rseq(0,p,acc)}}}function matchPattern(v,p){var captureCount=0;var result={};try{walk(v,p)}catch(e){if(e.matchPatternFailed)return null;throw e}result.length=captureCount;return result;function walk(v,p){if(p===v)return;if(p===__)return;if(Struct.isStructure(p)&&Struct.isStructure(v)&&p.meta.equals(v.meta)){for(var i=0;ir2.count){acc=rcopybranch(expand(leftBase(r1)));acc.wild=w;r2.edges.forEach(function(keymap,arity){keymap.forEach(function(r2v,key){var r1v=rlookup(r1,arity,key);rupdate_inplace(acc,arity,key,walk(r1v,r2v))})})}else{acc=rcopybranch(expand(rightBase(r2)));acc.wild=w;r1.edges.forEach(function(keymap,arity){keymap.forEach(function(r1v,key){var r2v=rlookup(r2,arity,key);rupdate_inplace(acc,arity,key,walk(r1v,r2v))})})}return collapse(acc)}}function asymmetricTrieError(r1,r2){die("Asymmetric tries: "+r1+", "+r2)}var unionSuccessesDefault=function(v1,v2){return rsuccess(v1.union(v2))};function union(o1,o2,unionSuccessesOpt){var unionSuccesses=unionSuccessesOpt||unionSuccessesDefault;return combine(unionCombiner,function(x){return x},function(x){return x},function(x){return x},function(x){return x},o1,o2);function unionCombiner(r1,r2){if(r1 instanceof $Success&&r2 instanceof $Success)return unionSuccesses(r1.value,r2.value);if(is_emptyTrie(r1))return r2;if(is_emptyTrie(r2))return r1;asymmetricTrieError(r1,r2)}}function unionN(){var acc=emptyTrie;for(var i=0;i";else if(Struct.isStructureType(key))key=key.label+"<"+arity+">";else if(key instanceof $Special)key=key.name;else key=JSON.stringify(key);if(typeof key==="undefined")key="undefined";acc.push(key);walk(i+key.length+1,k)})})}function indentStr(i){return new Array(i+1).join(" ")}}function parenTypeToString(key){if(Struct.isStructureType(key)){return":"+key.label}else{return"L"}}function stringToParenType(arity,key){if(key[0]===":"){ return new Struct.StructureType(key.slice(1),arity)}else if(key==="L"){return SOA}throw new Error("Unsupported JSON trie paren type: "+key)}function trieToJSON(t){if(is_emptyTrie(t)){return[]}if(t instanceof $Success){return[true]}var jParens=[];var jAtoms=[];t.edges.forEach(function(keymap,arity){keymap.forEach(function(k,key){var jk=trieToJSON(k);if(Struct.isStructureType(key)||key===SOA){jParens.push([arity,parenTypeToString(key),jk])}else{jAtoms.push([key,jk])}})});return[jParens,trieToJSON(t.wild),jAtoms]}function badJSON(j){die("Cannot deserialize JSON trie: "+JSON.stringify(j))}function trieFromJSON(j){return decode(j);function decode(j){if(!Array.isArray(j))badJSON(j);switch(j.length){case 0:return emptyTrie;case 1:return rsuccess(true);case 3:{var result=rcopybranch(expand(rwild(decode(j[1]))));j[0].forEach(function(entry){var arity=entry[0];if(typeof arity!=="number")badJSON(j);var key=stringToParenType(arity,entry[1]);rupdate_inplace(result,arity,key,decode(entry[2]))});j[2].forEach(function(entry){var key=entry[0];rupdate_inplace(result,0,key,decode(entry[1]))});return collapse(result)}default:badJSON(j)}}}module.exports.__=__;module.exports.SOA=SOA;module.exports.$Capture=$Capture;module.exports.$Special=$Special;module.exports._$=_$;module.exports.is_emptyTrie=is_emptyTrie;module.exports.emptyTrie=emptyTrie;module.exports.embeddedTrie=embeddedTrie;module.exports.embeddedTrieArray=embeddedTrieArray;module.exports.compilePattern=compilePattern;module.exports.matchPattern=matchPattern;module.exports._union=union;module.exports.union=unionN;module.exports.intersect=intersect;module.exports.subtract=subtract;module.exports.matchValue=matchValue;module.exports.matchTrie=matchTrie;module.exports.appendTrie=appendTrie;module.exports.trieStep=trieStep;module.exports.trieSuccess=rsuccess;module.exports.relabel=relabel;module.exports.projectionNames=projectionNames;module.exports.projectionArity=projectionArity;module.exports.projectionToPattern=projectionToPattern;module.exports.project=project;module.exports.projectMany=projectMany;module.exports.trieKeys=trieKeys;module.exports.captureToObject=captureToObject;module.exports.trieKeysToObjects=trieKeysToObjects;module.exports.projectObjects=projectObjects;module.exports.instantiateProjection=instantiateProjection;module.exports.prettyTrie=prettyTrie;module.exports.trieToJSON=trieToJSON;module.exports.trieFromJSON=trieFromJSON;module.exports._testing={rsuccess:rsuccess,rseq:rseq,rwild:rwild}},{"./special.js":243,"./struct.js":244,immutable:227}],247:[function(require,module,exports){"use strict";var Immutable=require("immutable");var Patch=require("./patch.js");var Trie=require("./trie.js");var DemandMatcher=require("./demand-matcher.js").DemandMatcher;var Struct=require("./struct.js");var RandomID=require("./randomid.js");var Dataspace_=require("./dataspace.js");var Dataspace=Dataspace_.Dataspace;var __=Dataspace_.__;var _$=Dataspace_._$;var globalEvent=Struct.makeConstructor("global-event",["selector","eventType","event"]);var windowEvent=Struct.makeConstructor("window-event",["eventType","event"]);var uiEvent=Struct.makeConstructor("ui-event",["fragmentId","selector","eventType","event"]);var uiFragment=Struct.makeConstructor("ui-fragment",["fragmentId","selector","html","orderBy"]);var uiFragmentVersion=Struct.makeConstructor("ui-fragment-version",["fragmentId","version"]);var uiAttribute=Struct.makeConstructor("ui-attribute",["selector","attribute","value"]);var uiProperty=Struct.makeConstructor("ui-property",["selector","property","value"]);var setAttribute=Struct.makeConstructor("set-ui-attribute",["selector","attribute","value"]);var removeAttribute=Struct.makeConstructor("remove-ui-attribute",["selector","attribute"]);var setProperty=Struct.makeConstructor("set-ui-property",["selector","property","value"]);var removeProperty=Struct.makeConstructor("remove-ui-property",["selector","property"]);var locationHash=Struct.makeConstructor("locationHash",["value"]);var setLocationHash=Struct.makeConstructor("setLocationHash",["value"]);var moduleInstance=RandomID.randomId(16,true);var nextFragmentIdNumber=0;function newFragmentId(){return"ui_"+moduleInstance+"_"+nextFragmentIdNumber++}function spawnUIDriver(options){options=options||{};var globalEventProj=globalEvent(_$("selector"),_$("eventType"),__);Dataspace.spawn(new DemandMatcher([Patch.observe(globalEventProj)],[Patch.advertise(globalEventProj)],function(c){Dataspace.spawn(new GlobalEventSupply(c.selector,c.eventType))},{name:"globalEventSupervisor"}));var windowEventProj=windowEvent(_$("eventType"),__);Dataspace.spawn(new DemandMatcher([Patch.observe(windowEventProj)],[Patch.advertise(windowEventProj)],function(c){Dataspace.spawn(new WindowEventSupply(c.eventType))},{name:"windowEventSupervisor"}));Dataspace.spawn(new DemandMatcher([uiFragment(_$("fragmentId"),__,__,__)],[uiFragmentVersion(_$("fragmentId"),__)],function(c){Dataspace.spawn(new UIFragment(c.fragmentId))},{name:"uiFragmentSupervisor"}));Dataspace.spawn(new DemandMatcher([uiAttribute(_$("selector"),_$("attribute"),_$("value"))],[Patch.advertise(uiAttribute(_$("selector"),_$("attribute"),_$("value")))],function(c){Dataspace.spawn(new UIAttribute(c.selector,c.attribute,c.value,"attribute"))},{name:"uiAttributeSupervisor"}));Dataspace.spawn(new DemandMatcher([uiProperty(_$("selector"),_$("property"),_$("value"))],[Patch.advertise(uiProperty(_$("selector"),_$("property"),_$("value")))],function(c){Dataspace.spawn(new UIAttribute(c.selector,c.property,c.value,"property"))},{name:"uiPropertySupervisor"}));Dataspace.spawn(new AttributeUpdater);Dataspace.spawn(new LocationHashTracker(options.defaultLocationHash||"/"))}function GlobalEventSupply(selector,eventType){this.selector=selector;this.eventType=eventType;this.demandPat=Patch.observe(globalEvent(this.selector,this.eventType,__));this.name=["globalEvent",selector,eventType]}GlobalEventSupply.prototype.boot=function(){var self=this;this.handlerClosure=Dataspace.wrap(function(e){return self.handleDomEvent(e)});this.updateEventListeners(true);return Patch.sub(this.demandPat).andThen(Patch.sub(uiFragmentVersion(__,__))).andThen(Patch.pub(globalEvent(this.selector,this.eventType,__)))};GlobalEventSupply.prototype.updateEventListeners=function(install){selectorMatch(document,this.selector).forEach(eventUpdater(cleanEventType(this.eventType),this.handlerClosure,install))};GlobalEventSupply.prototype.trapexit=function(){console.log("GlobalEventSupply trapexit running",this.selector,this.eventType);this.updateEventListeners(false)};GlobalEventSupply.prototype.handleDomEvent=function(event){Dataspace.send(globalEvent(this.selector,this.eventType,event));return dealWithPreventDefault(this.eventType,event)};GlobalEventSupply.prototype.handleEvent=function(e){this.updateEventListeners(true);if(e.type==="stateChange"&&e.patch.project(this.demandPat).hasRemoved()){Dataspace.exit()}};function WindowEventSupply(eventType){this.eventType=eventType;this.demandPat=Patch.observe(windowEvent(this.eventType,__));this.name=["windowEvent",eventType]}WindowEventSupply.prototype.boot=function(){var self=this;this.handlerClosure=Dataspace.wrap(function(e){return self.handleDomEvent(e)});this.updateEventListeners(true);return Patch.sub(this.demandPat).andThen(Patch.pub(windowEvent(this.eventType,__)))};WindowEventSupply.prototype.updateEventListeners=function(install){if(install){window.addEventListener(cleanEventType(this.eventType),this.handlerClosure)}else{window.removeEventListener(cleanEventType(this.eventType),this.handlerClosure)}};WindowEventSupply.prototype.trapexit=function(){console.log("WindowEventSupply trapexit running",this.eventType);this.updateEventListeners(false)};WindowEventSupply.prototype.handleDomEvent=function(event){Dataspace.send(windowEvent(this.eventType,event));return dealWithPreventDefault(this.eventType,event)};WindowEventSupply.prototype.handleEvent=function(e){if(e.type==="stateChange"&&e.patch.project(this.demandPat).hasRemoved()){Dataspace.exit()}};function UIFragment(fragmentId){this.fragmentId=fragmentId;this.demandProj=uiFragment(this.fragmentId,_$("selector"),_$("html"),_$("orderBy"));this.eventDemandProj=Patch.observe(uiEvent(this.fragmentId,_$("selector"),_$("eventType"),__));this.currentAnchorNodes=[];this.currentSelector=null;this.currentHtml=null;this.currentOrderBy=null;this.currentEventRegistrations=Immutable.Map();this.name=["uiFragment",fragmentId]}UIFragment.prototype.boot=function(){return Patch.sub(Trie.projectionToPattern(this.demandProj)).andThen(Patch.sub(Trie.projectionToPattern(this.eventDemandProj)))};UIFragment.prototype.trapexit=function(){console.log("UIFragment trapexit running",this.fragmentId);this.updateContent(null,null,null)};var SYNDICATE_SORT_KEY="__syndicate_sort_key";function setSortKey(n,orderBy,fragmentId){var v=JSON.stringify([orderBy,fragmentId]);if("dataset"in n){n.dataset[SYNDICATE_SORT_KEY]=v}else{n[SYNDICATE_SORT_KEY]=v}}function getSortKey(n){if("dataset"in n&&n.dataset[SYNDICATE_SORT_KEY]){return JSON.parse(n.dataset[SYNDICATE_SORT_KEY])}if(n[SYNDICATE_SORT_KEY]){return JSON.parse(n[SYNDICATE_SORT_KEY])}return null}function hasSortKey(n,orderBy,fragmentId){var v=getSortKey(n);if(!v)return false;if(v[0]!==orderBy)return false;if(v[1]!==fragmentId)return false;return true}function firstChildNodeIndex_withSortKey(n){for(var i=0;i=0;i--){if(getSortKey(n.childNodes[i]))return i}return n.childNodes.length-1}function isGreaterThan(a,b){if(typeof a>typeof b)return true;if(typeof ab}function findInsertionPoint(n,orderBy,fragmentId){var lo=firstChildNodeIndex_withSortKey(n);var hi=lastChildNodeIndex_withSortKey(n)+1;while(lo>1;var probeSortKey=getSortKey(n.childNodes[probe]);if(isGreaterThan(probeSortKey[0],orderBy)||probeSortKey[0]===orderBy&&probeSortKey[1]>fragmentId){hi=probe}else{lo=probe+1}}if(lo="a"&&c<="z"){result=result+c;continue}if(c>="A"&&c<="Z"){result=result+c;continue}if(c>="0"&&c<="9"){result=result+c;continue}if(c==="."||c===":"){result=result+c;continue}c=c.charCodeAt(0);result=result+"_"+c+"_"}return result}function dealWithPreventDefault(eventType,event){var shouldPreventDefault=eventType.charAt(0)!=="+";if(shouldPreventDefault)event.preventDefault();return!shouldPreventDefault}function cleanEventType(eventType){return eventType.charAt(0)==="+"?eventType.slice(1):eventType}function selectorMatch(n,selector){if(n&&typeof n==="object"&&"querySelectorAll"in n){if(selector==="."){return[n]}else{return Array.prototype.slice.call(n.querySelectorAll(selector))}}else{return[]}}function eventUpdater(eventType,handlerClosure,install){return function(n){if(install){n.addEventListener(eventType,handlerClosure)}else{n.removeEventListener(eventType,handlerClosure)}}}function Anchor(explicitFragmentId){this.fragmentId=typeof explicitFragmentId==="undefined"?newFragmentId():explicitFragmentId;this.htmlPattern=uiFragment(this.fragmentId,__,__,__);this.eventPattern=uiEvent(this.fragmentId,__,__,__)}Anchor.prototype.context=function(){var extn=Array.prototype.slice.call(arguments).map(escapeDataAttributeName).join("__");return new Anchor(this.fragmentId+"__"+extn)};Anchor.prototype.html=function(selector,html,orderBy){return uiFragment(this.fragmentId,selector,html,typeof orderBy==="undefined"?null:orderBy)};Anchor.prototype.event=function(selector,eventType,event){return uiEvent(this.fragmentId,selector,eventType,event)};Anchor.prototype.fragmentVersion=function(v){return uiFragmentVersion(this.fragmentId,v)};function LocationHashTracker(defaultLocationHash){this.defaultLocationHash=defaultLocationHash;this.hashValue=null;this.name="LocationHashTracker"}LocationHashTracker.prototype.boot=function(){var self=this;this.loadHash();this.handlerClosure=Dataspace.wrap(function(e){self.handleDomEvent(e)});window.addEventListener("hashchange",this.handlerClosure);return Patch.assert(locationHash(this.hashValue)).andThen(Patch.sub(setLocationHash(__)))};LocationHashTracker.prototype.trapexit=function(){window.removeEventListener("hashchange",this.handlerClosure)};LocationHashTracker.prototype.loadHash=function(){this.hashValue=window.location.hash;if(this.hashValue.length&&this.hashValue[0]==="#"){this.hashValue=this.hashValue.slice(1)}if(!this.hashValue){this.hashValue=this.defaultLocationHash}};LocationHashTracker.prototype.handleDomEvent=function(e){this.loadHash();Dataspace.stateChange(Patch.retract(locationHash(__)).andThen(Patch.assert(locationHash(this.hashValue))))};LocationHashTracker.prototype.handleEvent=function(e){if(e.type==="message"&&setLocationHash.isClassOf(e.message)){window.location.hash=e.message[0]}};function AttributeUpdater(){this.name="AttributeUpdater"}AttributeUpdater.prototype.boot=function(){return Patch.sub(setAttribute(__,__,__)).andThen(Patch.sub(removeAttribute(__,__))).andThen(Patch.sub(setProperty(__,__,__))).andThen(Patch.sub(removeProperty(__,__)))};AttributeUpdater.prototype.handleEvent=function(e){if(e.type==="message"){var f=false;if(setAttribute.isClassOf(e.message)){f=function(n,k){n.setAttribute(k,e.message[2])}}else if(removeAttribute.isClassOf(e.message)){f=function(n,k){n.removeAttribute(k)}}else if(setProperty.isClassOf(e.message)){f=function(n,k){n[k]=e.message[2]}}else if(removeProperty.isClassOf(e.message)){f=function(n,k){delete n[k]}}if(f){selectorMatch(document,e.message[0]).forEach(function(n){f(n,e.message[1])})}}};module.exports.newFragmentId=newFragmentId;module.exports.spawnUIDriver=spawnUIDriver;module.exports.Anchor=Anchor;module.exports.globalEvent=globalEvent;module.exports.windowEvent=windowEvent;module.exports.uiEvent=uiEvent;module.exports.uiFragment=uiFragment;module.exports.uiFragmentVersion=uiFragmentVersion;module.exports.uiAttribute=uiAttribute;module.exports.uiProperty=uiProperty;module.exports.setAttribute=setAttribute;module.exports.removeAttribute=removeAttribute;module.exports.setProperty=setProperty;module.exports.removeProperty=removeProperty;module.exports.locationHash=locationHash;module.exports.setLocationHash=setLocationHash},{"./dataspace.js":233,"./demand-matcher.js":234,"./patch.js":239,"./randomid.js":240,"./struct.js":244,"./trie.js":246,immutable:227}],248:[function(require,module,exports){"use strict";var Reflect=require("./reflect.js");module.exports.extend=function(what,_with){for(var prop in _with){if(_with.hasOwnProperty(prop)){what[prop]=_with[prop]}}return what};module.exports.kwApply=function(f,thisArg,args){var formals=Reflect.formalParameters(f);var actuals=[];for(var i=0;ithis.period*1.5){Dataspace.send(wakeEvent())}this.mostRecentTrigger=now};module.exports.spawnWakeDetector=spawnWakeDetector;module.exports.WakeDetector=WakeDetector;module.exports.wakeEvent=wakeEvent},{"./dataspace.js":233,"./patch.js":239,"./struct.js":244}],250:[function(require,module,exports){var Ground=require("./ground.js").Ground;var Util=require("./util.js");var Codec=require("./codec.js");var Dataspace=require("./dataspace.js").Dataspace;var BuiltinWorker=typeof window!=="undefined"&&window.Worker;function Worker(scriptUrl){this.scriptUrl=scriptUrl;this.w=new BuiltinWorker(scriptUrl)}Worker.prototype.boot=function(){this.w.onmessage=Dataspace.wrap(function(e){console.log("Received from worker",JSON.stringify(e.data));Dataspace.enqueueAction(Codec.decodeAction(e.data))})};Worker.prototype.handleEvent=function(e){console.log("Sending to worker",JSON.stringify(Codec.encodeEvent(e)));this.w.postMessage(Codec.encodeEvent(e))};function WorkerGround(bootFn){var self=this;Ground.call(this,bootFn);onmessage=function(e){console.log("Received from main page",JSON.stringify(e.data));self.dataspace.handleEvent(Codec.decodeEvent(e.data));self.startStepping()}}WorkerGround.prototype=Util.extend({},Ground.prototype);WorkerGround.prototype.enqueueAction=function(pid,action){console.log("Sending to main page",JSON.stringify(Codec.encodeAction(action)));postMessage(Codec.encodeAction(action));console.log("Sent to main page")};module.exports.Worker=Worker;module.exports.WorkerGround=WorkerGround},{"./codec.js":231,"./dataspace.js":233,"./ground.js":235,"./util.js":248}]},{},[236])(236)});